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
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Orders/HBCISepaStandingOrderNewOrder.swift
1
5200
// // HBCISepaStandingOrderNewOrder.swift // HBCI4Swift // // Created by Frank Emminghaus on 16.05.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation public struct HBCISepaStandingOrderNewPar { public var maxUsage:Int; public var minPreDays:Int; public var maxPreDays:Int; public var cycleMonths:String; public var daysPerMonth:String; public var cycleWeeks:String? public var daysPerWeek:String? } open class HBCISepaStandingOrderNewOrder : HBCIOrder { var standingOrder:HBCIStandingOrder; public init?(message: HBCICustomMessage, order:HBCIStandingOrder) { self.standingOrder = order; super.init(name: "SepaStandingOrderNew", message: message); if self.segment == nil { return nil; } } open func enqueue() ->Bool { if !standingOrder.validate() { return false; } // check if order is supported if !user.parameters.isOrderSupportedForAccount(self, number: standingOrder.account.number, subNumber: standingOrder.account.subNumber) { logInfo(self.name + " is not supported for account " + standingOrder.account.number); return false; } // create SEPA data if let gen = HBCISepaGeneratorFactory.creditGenerator(self.user) { if let data = gen.documentForTransfer(standingOrder) { if let iban = standingOrder.account.iban, let bic = standingOrder.account.bic { var values:Dictionary<String,Any> = ["My.iban":iban, "My.bic":bic, "sepapain":data, "sepadescr":gen.sepaFormat.urn, "details.firstdate":standingOrder.startDate, "details.timeunit":standingOrder.cycleUnit == HBCIStandingOrderCycleUnit.monthly ? "M":"W", "details.turnus":standingOrder.cycle, "details.execday":standingOrder.executionDay ]; if let lastDate = standingOrder.lastDate { values["details.lastdate"] = lastDate; } if self.segment.setElementValues(values) { // add to dialog return msg.addOrder(self); } else { logInfo("Could not set values for Sepa Standing Order"); } } else { if standingOrder.account.iban == nil { logInfo("IBAN is missing for SEPA Standing Order"); } if standingOrder.account.bic == nil { logInfo("BIC is missing for SEPA Standing Order"); } } } } return false; } override open func updateResult(_ result:HBCIResultMessage) { super.updateResult(result); for segment in resultSegments { standingOrder.orderId = segment.elementValueForPath("orderid") as? String; } } open class func getParameters(_ user:HBCIUser) ->HBCISepaStandingOrderNewPar? { guard let (elem, seg) = self.getParameterElement(user, orderName: "SepaStandingOrderNew") else { return nil; } guard let maxUsage = elem.elementValueForPath("maxusage") as? Int else { logInfo("SepaStandingOrderNewParameter: mandatory parameter maxusage missing"); logInfo(seg.description); return nil; } guard let minPreDays = elem.elementValueForPath("minpretime") as? Int else { logInfo("SepaStandingOrderNewParameter: mandatory parameter minpretime missing"); logInfo(seg.description); return nil; } guard let maxPreDays = elem.elementValueForPath("maxpretime") as? Int else { logInfo("SepaStandingOrderNewParameter: mandatory parameter maxpretime missing"); logInfo(seg.description); return nil; } guard let cm = elem.elementValueForPath("turnusmonths") as? String else { logInfo("SepaStandingOrderNewParameter: mandatory parameter turnusmonths missing"); logInfo(seg.description); return nil; } guard let dpm = elem.elementValueForPath("dayspermonth") as? String else { logInfo("SepaStandingOrderNewParameter: mandatory parameter dayspermonth missing"); logInfo(seg.description); return nil; } let cw = elem.elementValueForPath("turnusweeks") as? String; let dpw = elem.elementValueForPath("daysperweek") as? String; return HBCISepaStandingOrderNewPar(maxUsage: maxUsage, minPreDays: minPreDays, maxPreDays: maxPreDays, cycleMonths: cm, daysPerMonth: dpm, cycleWeeks: cw, daysPerWeek: dpw); } }
gpl-2.0
8b79998a39f154581a9e6292ba43b1ed
42.333333
181
0.568462
4.744526
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/HBCIMT535Parser.swift
1
19351
// // HBCIMT535Parser.swift // HBCI4Swift // // Created by Frank Emminghaus on 11.05.21. // Copyright © 2021 Frank Emminghaus. All rights reserved. // import Foundation struct HBCIMT535Tag { let tag:String; let value:String; init(tag:String, value:String) { self.tag = tag; self.value = value; } } class HBCIMT535Parser { let mt535String:String; var tags = Array<HBCIMT535Tag>() init(_ mt535String:String) { var s = mt535String.replacingOccurrences(of:"\r\n", with: "\n"); if !s.hasPrefix("\n") { s = "\n"+s; } self.mt535String = s; } func getTagsFromString(_ mtString:String) throws ->Array<HBCIMT535Tag> { var residualRange: NSRange; var tags = Array<HBCIMT535Tag>(); residualRange = NSRange(location:0, length: mtString.count); do { let regex = try NSRegularExpression(pattern: "\n:...:|\n-", options: NSRegularExpression.Options.caseInsensitive) var range1 = regex.rangeOfFirstMatch(in: mtString, options: NSRegularExpression.MatchingOptions(), range: residualRange); while range1.location != NSNotFound { residualRange.location = range1.location+range1.length; residualRange.length = mtString.count-residualRange.location; let range2 = regex.rangeOfFirstMatch(in: mtString as String, options: NSRegularExpression.MatchingOptions(), range: residualRange); if range2.location != NSNotFound { var startIdx = mtString.index(mtString.startIndex, offsetBy: range1.location+2) var endIdx = mtString.index(mtString.startIndex, offsetBy: range1.location+range1.length-1) let tagString = String(mtString[startIdx..<endIdx]); startIdx = mtString.index(mtString.startIndex, offsetBy: residualRange.location); endIdx = mtString.index(mtString.startIndex, offsetBy: range2.location) let value = String(mtString[startIdx..<endIdx]); let tag = HBCIMT535Tag(tag: tagString, value: value); tags.append(tag); } range1 = range2; } } catch let err as NSError { logInfo("MT535Parse error: "+err.description); throw HBCIError.parseError; } return tags; } func parseASegment() ->HBCICustodyAccountBalance? { var pageNumber:Int? var accountNumber:String? var bankCode:String? var date:Date? var prepDate:Date? var exists:Bool? var balanceNumber:Int? var accountBalance:HBCICustodyAccountBalance! var idx=0; while idx < tags.count { if tags[idx].tag == "16R" && tags[idx].value.hasPrefix("GENL") { idx+=1; while idx < tags.count { let tag = tags[idx]; var val = tag.value; if tag.tag == "16S" && tag.value.hasPrefix("GENL") { break; } switch tag.tag { case "28E": if let indx = val.firstIndex(of: "/") { pageNumber = Int(val.prefix(upTo: indx)) } break; case "97A": val.removeFirst(7); if var indx = val.firstIndex(of: "/") { bankCode = String(val.prefix(upTo: indx)) indx = val.index(indx, offsetBy: 1) accountNumber = String(val.suffix(from: indx)) } break; case "98A": if val.hasPrefix(":PREP//") { val.removeFirst(7); prepDate = HBCIUtils.dateFormatter().date(from: val); if prepDate == nil { logInfo("MT535 Parse error: cannot parse preparation date from "+val); return nil; } } if val.hasPrefix(":STAT//") { val.removeFirst(7); date = HBCIUtils.dateFormatter().date(from: val); if date == nil { logInfo("MT535 Parse error: cannot parse posting date from "+val); return nil; } } break; case "98C": if val.hasPrefix(":PREP//") { val.removeFirst(7); prepDate = HBCIUtils.dateTimeFormatter().date(from: val); if prepDate == nil { logInfo("MT535 Parse error: cannot parse preparation date from "+val); return nil; } } if val.hasPrefix(":STAT//") { val.removeFirst(7); date = HBCIUtils.dateTimeFormatter().date(from: val); if date == nil { logInfo("MT535 Parse error: cannot parse posting date from "+val); return nil; } } break; case "17B": val.removeFirst(7); exists = (val=="Y"); break; case "13A": val.removeFirst(7); balanceNumber = Int(val); break; default: break; } idx+=1; } } else { idx += 1; } } if let date=date, let accountNumber=accountNumber, let bankCode=bankCode, let pageNumber=pageNumber, let exists=exists { accountBalance = HBCICustodyAccountBalance(pageNumber: pageNumber, date: date, accountNumber: accountNumber, bankCode: bankCode, exists: exists); } else { logInfo("MT535 Parse error: cannot parse header"); return nil; } accountBalance.balanceNumber = balanceNumber; return accountBalance; } func parseCSegment(balance: inout HBCICustodyAccountBalance) throws { var idx=0; while idx < tags.count { if tags[idx].tag == "16R" && tags[idx].value.hasPrefix("ADDINFO") { idx+=1; while idx < tags.count { let tag = tags[idx]; var val = tag.value; if tag.tag == "16S" && tag.value.hasPrefix("ADDINFO") { break; } switch tag.tag { case "19A": var negative = false; val.removeFirst(7); if val.hasPrefix("N") { negative = true; val.removeFirst(1); } let curr = String(val.prefix(3)); val.removeFirst(3); var totalValue = HBCIUtils.numberFormatter().number(from: val) as? NSDecimalNumber; if totalValue != nil && negative == true { totalValue = totalValue!.multiplying(by: NSDecimalNumber(-1)); } if let totalValue=totalValue { balance.depotValue = HBCIValue(value: totalValue, currency: curr); } else { logInfo("MT535 Parse error: cannot parse total value from "+val); throw HBCIError.parseError } break; default: break; } idx+=1; } } else { idx+=1; } } } func createInstrument(s: String) -> HBCICustodyAccountBalance.FinancialInstrument? { var isin:String? var wkn:String? var name = ""; var lines = s.split(separator: "\n"); if let idLine = lines.first { if idLine.hasPrefix("ISIN ") { isin = String(idLine.suffix(from: idLine.index(idLine.startIndex, offsetBy: 5))) } if idLine.hasPrefix("/DE/") { wkn = String(idLine.suffix(from: idLine.index(idLine.startIndex, offsetBy: 4))) } } lines.removeFirst(); if lines.count > 0 { let descrLine = lines[0]; if descrLine.hasPrefix("/DE/") { wkn = String(descrLine.suffix(from: descrLine.index(descrLine.startIndex, offsetBy: 4))) lines.removeFirst(); } } for line in lines { name = name + line + "\n"; } name = name.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines); if isin == nil && wkn == nil { return nil; } return HBCICustodyAccountBalance.FinancialInstrument(isin: isin, wkn: wkn, name: name); } func parse70E(s: String, instrument: inout HBCICustodyAccountBalance.FinancialInstrument) { let lines = s.split(separator: "\n"); for var line in lines { if line.hasPrefix("1") { line.removeFirst(1); instrument.depotCurrency = String(line.prefix(3)); } if line.hasPrefix("2") { line.removeFirst(1); let fields = line.split(separator: "+", maxSplits: 3, omittingEmptySubsequences: false); if fields.count > 1 && fields[0].count > 0 && fields[1].count > 0 { if let price = HBCIUtils.numberFormatter().number(from: String(fields[0])) as? NSDecimalNumber { instrument.startPrice = HBCIValue(value: price, currency: String(fields[1])); } else { logInfo("MT535 Parse error: cannot parse instrument price from "+String(fields[0])); } } if fields.count > 2 && fields[2].count > 0 { instrument.interestRate = HBCIUtils.numberFormatter().number(from: String(fields[2])) as? NSDecimalNumber; } } } } func parseB1Segment(balTags:Array<HBCIMT535Tag>) throws ->HBCICustodyAccountBalance.FinancialInstrument.SubBalance? { var idx=0; var qualifier:String var numberType:HBCICustodyAccountBalance.NumberType; var isAvailable:Bool while idx < balTags.count { let tag = balTags[idx]; var val = tag.value; switch tag.tag { case "93C": val.removeFirst(1); qualifier = String(val.prefix(4)); val.removeFirst(6); if val.hasPrefix("UNIT") { numberType = HBCICustodyAccountBalance.NumberType.pieces; } else { numberType = HBCICustodyAccountBalance.NumberType.values; } val.removeFirst(5); isAvailable = val.hasPrefix("AVAI"); val.removeFirst(5); var negative = false; if val.hasPrefix("N") { negative = true; val.removeFirst(1); } guard var balance = HBCIUtils.numberFormatter().number(from: val) as? NSDecimalNumber else { logInfo("MT535 Parse error: cannot parse balance from "+val); throw HBCIError.parseError; } if negative { balance = balance.multiplying(by: NSDecimalNumber(-1)); } return HBCICustodyAccountBalance.FinancialInstrument.SubBalance(balance: balance, qualifier: qualifier, numberType: numberType, isAvailable: isAvailable); default: break; } idx+=1; } return nil; } func parseSingleBSegment(segTags:Array<HBCIMT535Tag>) throws ->HBCICustodyAccountBalance.FinancialInstrument? { let firstTag = segTags[0]; if firstTag.tag != "35B" { return nil; } // process first tag to get basic instrument data guard var result = createInstrument(s: firstTag.value) else { return nil; } var idx=1; while idx < segTags.count { let tag = segTags[idx]; switch tag.tag { case "90B": var val = tag.value; val.removeFirst(12); result.currentPrice = HBCIValue(s: val); break; case "98A": var val = tag.value; val.removeFirst(7); result.priceDate = HBCIUtils.dateFormatter().date(from: val); break; case "98C": var val = tag.value; val.removeFirst(7); result.priceDate = HBCIUtils.dateTimeFormatter().date(from: val); break; case "93B": var val = tag.value; val.removeFirst(7); if val.hasPrefix("UNIT/") { result.numberType = HBCICustodyAccountBalance.NumberType.pieces; } else { result.numberType = HBCICustodyAccountBalance.NumberType.values; } val.removeFirst(5); var negative = false; if val.hasPrefix("N") { negative = true; val.removeFirst(1); } if let totalNumber = HBCIUtils.numberFormatter().number(from: val) as? NSDecimalNumber { result.totalNumber = totalNumber if negative { result.totalNumber = totalNumber.multiplying(by: NSDecimalNumber(-1)); } } else { logInfo("MT535 Parse error: cannot parse total number from "+val); throw HBCIError.parseError; } break; case "94B": var val = tag.value; val.removeFirst(7); result.priceLocation = val; break; case "19A": var val = tag.value; if val.hasPrefix(":HOLD") { val.removeFirst(7); var negative = false; if val.hasPrefix("N") { negative = true; val.removeFirst(1); } if var value = HBCIValue(s: val) { if negative { value = HBCIValue(value: value.value.multiplying(by: NSDecimalNumber(-1)), currency: value.currency); } result.depotValue = value; } else { logInfo("MT535 Parse error: cannot parse stock value from "+val); } } if val.hasPrefix(":ACRU") { val.removeFirst(7); var negative = false; if val.hasPrefix("N") { negative = true; val.removeFirst(1); } if var value = HBCIValue(s: val) { if negative { value = HBCIValue(value: value.value.multiplying(by: NSDecimalNumber(-1)), currency: value.currency); } result.accruedInterestValue = value; } else { logInfo("MT535 Parse error: cannot parse stock interest value from "+val); } } break; case "70E": var val = tag.value; if val.hasPrefix(":HOLD") { val.removeFirst(7); parse70E(s: val, instrument: &result); } case "16R": if tag.value.hasPrefix("SUBBAL") { idx+=1; var balTags = Array<HBCIMT535Tag>(); while idx < segTags.count { if segTags[idx].tag == "16S" && segTags[idx].value.hasPrefix("SUBBAL") { // parse B1 segments if let balance = try parseB1Segment(balTags: balTags) { result.balances.append(balance); } break; } else { balTags.append(segTags[idx]); idx+=1; } } } break; default: break; } idx+=1; } return result; } func parseBSegments(balance: inout HBCICustodyAccountBalance) throws { var idx=0; while idx < tags.count { if tags[idx].tag == "16R" && tags[idx].value.hasPrefix("FIN") { var segTags = Array<HBCIMT535Tag>(); idx+=1; while idx < tags.count { if tags[idx].tag == "16S" && tags[idx].value.hasPrefix("FIN") { idx += 1; break; } else { segTags.append(tags[idx]); idx += 1; } } // now parse single B segment if let segment = try parseSingleBSegment(segTags: segTags) { balance.instruments.append(segment); } } else { idx+=1; } } } func parse() -> HBCICustodyAccountBalance? { do { self.tags = try getTagsFromString(self.mt535String); guard var balance = parseASegment() else { logInfo("MT535 Parse error: cannot parse account balance string " + self.mt535String); return nil; } try parseBSegments(balance: &balance); try parseCSegment(balance: &balance); return balance; } catch { logInfo("MT535 Parse error: cannot parse tags from account balance string " + self.mt535String); } return nil; } }
gpl-2.0
49891963d5f8a098d822ace51f1f62b5
38.896907
170
0.452661
5.127186
false
false
false
false
tehprofessor/SwiftyFORM
Example/AppDelegate.swift
1
577
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let vc = FirstViewController() let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = UINavigationController(rootViewController: vc) window.tintColor = nil self.window = window window.makeKeyAndVisible() return true } }
mit
3fa88b54a9d33e3673983ac3085194d7
31.055556
125
0.778163
4.729508
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/WMFCaptchaResetter.swift
1
1938
public enum WMFCaptchaResetterError: LocalizedError { case cannotExtractCaptchaIndex case zeroLengthIndex public var errorDescription: String? { switch self { case .cannotExtractCaptchaIndex: return "Could not extract captcha index" case .zeroLengthIndex: return "Valid captcha reset index not obtained" } } } public typealias WMFCaptchaResetterResultBlock = (WMFCaptchaResetterResult) -> Void public struct WMFCaptchaResetterResult { var index: String init(index:String) { self.index = index } } public class WMFCaptchaResetter { private let manager = AFHTTPSessionManager.wmf_createDefault() public func isFetching() -> Bool { return manager.operationQueue.operationCount > 0 } public func resetCaptcha(siteURL: URL, success: @escaping WMFCaptchaResetterResultBlock, failure: @escaping WMFErrorHandler){ let manager = AFHTTPSessionManager(baseURL: siteURL) manager.responseSerializer = WMFApiJsonResponseSerializer.init(); let parameters = [ "action": "fancycaptchareload", "format": "json" ]; _ = manager.wmf_apiPOSTWithParameters(parameters, success: { (_, response) in guard let response = response as? [String : AnyObject], let fancycaptchareload = response["fancycaptchareload"] as? [String: Any], let index = fancycaptchareload["index"] as? String else { failure(WMFCaptchaResetterError.cannotExtractCaptchaIndex) return } guard index.count > 0 else { failure(WMFCaptchaResetterError.zeroLengthIndex) return } success(WMFCaptchaResetterResult.init(index: index)) }, failure: { (_, error) in failure(error) }) } }
mit
04f0a5c18277ab540f7dd5b46e9ba21e
34.236364
129
0.625387
5.060052
false
false
false
false
wesj/firefox-ios-1
SyncTests/DeferredTests.swift
1
1207
/* 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 Shared import XCTest // Trivial test for using Deferred. class DeferredTests: XCTestCase { func testDeferred() { let d = Deferred<Int>() XCTAssertNil(d.peek(), "Value not yet filled.") let expectation = expectationWithDescription("Waiting on value.") d.upon({ x in expectation.fulfill() }) d.fill(5) waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } XCTAssertEqual(5, d.peek()!, "Value is filled."); } func testMultipleUponBlocks() { let e1 = self.expectationWithDescription("First.") let e2 = self.expectationWithDescription("Second.") let d = Deferred<Int>() d.upon { x in XCTAssertEqual(x, 5) e1.fulfill() } d.upon { x in XCTAssertEqual(x, 5) e2.fulfill() } d.fill(5) waitForExpectationsWithTimeout(10, handler: nil) } }
mpl-2.0
5dd5f3da431278b934c5485748e76c24
27.069767
73
0.584093
4.373188
false
true
false
false
gxfeng/iOS-
NavigationController.swift
1
1588
// // NavigationViewController.swift // ProjectSwift // // Created by ZJQ on 2016/12/22. // Copyright © 2016年 ZJQ. All rights reserved. // import UIKit enum TabbarHideStyle { // 有动画 case tabbarHideWithAnimation // 无动画 case tabbarHideWithNoAnimation } class NavigationController: UINavigationController { var tabbarHideStyle = TabbarHideStyle.tabbarHideWithNoAnimation override func viewDidLoad() { super.viewDidLoad() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0 { let rootVC = self.viewControllers[0] // 是否添加动画 if tabbarHideStyle == TabbarHideStyle.tabbarHideWithAnimation { UIView.animate(withDuration: 0.35, animations: { rootVC.tabBarController?.tabBar.transform = CGAffineTransform(translationX: 0, y: 64) }) }else{ viewController.hidesBottomBarWhenPushed = true } } super.pushViewController(viewController, animated: true) } }
apache-2.0
5188390319f027147bfd379ac9e3ce9a
27.907407
105
0.639974
5.084691
false
false
false
false
megha14/Lets-Code-Them-Up
Learning-Swift/Learning Swift - Variables and Constants.playground/Contents.swift
1
514
/* Copyright (C) 2016 Megha Rastogi You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ import UIKit //Variables and Constants //Constants //Remove the comments //let firstName : String = "John" //firstName = "Dave" //Variables var firstName : String = "John" print(firstName) //Changing value of variable firstName = "Dave" //Another way of assigning values without using types var lastName = "Sanders" print(lastName)
gpl-3.0
9fc05790e7b51d27d3fb3bd5c7737f43
18.037037
132
0.735409
3.697842
false
false
false
false
nickoneill/Pantry
PantryExample/ViewController.swift
1
1427
// // ViewController.swift // StorageExample // // Created by Nick O'Neill on 11/4/15. // Copyright © 2015 That Thing in Swift. All rights reserved. // import UIKit import Pantry class ViewController: UIViewController { @IBOutlet var textField: UITextField! @IBOutlet var persistTextField: UITextField! { didSet { persistTextField.text = autopersist } } var autopersist: String? { set { if let newValue = newValue { Pantry.pack(newValue, key: "autopersist") persistTextField.text = newValue } } get { return Pantry.unpack("autopersist") } } @IBAction func saveText() { if let text = textField.text , !text.isEmpty { Pantry.pack(text, key: "saved_text") textField.text = "" print("Stored text") } } @IBAction func loadText() { if let unpackedText: String = Pantry.unpack("saved_text") { textField.text = unpackedText print("Loaded text") } } @IBAction func segmentTapped(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: autopersist = "first" case 1: autopersist = "second" case 2: autopersist = "third" default: break } } }
mit
ce2ba47510526e126e92ed64c6f86940
22.766667
67
0.542076
4.541401
false
false
false
false
srn214/Floral
Floral/Pods/CleanJSON/CleanJSON/Classes/_CleanJSONDecoder+SingleValueDecodingContainer.swift
1
7984
// // _CleanJSONDecoder+SingleValueDecodingContainer.swift // CleanJSON // // Created by Pircate([email protected]) on 2018/10/11 // Copyright © 2018 Pircate. All rights reserved. // import Foundation extension _CleanJSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods public func decodeNil() -> Bool { return storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { if let value = try unbox(storage.topContainer, as: Bool.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Bool.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Int.Type) throws -> Int { if let value = try unbox(storage.topContainer, as: Int.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Int.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Int8.Type) throws -> Int8 { if let value = try unbox(storage.topContainer, as: Int8.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Int8.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Int16.Type) throws -> Int16 { if let value = try unbox(storage.topContainer, as: Int16.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Int16.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Int32.Type) throws -> Int32 { if let value = try unbox(storage.topContainer, as: Int32.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Int32.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Int64.Type) throws -> Int64 { if let value = try unbox(storage.topContainer, as: Int64.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Int64.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: UInt.Type) throws -> UInt { if let value = try unbox(storage.topContainer, as: UInt.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return UInt.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: UInt8.Type) throws -> UInt8 { if let value = try unbox(storage.topContainer, as: UInt8.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return UInt8.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: UInt16.Type) throws -> UInt16 { if let value = try unbox(storage.topContainer, as: UInt16.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return UInt16.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: UInt32.Type) throws -> UInt32 { if let value = try unbox(storage.topContainer, as: UInt32.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return UInt32.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: UInt64.Type) throws -> UInt64 { if let value = try unbox(storage.topContainer, as: UInt64.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return UInt64.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Float.Type) throws -> Float { if let value = try unbox(storage.topContainer, as: Float.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Float.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: Double.Type) throws -> Double { if let value = try unbox(storage.topContainer, as: Double.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return Double.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode(_ type: String.Type) throws -> String { if let value = try unbox(storage.topContainer, as: String.self) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue: return String.defaultValue case .custom(let adapter): return try adapter.adapt(self) } } public func decode<T : Decodable>(_ type: T.Type) throws -> T { if type == Date.self || type == NSDate.self { return try decode(as: Date.self) as! T } else if type == Data.self || type == NSData.self { return try decode(as: Data.self) as! T } else if type == Decimal.self || type == NSDecimalNumber.self { return try decode(as: Decimal.self) as! T } if let value = try unbox(storage.topContainer, as: type) { return value } switch options.valueNotFoundDecodingStrategy { case .throw: throw DecodingError.Keyed.valueNotFound(type, codingPath: codingPath) case .useDefaultValue, .custom: return try decodeAsDefaultValue() } } }
mit
1ae9a4d63b2a825ff7fa4412d07a84ab
35.619266
88
0.615433
4.882569
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CognitoSync/CognitoSync_Shapes.swift
1
54125
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension CognitoSync { // MARK: Enums public enum BulkPublishStatus: String, CustomStringConvertible, Codable { case failed = "FAILED" case inProgress = "IN_PROGRESS" case notStarted = "NOT_STARTED" case succeeded = "SUCCEEDED" public var description: String { return self.rawValue } } public enum Operation: String, CustomStringConvertible, Codable { case remove case replace public var description: String { return self.rawValue } } public enum Platform: String, CustomStringConvertible, Codable { case adm = "ADM" case apns = "APNS" case apnsSandbox = "APNS_SANDBOX" case gcm = "GCM" public var description: String { return self.rawValue } } public enum StreamingStatus: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" public var description: String { return self.rawValue } } // MARK: Shapes public struct BulkPublishRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(identityPoolId: String) { self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct BulkPublishResponse: AWSDecodableShape { /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String? public init(identityPoolId: String? = nil) { self.identityPoolId = identityPoolId } private enum CodingKeys: String, CodingKey { case identityPoolId = "IdentityPoolId" } } public struct CognitoStreams: AWSEncodableShape & AWSDecodableShape { /// The ARN of the role Amazon Cognito can assume in order to publish to the stream. This role must grant access to Amazon Cognito (cognito-sync) to invoke PutRecord on your Cognito stream. public let roleArn: String? /// Status of the Cognito streams. Valid values are: ENABLED - Streaming of updates to identity pool is enabled. DISABLED - Streaming of updates to identity pool is disabled. Bulk publish will also fail if StreamingStatus is DISABLED. public let streamingStatus: StreamingStatus? /// The name of the Cognito stream to receive updates. This stream must be in the developers account and in the same region as the identity pool. public let streamName: String? public init(roleArn: String? = nil, streamingStatus: StreamingStatus? = nil, streamName: String? = nil) { self.roleArn = roleArn self.streamingStatus = streamingStatus self.streamName = streamName } public func validate(name: String) throws { try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws:iam::\\d+:role/.*") try self.validate(self.streamName, name: "streamName", parent: name, max: 128) try self.validate(self.streamName, name: "streamName", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case roleArn = "RoleArn" case streamingStatus = "StreamingStatus" case streamName = "StreamName" } } public struct Dataset: AWSDecodableShape { /// Date on which the dataset was created. public let creationDate: Date? /// A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot). public let datasetName: String? /// Total size in bytes of the records in this dataset. public let dataStorage: Int64? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String? /// The device that made the last change to this dataset. public let lastModifiedBy: String? /// Date when the dataset was last modified. public let lastModifiedDate: Date? /// Number of records in this dataset. public let numRecords: Int64? public init(creationDate: Date? = nil, datasetName: String? = nil, dataStorage: Int64? = nil, identityId: String? = nil, lastModifiedBy: String? = nil, lastModifiedDate: Date? = nil, numRecords: Int64? = nil) { self.creationDate = creationDate self.datasetName = datasetName self.dataStorage = dataStorage self.identityId = identityId self.lastModifiedBy = lastModifiedBy self.lastModifiedDate = lastModifiedDate self.numRecords = numRecords } private enum CodingKeys: String, CodingKey { case creationDate = "CreationDate" case datasetName = "DatasetName" case dataStorage = "DataStorage" case identityId = "IdentityId" case lastModifiedBy = "LastModifiedBy" case lastModifiedDate = "LastModifiedDate" case numRecords = "NumRecords" } } public struct DeleteDatasetRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot). public let datasetName: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(datasetName: String, identityId: String, identityPoolId: String) { self.datasetName = datasetName self.identityId = identityId self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct DeleteDatasetResponse: AWSDecodableShape { /// A collection of data for an identity pool. An identity pool can have multiple datasets. A dataset is per identity and can be general or associated with a particular entity in an application (like a saved game). Datasets are automatically created if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value pairs. public let dataset: Dataset? public init(dataset: Dataset? = nil) { self.dataset = dataset } private enum CodingKeys: String, CodingKey { case dataset = "Dataset" } } public struct DescribeDatasetRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot). public let datasetName: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(datasetName: String, identityId: String, identityPoolId: String) { self.datasetName = datasetName self.identityId = identityId self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeDatasetResponse: AWSDecodableShape { /// Meta data for a collection of data for an identity. An identity can have multiple datasets. A dataset can be general or associated with a particular entity in an application (like a saved game). Datasets are automatically created if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value pairs. public let dataset: Dataset? public init(dataset: Dataset? = nil) { self.dataset = dataset } private enum CodingKeys: String, CodingKey { case dataset = "Dataset" } } public struct DescribeIdentityPoolUsageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(identityPoolId: String) { self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeIdentityPoolUsageResponse: AWSDecodableShape { /// Information about the usage of the identity pool. public let identityPoolUsage: IdentityPoolUsage? public init(identityPoolUsage: IdentityPoolUsage? = nil) { self.identityPoolUsage = identityPoolUsage } private enum CodingKeys: String, CodingKey { case identityPoolUsage = "IdentityPoolUsage" } } public struct DescribeIdentityUsageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(identityId: String, identityPoolId: String) { self.identityId = identityId self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeIdentityUsageResponse: AWSDecodableShape { /// Usage information for the identity. public let identityUsage: IdentityUsage? public init(identityUsage: IdentityUsage? = nil) { self.identityUsage = identityUsage } private enum CodingKeys: String, CodingKey { case identityUsage = "IdentityUsage" } } public struct GetBulkPublishDetailsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String public init(identityPoolId: String) { self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct GetBulkPublishDetailsResponse: AWSDecodableShape { /// If BulkPublishStatus is SUCCEEDED, the time the last bulk publish operation completed. public let bulkPublishCompleteTime: Date? /// The date/time at which the last bulk publish was initiated. public let bulkPublishStartTime: Date? /// Status of the last bulk publish operation, valid values are: NOT_STARTED - No bulk publish has been requested for this identity pool IN_PROGRESS - Data is being published to the configured stream SUCCEEDED - All data for the identity pool has been published to the configured stream FAILED - Some portion of the data has failed to publish, check FailureMessage for the cause. public let bulkPublishStatus: BulkPublishStatus? /// If BulkPublishStatus is FAILED this field will contain the error message that caused the bulk publish to fail. public let failureMessage: String? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String? public init(bulkPublishCompleteTime: Date? = nil, bulkPublishStartTime: Date? = nil, bulkPublishStatus: BulkPublishStatus? = nil, failureMessage: String? = nil, identityPoolId: String? = nil) { self.bulkPublishCompleteTime = bulkPublishCompleteTime self.bulkPublishStartTime = bulkPublishStartTime self.bulkPublishStatus = bulkPublishStatus self.failureMessage = failureMessage self.identityPoolId = identityPoolId } private enum CodingKeys: String, CodingKey { case bulkPublishCompleteTime = "BulkPublishCompleteTime" case bulkPublishStartTime = "BulkPublishStartTime" case bulkPublishStatus = "BulkPublishStatus" case failureMessage = "FailureMessage" case identityPoolId = "IdentityPoolId" } } public struct GetCognitoEventsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// The Cognito Identity Pool ID for the request public let identityPoolId: String public init(identityPoolId: String) { self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct GetCognitoEventsResponse: AWSDecodableShape { /// The Cognito Events returned from the GetCognitoEvents request public let events: [String: String]? public init(events: [String: String]? = nil) { self.events = events } private enum CodingKeys: String, CodingKey { case events = "Events" } } public struct GetIdentityPoolConfigurationRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool for which to return a configuration. public let identityPoolId: String public init(identityPoolId: String) { self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct GetIdentityPoolConfigurationResponse: AWSDecodableShape { /// Options to apply to this identity pool for Amazon Cognito streams. public let cognitoStreams: CognitoStreams? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. public let identityPoolId: String? /// Options to apply to this identity pool for push synchronization. public let pushSync: PushSync? public init(cognitoStreams: CognitoStreams? = nil, identityPoolId: String? = nil, pushSync: PushSync? = nil) { self.cognitoStreams = cognitoStreams self.identityPoolId = identityPoolId self.pushSync = pushSync } private enum CodingKeys: String, CodingKey { case cognitoStreams = "CognitoStreams" case identityPoolId = "IdentityPoolId" case pushSync = "PushSync" } } public struct IdentityPoolUsage: AWSDecodableShape { /// Data storage information for the identity pool. public let dataStorage: Int64? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String? /// Date on which the identity pool was last modified. public let lastModifiedDate: Date? /// Number of sync sessions for the identity pool. public let syncSessionsCount: Int64? public init(dataStorage: Int64? = nil, identityPoolId: String? = nil, lastModifiedDate: Date? = nil, syncSessionsCount: Int64? = nil) { self.dataStorage = dataStorage self.identityPoolId = identityPoolId self.lastModifiedDate = lastModifiedDate self.syncSessionsCount = syncSessionsCount } private enum CodingKeys: String, CodingKey { case dataStorage = "DataStorage" case identityPoolId = "IdentityPoolId" case lastModifiedDate = "LastModifiedDate" case syncSessionsCount = "SyncSessionsCount" } } public struct IdentityUsage: AWSDecodableShape { /// Number of datasets for the identity. public let datasetCount: Int? /// Total data storage for this identity. public let dataStorage: Int64? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String? /// Date on which the identity was last modified. public let lastModifiedDate: Date? public init(datasetCount: Int? = nil, dataStorage: Int64? = nil, identityId: String? = nil, identityPoolId: String? = nil, lastModifiedDate: Date? = nil) { self.datasetCount = datasetCount self.dataStorage = dataStorage self.identityId = identityId self.identityPoolId = identityPoolId self.lastModifiedDate = lastModifiedDate } private enum CodingKeys: String, CodingKey { case datasetCount = "DatasetCount" case dataStorage = "DataStorage" case identityId = "IdentityId" case identityPoolId = "IdentityPoolId" case lastModifiedDate = "LastModifiedDate" } } public struct ListDatasetsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String /// The maximum number of results to be returned. public let maxResults: Int? /// A pagination token for obtaining the next page of results. public let nextToken: String? public init(identityId: String, identityPoolId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.identityId = identityId self.identityPoolId = identityPoolId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct ListDatasetsResponse: AWSDecodableShape { /// Number of datasets returned. public let count: Int? /// A set of datasets. public let datasets: [Dataset]? /// A pagination token for obtaining the next page of results. public let nextToken: String? public init(count: Int? = nil, datasets: [Dataset]? = nil, nextToken: String? = nil) { self.count = count self.datasets = datasets self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case count = "Count" case datasets = "Datasets" case nextToken = "NextToken" } } public struct ListIdentityPoolUsageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The maximum number of results to be returned. public let maxResults: Int? /// A pagination token for obtaining the next page of results. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: CodingKey {} } public struct ListIdentityPoolUsageResponse: AWSDecodableShape { /// Total number of identities for the identity pool. public let count: Int? /// Usage information for the identity pools. public let identityPoolUsages: [IdentityPoolUsage]? /// The maximum number of results to be returned. public let maxResults: Int? /// A pagination token for obtaining the next page of results. public let nextToken: String? public init(count: Int? = nil, identityPoolUsages: [IdentityPoolUsage]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.count = count self.identityPoolUsages = identityPoolUsages self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case count = "Count" case identityPoolUsages = "IdentityPoolUsages" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListRecordsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")), AWSMemberEncoding(label: "lastSyncCount", location: .querystring(locationName: "lastSyncCount")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "syncSessionToken", location: .querystring(locationName: "syncSessionToken")) ] /// A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot). public let datasetName: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String /// The last server sync count for this record. public let lastSyncCount: Int64? /// The maximum number of results to be returned. public let maxResults: Int? /// A pagination token for obtaining the next page of results. public let nextToken: String? /// A token containing a session ID, identity ID, and expiration. public let syncSessionToken: String? public init(datasetName: String, identityId: String, identityPoolId: String, lastSyncCount: Int64? = nil, maxResults: Int? = nil, nextToken: String? = nil, syncSessionToken: String? = nil) { self.datasetName = datasetName self.identityId = identityId self.identityPoolId = identityPoolId self.lastSyncCount = lastSyncCount self.maxResults = maxResults self.nextToken = nextToken self.syncSessionToken = syncSessionToken } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct ListRecordsResponse: AWSDecodableShape { /// Total number of records. public let count: Int? /// A boolean value specifying whether to delete the dataset locally. public let datasetDeletedAfterRequestedSyncCount: Bool? /// Indicates whether the dataset exists. public let datasetExists: Bool? /// Server sync count for this dataset. public let datasetSyncCount: Int64? /// The user/device that made the last change to this record. public let lastModifiedBy: String? /// Names of merged datasets. public let mergedDatasetNames: [String]? /// A pagination token for obtaining the next page of results. public let nextToken: String? /// A list of all records. public let records: [Record]? /// A token containing a session ID, identity ID, and expiration. public let syncSessionToken: String? public init(count: Int? = nil, datasetDeletedAfterRequestedSyncCount: Bool? = nil, datasetExists: Bool? = nil, datasetSyncCount: Int64? = nil, lastModifiedBy: String? = nil, mergedDatasetNames: [String]? = nil, nextToken: String? = nil, records: [Record]? = nil, syncSessionToken: String? = nil) { self.count = count self.datasetDeletedAfterRequestedSyncCount = datasetDeletedAfterRequestedSyncCount self.datasetExists = datasetExists self.datasetSyncCount = datasetSyncCount self.lastModifiedBy = lastModifiedBy self.mergedDatasetNames = mergedDatasetNames self.nextToken = nextToken self.records = records self.syncSessionToken = syncSessionToken } private enum CodingKeys: String, CodingKey { case count = "Count" case datasetDeletedAfterRequestedSyncCount = "DatasetDeletedAfterRequestedSyncCount" case datasetExists = "DatasetExists" case datasetSyncCount = "DatasetSyncCount" case lastModifiedBy = "LastModifiedBy" case mergedDatasetNames = "MergedDatasetNames" case nextToken = "NextToken" case records = "Records" case syncSessionToken = "SyncSessionToken" } } public struct PushSync: AWSEncodableShape & AWSDecodableShape { /// List of SNS platform application ARNs that could be used by clients. public let applicationArns: [String]? /// A role configured to allow Cognito to call SNS on behalf of the developer. public let roleArn: String? public init(applicationArns: [String]? = nil, roleArn: String? = nil) { self.applicationArns = applicationArns self.roleArn = roleArn } public func validate(name: String) throws { try self.applicationArns?.forEach { try validate($0, name: "applicationArns[]", parent: name, pattern: "arn:aws:sns:[-0-9a-z]+:\\d+:app/[A-Z_]+/[a-zA-Z0-9_.-]+") } try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws:iam::\\d+:role/.*") } private enum CodingKeys: String, CodingKey { case applicationArns = "ApplicationArns" case roleArn = "RoleArn" } } public struct Record: AWSDecodableShape { /// The last modified date of the client device. public let deviceLastModifiedDate: Date? /// The key for the record. public let key: String? /// The user/device that made the last change to this record. public let lastModifiedBy: String? /// The date on which the record was last modified. public let lastModifiedDate: Date? /// The server sync count for this record. public let syncCount: Int64? /// The value for the record. public let value: String? public init(deviceLastModifiedDate: Date? = nil, key: String? = nil, lastModifiedBy: String? = nil, lastModifiedDate: Date? = nil, syncCount: Int64? = nil, value: String? = nil) { self.deviceLastModifiedDate = deviceLastModifiedDate self.key = key self.lastModifiedBy = lastModifiedBy self.lastModifiedDate = lastModifiedDate self.syncCount = syncCount self.value = value } private enum CodingKeys: String, CodingKey { case deviceLastModifiedDate = "DeviceLastModifiedDate" case key = "Key" case lastModifiedBy = "LastModifiedBy" case lastModifiedDate = "LastModifiedDate" case syncCount = "SyncCount" case value = "Value" } } public struct RecordPatch: AWSEncodableShape { /// The last modified date of the client device. public let deviceLastModifiedDate: Date? /// The key associated with the record patch. public let key: String /// An operation, either replace or remove. public let op: Operation /// Last known server sync count for this record. Set to 0 if unknown. public let syncCount: Int64 /// The value associated with the record patch. public let value: String? public init(deviceLastModifiedDate: Date? = nil, key: String, op: Operation, syncCount: Int64, value: String? = nil) { self.deviceLastModifiedDate = deviceLastModifiedDate self.key = key self.op = op self.syncCount = syncCount self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 1024) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.value, name: "value", parent: name, max: 1_048_575) } private enum CodingKeys: String, CodingKey { case deviceLastModifiedDate = "DeviceLastModifiedDate" case key = "Key" case op = "Op" case syncCount = "SyncCount" case value = "Value" } } public struct RegisterDeviceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// The unique ID for this identity. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. Here, the ID of the pool that the identity belongs to. public let identityPoolId: String /// The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX). public let platform: Platform /// The push token. public let token: String public init(identityId: String, identityPoolId: String, platform: Platform, token: String) { self.identityId = identityId self.identityPoolId = identityPoolId self.platform = platform self.token = token } public func validate(name: String) throws { try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: String, CodingKey { case platform = "Platform" case token = "Token" } } public struct RegisterDeviceResponse: AWSDecodableShape { /// The unique ID generated for this device by Cognito. public let deviceId: String? public init(deviceId: String? = nil) { self.deviceId = deviceId } private enum CodingKeys: String, CodingKey { case deviceId = "DeviceId" } } public struct SetCognitoEventsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// The events to configure public let events: [String: String] /// The Cognito Identity Pool to use when configuring Cognito Events public let identityPoolId: String public init(events: [String: String], identityPoolId: String) { self.events = events self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: String, CodingKey { case events = "Events" } } public struct SetIdentityPoolConfigurationRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// Options to apply to this identity pool for Amazon Cognito streams. public let cognitoStreams: CognitoStreams? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool to modify. public let identityPoolId: String /// Options to apply to this identity pool for push synchronization. public let pushSync: PushSync? public init(cognitoStreams: CognitoStreams? = nil, identityPoolId: String, pushSync: PushSync? = nil) { self.cognitoStreams = cognitoStreams self.identityPoolId = identityPoolId self.pushSync = pushSync } public func validate(name: String) throws { try self.cognitoStreams?.validate(name: "\(name).cognitoStreams") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.pushSync?.validate(name: "\(name).pushSync") } private enum CodingKeys: String, CodingKey { case cognitoStreams = "CognitoStreams" case pushSync = "PushSync" } } public struct SetIdentityPoolConfigurationResponse: AWSDecodableShape { /// Options to apply to this identity pool for Amazon Cognito streams. public let cognitoStreams: CognitoStreams? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. public let identityPoolId: String? /// Options to apply to this identity pool for push synchronization. public let pushSync: PushSync? public init(cognitoStreams: CognitoStreams? = nil, identityPoolId: String? = nil, pushSync: PushSync? = nil) { self.cognitoStreams = cognitoStreams self.identityPoolId = identityPoolId self.pushSync = pushSync } private enum CodingKeys: String, CodingKey { case cognitoStreams = "CognitoStreams" case identityPoolId = "IdentityPoolId" case pushSync = "PushSync" } } public struct SubscribeToDatasetRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "deviceId", location: .uri(locationName: "DeviceId")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// The name of the dataset to subcribe to. public let datasetName: String /// The unique ID generated for this device by Cognito. public let deviceId: String /// Unique ID for this identity. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which the identity belongs. public let identityPoolId: String public init(datasetName: String, deviceId: String, identityId: String, identityPoolId: String) { self.datasetName = datasetName self.deviceId = deviceId self.identityId = identityId self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.deviceId, name: "deviceId", parent: name, max: 256) try self.validate(self.deviceId, name: "deviceId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct SubscribeToDatasetResponse: AWSDecodableShape { public init() {} } public struct UnsubscribeFromDatasetRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "deviceId", location: .uri(locationName: "DeviceId")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// The name of the dataset from which to unsubcribe. public let datasetName: String /// The unique ID generated for this device by Cognito. public let deviceId: String /// Unique ID for this identity. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which this identity belongs. public let identityPoolId: String public init(datasetName: String, deviceId: String, identityId: String, identityPoolId: String) { self.datasetName = datasetName self.deviceId = deviceId self.identityId = identityId self.identityPoolId = identityPoolId } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.deviceId, name: "deviceId", parent: name, max: 256) try self.validate(self.deviceId, name: "deviceId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") } private enum CodingKeys: CodingKey {} } public struct UnsubscribeFromDatasetResponse: AWSDecodableShape { public init() {} } public struct UpdateRecordsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "clientContext", location: .header(locationName: "x-amz-Client-Context")), AWSMemberEncoding(label: "datasetName", location: .uri(locationName: "DatasetName")), AWSMemberEncoding(label: "identityId", location: .uri(locationName: "IdentityId")), AWSMemberEncoding(label: "identityPoolId", location: .uri(locationName: "IdentityPoolId")) ] /// Intended to supply a device ID that will populate the lastModifiedBy field referenced in other methods. The ClientContext field is not yet implemented. public let clientContext: String? /// A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot). public let datasetName: String /// The unique ID generated for this device by Cognito. public let deviceId: String? /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityId: String /// A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region. public let identityPoolId: String /// A list of patch operations. public let recordPatches: [RecordPatch]? /// The SyncSessionToken returned by a previous call to ListRecords for this dataset and identity. public let syncSessionToken: String public init(clientContext: String? = nil, datasetName: String, deviceId: String? = nil, identityId: String, identityPoolId: String, recordPatches: [RecordPatch]? = nil, syncSessionToken: String) { self.clientContext = clientContext self.datasetName = datasetName self.deviceId = deviceId self.identityId = identityId self.identityPoolId = identityPoolId self.recordPatches = recordPatches self.syncSessionToken = syncSessionToken } public func validate(name: String) throws { try self.validate(self.datasetName, name: "datasetName", parent: name, max: 128) try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1) try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "[a-zA-Z0-9_.:-]+") try self.validate(self.deviceId, name: "deviceId", parent: name, max: 256) try self.validate(self.deviceId, name: "deviceId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, max: 55) try self.validate(self.identityId, name: "identityId", parent: name, min: 1) try self.validate(self.identityId, name: "identityId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try self.validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try self.recordPatches?.forEach { try $0.validate(name: "\(name).recordPatches[]") } } private enum CodingKeys: String, CodingKey { case deviceId = "DeviceId" case recordPatches = "RecordPatches" case syncSessionToken = "SyncSessionToken" } } public struct UpdateRecordsResponse: AWSDecodableShape { /// A list of records that have been updated. public let records: [Record]? public init(records: [Record]? = nil) { self.records = records } private enum CodingKeys: String, CodingKey { case records = "Records" } } }
apache-2.0
1a49d7b239a60b1d51a3b97491f83d22
48.976916
387
0.647021
4.498795
false
false
false
false
wanliming11/MurlocAlgorithms
Last/Algorithms/CountOccurs/CountOccurs/CountOccurs/CountOccurs.swift
1
1148
// // Created by FlyingPuPu on 09/12/2016. // Copyright (c) 2016 FlyingPuPu. All rights reserved. // import Foundation public func countOccursBinarySearch<T: Comparable>(_ array: [T], key: T) -> Int { func findLeft() -> Int { var left: Int = 0 var right: Int = array.count var middle: Int = 0 while left < right { middle = left + (right - left) / 2 if array[middle] > key { left = middle + 1 } else { right = middle } print("Find left during <\(left)>--<\(array[middle])>--<\(right)>") } return left } func findRight() -> Int { var left: Int = 0 var right: Int = array.count var middle: Int = 0 while left < right { middle = left + (right - left) / 2 if array[middle] > key { right = middle } else { left = middle + 1 } print("Find right during <\(left)>--<\(array[middle])>--<\(right)>") } return left } return findRight() - findLeft() }
mit
c34d8c2a50e3e2ae9b5a6d4a9262367b
23.425532
81
0.468641
4.174545
false
false
false
false
xwu/swift
test/SILGen/import_as_member.swift
13
2966
// RUN: %target-swift-emit-silgen -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s // REQUIRES: objc_interop import ImportAsMember.A import ImportAsMember.Class import Foundation public func returnGlobalVar() -> Double { return Struct1.globalVar } // CHECK-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double { // CHECK: %0 = global_addr @IAMStruct1GlobalVar : $*Double // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] %0 : $*Double // CHECK: [[VAL:%.*]] = load [trivial] [[READ]] : $*Double // CHECK: return [[VAL]] : $Double // CHECK-NEXT: } // N.B. Whether by design or due to a bug, nullable NSString globals // still import as non-null. public func returnStringGlobalVar() -> String { return Panda.cutenessFactor } // CHECK-LABEL: sil [ossa] {{.*}}returnStringGlobalVar{{.*}} () -> @owned String { // CHECK: %0 = global_addr @PKPandaCutenessFactor : $*NSString // CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString // CHECK: [[BRIDGE:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // CHECK: [[RESULT:%.*]] = apply [[BRIDGE]]( // CHECK: return [[RESULT]] : $String // CHECK-NEXT: } public func returnNullableStringGlobalVar() -> String? { return Panda.cuddlynessFactor } // CHECK-LABEL: sil [ossa] {{.*}}returnNullableStringGlobalVar{{.*}} () -> @owned Optional<String> { // CHECK: %0 = global_addr @PKPandaCuddlynessFactor : $*NSString // CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString // CHECK: [[BRIDGE:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // CHECK: [[RESULT:%.*]] = apply [[BRIDGE]]( // CHECK: [[SOME:%.*]] = enum $Optional<String>, #Optional.some!enumelt, [[RESULT]] // CHECK: return [[SOME]] : $Optional<String> // CHECK-NEXT: } // CHECK-LABEL: sil {{.*}}useClass{{.*}} // CHECK: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options): public func useClass(d: Double, opts: SomeClass.Options) { // CHECK: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass // CHECK: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]]) let o = SomeClass(value: d) // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> () // CHECK: apply [[APPLY_FN]]([[BORROWED_OBJ]], [[OPTS]]) // CHECK: end_borrow [[BORROWED_OBJ]] // CHECK: destroy_value [[OBJ]] o.applyOptions(opts) } extension SomeClass { // CHECK-LABEL: sil hidden [ossa] @$sSo12IAMSomeClassC16import_as_memberE6doubleABSd_tcfC // CHECK: bb0([[DOUBLE:%[0-9]+]] : $Double // CHECK-NOT: value_metatype // CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // CHECK: apply [[FNREF]]([[DOUBLE]]) convenience init(double: Double) { self.init(value: double) } } public func useSpecialInit() -> Struct1 { return Struct1(specialLabel:()) }
apache-2.0
5e478c2d63fdc967dc727a89a1ab8734
40.774648
128
0.641942
3.493522
false
false
false
false
xwu/swift
test/SILGen/local_recursion.swift
7
5649
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s15local_recursionAA_1yySi_SitF : $@convention(thin) (Int, Int) -> () { // CHECK: bb0([[X:%0]] : $Int, [[Y:%1]] : $Int): func local_recursion(_ x: Int, y: Int) { func self_recursive(_ a: Int) { self_recursive(x + a) } // Invoke local functions by passing all their captures. // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@\$s15local_recursionAA_1yySi_SitF14self_recursiveL_yySiF]] // CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]]) self_recursive(x) // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[SELF_RECURSIVE_REF]]([[X]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let sr = self_recursive // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[Y]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] sr(y) func mutually_recursive_1(_ a: Int) { mutually_recursive_2(x + a) } func mutually_recursive_2(_ b: Int) { mutually_recursive_1(y + b) } // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_1L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]]) mutually_recursive_1(x) // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] _ = mutually_recursive_1 func transitive_capture_1(_ a: Int) -> Int { return x + a } func transitive_capture_2(_ b: Int) -> Int { return transitive_capture_1(y + b) } // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_2L_yS2iF]] // CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]]) transitive_capture_2(x) // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[TRANS_CAPTURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let tc = transitive_capture_2 // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] tc(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySiXEfU_ // CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]]) let _: Void = { self_recursive($0) transitive_capture_2($0) }(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySicfU0_ // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] let f: (Int) -> () = { self_recursive($0) transitive_capture_2($0) } f(x) } // CHECK: sil private [ossa] [[SELF_RECURSIVE]] : // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]] : // CHECK: apply [[SELF_REF]]({{.*}}, [[X]]) // CHECK: sil private [ossa] [[MUTUALLY_RECURSIVE_1]] // CHECK: bb0([[A:%0]] : $Int, [[Y:%1]] : $Int, [[X:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_2L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]]) // CHECK: sil private [ossa] [[MUTUALLY_RECURSIVE_2]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]]) // CHECK: sil private [ossa] [[TRANS_CAPTURE_1:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_1L_yS2iF]] // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: sil private [ossa] [[TRANS_CAPTURE]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]] // CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]]) func plus<T>(_ x: T, _ y: T) -> T { return x } func toggle<T, U>(_ x: T, _ y: U) -> U { return y } func generic_local_recursion<T, U>(_ x: T, y: U) { func self_recursive(_ a: T) { self_recursive(plus(x, a)) } self_recursive(x) _ = self_recursive func transitive_capture_1(_ a: T) -> U { return toggle(a, y) } func transitive_capture_2(_ b: U) -> U { return transitive_capture_1(toggle(b, x)) } transitive_capture_2(y) _ = transitive_capture_2 func no_captures() {} no_captures() _ = no_captures func transitive_no_captures() { no_captures() } transitive_no_captures() _ = transitive_no_captures } func local_properties(_ x: Int, y: Int) -> Int { var self_recursive: Int { return x + self_recursive } var transitive_capture_1: Int { return x } var transitive_capture_2: Int { return transitive_capture_1 + y } func transitive_capture_fn() -> Int { return transitive_capture_2 } return self_recursive + transitive_capture_fn() }
apache-2.0
b46dc3376bedad17dca164c1dfdf9140
34.086957
146
0.591078
3.043642
false
false
false
false
ReactiveX/RxSwift
RxSwift/Disposables/SingleAssignmentDisposable.swift
2
2337
// // SingleAssignmentDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /** Represents a disposable resource which only allows a single assignment of its underlying disposable resource. If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. */ public final class SingleAssignmentDisposable : DisposeBase, Cancelable { private struct DisposeState: OptionSet { let rawValue: Int32 static let disposed = DisposeState(rawValue: 1 << 0) static let disposableSet = DisposeState(rawValue: 1 << 1) } // state private let state = AtomicInt(0) private var disposable = nil as Disposable? /// - returns: A value that indicates whether the object is disposed. public var isDisposed: Bool { isFlagSet(self.state, DisposeState.disposed.rawValue) } /// Initializes a new instance of the `SingleAssignmentDisposable`. public override init() { super.init() } /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. /// /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** public func setDisposable(_ disposable: Disposable) { self.disposable = disposable let previousState = fetchOr(self.state, DisposeState.disposableSet.rawValue) if (previousState & DisposeState.disposableSet.rawValue) != 0 { rxFatalError("oldState.disposable != nil") } if (previousState & DisposeState.disposed.rawValue) != 0 { disposable.dispose() self.disposable = nil } } /// Disposes the underlying disposable. public func dispose() { let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) if (previousState & DisposeState.disposed.rawValue) != 0 { return } if (previousState & DisposeState.disposableSet.rawValue) != 0 { guard let disposable = self.disposable else { rxFatalError("Disposable not set") } disposable.dispose() self.disposable = nil } } }
mit
691ff93383be52c82c70338237518918
31.444444
141
0.660103
5.134066
false
false
false
false
michaelcordero/CoreDataStructures
Sources/CoreDataStructures/Tree.swift
1
3395
// // Tree.swift // CoreDataStructures // // Created by Michael Cordero on 1/2/21. // import Foundation protocol Tree { /*common operations*/ associatedtype T : Comparable func get(_ value: T) -> Node<T>? func set(_ node: Node<T>, value: T) throws -> T? func put(_ value: T) throws -> Void func remove(_ value: T) throws -> Node<T>? func isEmpty() -> Bool func all() -> [Node<T>] func values() -> [T] func all(_ order: TreeOrder ) -> [Node<T>] func values(_ order: TreeOrder ) -> [T] func contains(_ value: T) -> Bool /*computed properties*/ var size: Int { get } var root: Node<T>? { get set } var max: Node<T>? { get } var min: Node<T>? { get } /*algorithms*/ func depth(_ value: T) -> Int func height(_ value: T) -> Int func preorder( operation: ( Node<T> ) -> Void ) -> Void func postorder( operation: ( Node<T> ) -> Void ) -> Void func inorder( operation: ( Node<T> ) -> Void ) -> Void } // MARK: - Error /** Custom error enum to notify users what went wrong. */ public enum TreeError: Error { case DuplicateValueError case InvalidNodeError case NilRootError } /*OrderEnum*/ public enum TreeOrder { case Preorder case Postorder case Inorder } open class Node<T: Comparable>: Equatable { var value: T? var left: Node<T>? var right: Node<T>? var parent: Node<T>? // MARK: - Node Constructor(s) public init() { self.value = nil self.left = nil self.right = nil self.parent = nil } public init(value: T?) { self.value = value self.left = nil self.right = nil self.parent = nil } public init(value: T?, left: Node<T>?, right: Node<T>?) { self.value = value self.left = left self.right = right self.parent = nil } public init(value: T?, left: Node<T>?, right: Node<T>?, parent: Node<T>?) { self.value = value self.left = left self.right = right self.parent = parent } // MARK: - Protocol Conformance public static func == (lhs: Node<T>, rhs: Node<T>) -> Bool { // return lhs.value == rhs.value && lhs.parent == rhs.parent && lhs.left == rhs.left && lhs.right == rhs.right if lhs.value == nil && rhs.value != nil { return false } else if rhs.value == nil && lhs.value != nil { return false } return lhs.value! == rhs.value! } static func > (lhs: Node<T>, rhs: Node<T>) -> Bool{ return lhs.value! > rhs.value! } static func < (lhs: Node<T>, rhs: Node<T>) -> Bool { return lhs.value! < rhs.value! } // MARK: - Public API func isParent() -> Bool { return left != nil || right != nil } func isChild() -> Bool { return parent != nil } func isRoot() -> Bool { return parent == nil } func isLeaf() -> Bool { return left == nil && right == nil } } extension Node : CustomDebugStringConvertible { public var debugDescription: String { var description: String = "Node[ Key:\(String(describing: self.value))" description += "Left: \(String(describing: self.left)), " description += "Right: \(String(describing: self.right)), " description += " ]" return description } }
mit
c386a311d374c5cfebfd6381e8a65082
26.16
117
0.552577
3.747241
false
false
false
false
kingcos/Swift-X-Algorithms
LeetCode/007-Reverse-Integer/007-Reverse-Integer.playground/Contents.swift
1
360
import UIKit class Solution { // 12 ms func reverse(_ x: Int) -> Int { var x = x var result = 0 while x != 0 { result *= 10 result += x % 10 x /= 10 } guard result <= Int32.max && result >= Int32.min else { return 0 } return result } }
mit
d42ed637002e70ba15548ae4715691fc
17.947368
74
0.4
4.390244
false
false
false
false
sudeepunnikrishnan/ios-sdk
Instamojo/Order.swift
1
13448
// // Order.swift // Instamojo // // Created by Sukanya Raj on 14/02/17. // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit public class Order: NSObject { public var id: String? public var transactionID: String? public var buyerName: String? public var buyerEmail: String? public var buyerPhone: String? public var amount: String? public var orderDescription: String? public var currency: String? public var redirectionUrl: String? public var webhook: String? public var mode: String? public var authToken: String? public var resourceURI: String? public var clientID: String? public var cardOptions: CardOptions! public var netBankingOptions: NetBankingOptions! public var emiOptions: EMIOptions! public var walletOptions: WalletOptions! public var upiOptions: UPIOptions! override init() {} public init(authToken: String, transactionID: String, buyerName: String, buyerEmail: String, buyerPhone: String, amount: String, description: String, webhook: String ) { self.authToken = authToken self.transactionID = transactionID self.buyerName = buyerName self.buyerEmail = buyerEmail self.buyerPhone = buyerPhone self.amount = amount self.currency = "INR" self.mode = "IOS_SDK" self.redirectionUrl = Urls.getDefaultRedirectUrl() self.orderDescription = description self.webhook = webhook if Urls.getBaseUrl().contains("test") { self.clientID = Constants.TestClientId } else { self.clientID = Constants.ProdClientId } } public func isValid() -> (validity: Bool, error: String) { let space = "," return (isValidName().validity && isValidEmail().validity && isValidPhone().validity && isValidAmount().validity && isValidWebhook().validity && isValidDescription().validity && isValidTransactionID().validity, isValidName().error + space + isValidEmail().error + space + isValidPhone().error + space + isValidAmount().error + space + isValidWebhook().error + space + isValidTransactionID().error) } public func isValid() -> Bool { return isValidName().validity && isValidEmail().validity && isValidPhone().validity && isValidAmount().validity && isValidWebhook().validity && isValidDescription().validity && isValidRedirectURL().validity && isValidTransactionID().validity } /** * @return false if the buyer name is empty or has greater than 100 characters. Else true. */ public func isValidName() -> (validity: Bool, error: String) { if (self.buyerName?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if ((self.buyerName?.characters.count)! > 100) { return (false, "The buyer name is greater than 100 characters") } else { return (true, "Valid Name") } } //Tuples are not supported by Objective-C public func isValidName() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerName?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if ((self.buyerName?.characters.count)! > 100) { dictonary.setValue("The buyer name is greater than 100 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Name", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the buyer email is empty or has greater than 75 characters. Else true. */ public func isValidEmail() -> (validity: Bool, error: String) { if (self.buyerEmail?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if (self.buyerEmail?.characters.count)! > 75 { return (false, "The buyer email is greater than 75 characters") } else if !validateEmail(email: self.buyerEmail!) { return (false, "Invalid Email") } else { return (true, "Valid Email") } } public func isValidEmail() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerEmail?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.buyerEmail?.characters.count)! > 75 { dictonary.setValue("The buyer email is greater than 75 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if !validateEmail(email: self.buyerEmail!) { dictonary.setValue("Invalid Email", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Email", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } func validateEmail(email: String) -> Bool { let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat) return emailPredicate.evaluate(with: email) } /** * @return false if the phone number is empty. Else true. */ public func isValidPhone() -> (validity: Bool, error: String) { if (self.buyerPhone?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else { return (true, "Valid Phone Number") } } public func isValidPhone() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerPhone?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Phone Number", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the amount is empty or less than Rs. 9 or has more than 2 decimal places. */ public func isValidAmount() -> (validity: Bool, error: String) { if (self.amount?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else { let amountArray = self.amount?.components(separatedBy: ".") if amountArray?.count != 2 { return (false, "Invalid Amount") } else { let amount = Int((amountArray?[0])!) if amount! < 9 { return (false, "Invalid Amount") } else { return (true, "Valid Amount") } } } } public func isValidAmount() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.amount?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { let amountArray = self.amount?.components(separatedBy: ".") if amountArray?.count != 2 { dictonary.setValue("Invalid Amount", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { let amount = Int((amountArray?[0])!) if amount! < 9 { dictonary.setValue("Invalid Amount", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Amount", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } } } /** * @return false if the description is empty or has greater than 255 characters. Else true. */ public func isValidDescription()-> (validity: Bool, error: String) { if (self.orderDescription?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if (self.orderDescription?.characters.count)! > 255 { return (true, "Description is greater than 255 characters") } else { return (true, "Valid Description") } } public func isValidDescription() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.orderDescription?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.orderDescription?.characters.count)! > 255 { dictonary.setValue("Description is greater than 255 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Description", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the transaction ID is empty or has greater than 64 characters. */ public func isValidTransactionID() -> (validity: Bool, error: String) { if (self.transactionID?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Transaction ID is a mandatory parameter") } else if (self.transactionID?.characters.count)! > 64 { return (true, "Transaction ID is greater than 64 characters") } else { return (true, "Valid Transaction ID") } } public func isValidTransactionID() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.transactionID?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Transaction ID is a mandatory parameter", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.transactionID?.characters.count)! > 64 { dictonary.setValue("Transaction ID is greater than 64 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Transaction ID", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the redirection URL is empty or contains any query parameters. */ public func isValidRedirectURL() -> (validity: Bool, error: String) { if (self.redirectionUrl?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (true, "Invalid Redirection URL") } else if !isValidURL(urlString: (self.redirectionUrl)!) { return (true, "Invalid Redirection URL") } else { return (true, "Valid Redirection URL") } } public func isValidRedirectURL() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.redirectionUrl?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Invalid Redirection URL", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if !isValidURL(urlString: (self.redirectionUrl)!) { dictonary.setValue("Invalid Redirection URL", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Redirection URL", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if webhook is set and not a valid url or has query parameters */ public func isValidWebhook() -> (validity: Bool, error: String) { if (self.webhook?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Webhook is a mandatory parameter.") } else { return (true, "Valid Webhook") } } public func isValidWebhook() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.webhook?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Webhook is a mandatory parameter.", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Webhook", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } public func isValidURL(urlString: String) -> Bool { let url: NSURL = NSURL(string: urlString)! if url.query != nil { return false } else { return true } } }
lgpl-3.0
444ef1d8b254391ef18622b6c1524bba
39.381381
406
0.600059
4.686999
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Component/alert.swift
1
1216
// // alert.swift // Pods // // Created by 王小涛 on 2017/7/7. // // import Foundation public func showAlert(in controller: UIViewController, title: String? = nil, message: String? = nil, items: [String], selected: ((String, Int) -> Void)? = nil) { let sheet = UIAlertController(title: title, message: message, preferredStyle: .alert) items.enumerated().forEach { value in let action = UIAlertAction(title: value.element, style: .default, handler: { _ in selected?(value.element, value.offset) }) sheet.addAction(action) } controller.present(sheet, animated: true, completion: nil) } public func showActionSheet(in controller: UIViewController, title: String? = nil, message: String? = nil, items: [String], selected: ((String, Int) -> Void)? = nil) { let sheet = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) items.enumerated().forEach { value in let action = UIAlertAction(title: value.element, style: .default, handler: { _ in selected?(value.element, value.offset) }) sheet.addAction(action) } controller.present(sheet, animated: true, completion: nil) }
mit
b3f38a84cb291a3525e95a50d54451d9
35.666667
167
0.657851
3.993399
false
false
false
false
qiuncheng/for-graduation
SpeechRecognition/Helper/MBProgressHUD+Speech.swift
1
938
// // Speech.swift // SpeechRecognition // // Created by yolo on 2017/4/1. // Copyright © 2017年 Qiun Cheng. All rights reserved. // protocol HUDAble { } extension HUDAble where Self: UIViewController { func showHUD(in view: UIView, title: String, duration: TimeInterval) { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.animationType = .fade hud.mode = .customView hud.label.text = title hud.hide(animated: true, afterDelay: 0.75) } @discardableResult func showHUD(in view: UIView, title: String) -> MBProgressHUD { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.animationType = .fade hud.label.text = title return hud } @discardableResult func showProgress(in view: UIView) -> MBProgressHUD { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.animationType = .fade hud.mode = .indeterminate return hud } }
apache-2.0
ef6989cae497086525eb6941d948b928
24.972222
72
0.684492
3.831967
false
false
false
false
likumb/SimpleMemo
SMKit/Appearance.swift
2
490
// // Appearance.swift // SimpleMemo // // Created by  李俊 on 2017/2/26. // Copyright © 2017年 Lijun. All rights reserved. // import UIKit // MARK: - SMColor public struct SMColor { public static let tint = UIColor(r: 23, g: 127, b: 251) public static let title = UIColor(hex: 0x494949) public static let content = UIColor(r: 80, g: 80, b: 80) public static let backgroundGray = UIColor(r: 244, g: 244, b: 244) public static let red = UIColor(r: 252, g: 70, b: 100) }
mit
83849b75eda86f32723f5f3b5ae51ce6
25.777778
68
0.661826
2.957055
false
false
false
false
mastershadow/indecente-ios
Indecente/ViewController.swift
1
4071
// // ViewController.swift // Indecente // // Created by Eduard Roccatello on 01/10/14. // Copyright (c) 2014 Roccatello Eduard. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var indecente:UIImageView? = nil @IBOutlet var render:UIImageView? = nil @IBOutlet var bg:UIImageView? = nil @IBOutlet var menuView:UIView? = nil @IBOutlet var playButton:IndButton? = nil @IBOutlet var copioneButton:IndButton? = nil @IBOutlet var castButton:IndButton? = nil @IBOutlet var galleryButton:IndButton? = nil @IBOutlet var newsButton:IndButton? = nil @IBOutlet var trailerButton:IndButton? = nil @IBOutlet var creditsButton:UIButton? = nil @IBOutlet var menuViewRightMarginContraint:NSLayoutConstraint? = nil @IBOutlet var titleRightMarginConstraint:NSLayoutConstraint? = nil @IBOutlet var leftButtonLeftMarginConstraint:NSLayoutConstraint? = nil override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() bg?.image = UIImage(named: "indecente_bg.jpg") trailerButton?.addTarget(self, action: "onTrailer", forControlEvents: UIControlEvents.TouchUpInside) copioneButton?.addTarget(self, action: "onCopione", forControlEvents: UIControlEvents.TouchUpInside) castButton?.addTarget(self, action: "onCast", forControlEvents: UIControlEvents.TouchUpInside) newsButton?.addTarget(self, action: "onNews", forControlEvents: UIControlEvents.TouchUpInside) galleryButton?.addTarget(self, action: "onGallery", forControlEvents: UIControlEvents.TouchUpInside) creditsButton?.addTarget(self, action: "onCredits", forControlEvents: UIControlEvents.TouchUpInside) menuViewRightMarginContraint?.constant = 142 titleRightMarginConstraint?.constant = 180 leftButtonLeftMarginConstraint?.constant = -85 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true; self.view.layoutIfNeeded() UIView.animateWithDuration(0.5, animations: { () -> Void in self.menuViewRightMarginContraint?.constant = 0 self.view.layoutIfNeeded() }) UIView.animateWithDuration(0.5, animations: { () -> Void in self.titleRightMarginConstraint?.constant = 0 self.view.layoutIfNeeded() }) UIView.animateWithDuration(0.5, animations: { () -> Void in self.leftButtonLeftMarginConstraint?.constant = 0 self.view.layoutIfNeeded() }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // animating } func onTrailer() { UIApplication.sharedApplication().openURL(NSURL(string : "https://www.youtube.com/watch?v=eqI0LE9UpsE")!); } func onCopione() { pushWebViewWithUrl(INDECENTE_BASE_URL + "/copione.html", title: "Estratti dal Copione") } func onCredits() { pushWebViewWithUrl(INDECENTE_BASE_URL + "/credits/credits.html", title: "Behind the App") } func onCast() { pushWebViewWithUrl(INDECENTE_BASE_URL + "/cast.html", title: "Il Cast") } func onNews() { pushWebViewWithUrl(INDECENTE_BASE_URL + "/news.html", title: "News & Eventi") } func pushWebViewWithUrl(url: String, title: String) -> Void { var webView = WebViewController(url: url, title: title) navigationController?.pushViewController(webView, animated: true) } func onGallery() { var phVc = PhotoViewController() navigationController?.pushViewController(phVc, animated: true) } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.Portrait.rawValue); } }
mit
d3408838faf66ed34cfb1ef9289549aa
35.348214
114
0.675755
4.657895
false
false
false
false
silt-lang/silt
Sources/Lithosphere/SyntaxChildren.swift
1
1378
//===------------- SyntaxChildren.swift - Syntax Child Iterator -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // // This file contains modifications from the Silt Langauge project. These // modifications are released under the MIT license, a copy of which is // available in the repository. // //===----------------------------------------------------------------------===// import Foundation public struct SyntaxChildren: Sequence { public struct Iterator: IteratorProtocol { let node: Syntax var indexIterator: _SyntaxBase.PresentChildIndicesSequence.Iterator init(node: Syntax) { self.indexIterator = node.presentChildIndices.makeIterator() self.node = node } public mutating func next() -> Syntax? { guard let index = indexIterator.next() else { return nil } return node.child(at: index) } } let node: Syntax public func makeIterator() -> SyntaxChildren.Iterator { return Iterator(node: node) } }
mit
ad8f93a949ba4170a804576ed1cb8f90
31.809524
80
0.619739
4.886525
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/ACManagedTableController.swift
1
2937
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class ACManagedTableController: AAViewController { private let tableViewStyle: UITableViewStyle var delegate: ACManagedTableControllerDelegate? let binder = Binder() var tableView: UITableView! var managedTable: ACManagedTable! init(tableViewStyle: UITableViewStyle) { self.tableViewStyle = tableViewStyle super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Creating tables tableView = UITableView(frame: view.bounds, style: tableViewStyle) // Disabling separators as we use manual separators handling tableView.separatorStyle = .None // Setting tableView and view bg color depends on table style tableView.backgroundColor = tableViewStyle == UITableViewStyle.Grouped ? MainAppTheme.list.backyardColor : MainAppTheme.list.bgColor view.backgroundColor = tableView.backgroundColor managedTable = ACManagedTable(tableView: tableView, controller: self) view.addSubview(tableView) // Invoking table loading if let d = delegate { d.managedTableLoad(self, table: managedTable) } // Initial load of Managed Table tableView.reloadData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Performing data binding if let d = delegate { d.managedTableBind(self, table: managedTable, binder: binder) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Stopping data binding here if let d = delegate { d.managedTableUnbind(self, table: managedTable, binder: binder) } // Removing all bindings binder.unbindAll() } } protocol ACManagedTableControllerDelegate { func managedTableLoad(controller: ACManagedTableController, table: ACManagedTable) func managedTableBind(controller: ACManagedTableController, table: ACManagedTable, binder: Binder) func managedTableUnbind(controller: ACManagedTableController, table: ACManagedTable, binder: Binder) } extension ACManagedTableControllerDelegate { func managedTableLoad(controller: ACManagedTableController, table: ACManagedTable) { // Do nothing } func managedTableBind(controller: ACManagedTableController, table: ACManagedTable, binder: Binder) { // Do nothing } func managedTableUnbind(controller: ACManagedTableController, table: ACManagedTable, binder: Binder) { // Do nothing } }
mit
14cc97be6bd44f419bd6fb91f88f39a0
29.28866
106
0.65509
5.510319
false
false
false
false
podverse/podverse-ios
Podverse/FindBrowsePodcastsViewController.swift
1
4387
// // FindBrowsePodcastsViewController.swift // Podverse // // Created by Mitchell Downey on 10/22/17. // Copyright © 2017 Podverse LLC. All rights reserved. // import UIKit class FindBrowsePodcastsViewController: PVViewController { var podcasts = [SearchPodcast]() var groupTitle = "" var categoryName:String? var networkName:String? @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() var params = Dictionary<String,String>() if let categoryName = categoryName { self.title = "Category" params["filters[categories.name]"] = categoryName } else if let networkName = networkName { self.title = "Network" params["filters[network.name]"] = networkName } params["sort_by"] = "buzz_score" params["sort_order"] = "desc" // SearchClientSwift.search(query: "*", params: params, type: "shows") { (serviceResponse) in // // self.podcasts.removeAll() // // if let response = serviceResponse.0 { // // let page = response["page"] as? String // // let query = response["query"] as? String // // let results_per_page = response["results_per_page"] as? String // // let total_results = response["total_results"] as? String // // if let results = response["results"] as? [AnyObject] { // for result in results { // if let searchResult = SearchPodcast.convertJSONToSearchPodcast(result) { // self.podcasts.append(searchResult) // } // } // } // // DispatchQueue.main.async { // self.tableView.reloadData() // } // } // // if let error = serviceResponse.1 { // print(error.localizedDescription) // } // // } } } extension FindBrowsePodcastsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.groupTitle } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 96.5 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 96.5 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.podcasts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PodcastSearchResultTableViewCell let podcast = self.podcasts[indexPath.row] cell.title.text = podcast.title cell.hosts.text = podcast.hosts cell.categories.text = podcast.categories cell.pvImage.image = Podcast.retrievePodcastImage(podcastImageURLString: podcast.imageUrl, feedURLString: nil, completion: { image in cell.pvImage.image = image }) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let podcast = self.podcasts[indexPath.row] SearchPodcast.showSearchPodcastActions(searchPodcast: podcast, vc: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Show Search Podcast" { if let searchPodcastVC = segue.destination as? SearchPodcastViewController, let indexPath = self.tableView.indexPathForSelectedRow, indexPath.row < self.podcasts.count { let podcast = podcasts[indexPath.row] searchPodcastVC.searchPodcast = podcast searchPodcastVC.filterTypeOverride = .about } } } }
agpl-3.0
acdceed23d2176f6805e1d05d5a8161e
34.370968
181
0.577975
5.052995
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/View/PotentialValueStepper.swift
1
717
// // PotentialValueStepper.swift // DereGuide // // Created by zzk on 2017/8/3. // Copyright © 2017年 zzk. All rights reserved. // import UIKit class PotentialValueStepper: ValueStepper { override init(frame: CGRect) { super.init(frame: frame) maximumValue = 10 minimumValue = 0 stepValue = 1 numberFormatter.maximumFractionDigits = 0 } convenience init(type: CGSSAttributeTypes) { self.init(frame: .zero) numberFormatter.positivePrefix = type.short + " +" tintColor = type.color } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
263466754d5703d7ecbedee9f8772cc6
21.3125
59
0.619048
4.275449
false
false
false
false
mpurland/Tyro
Tyro/JSONOperators.swift
3
2842
// // Operators.swift // Tyro // // Created by Matthew Purland on 11/17/15. // Copyright © 2015 TypeLift. All rights reserved. // import Foundation import Swiftz // JSONFormatterType decoding operators public func <? (lhs : JSONValue?, rhs : JSONKeypath) -> JSONValue? { return lhs?[rhs] } public func <? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> B.DecodedType? { return (lhs?.decode <*> lhs?.jsonValue?[rhs]) ?? nil } public func <? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> [B.DecodedType]? { return lhs?.jsonValue?[rhs]?.array.flatMap { $0.flatMap { lhs?.decode($0) } } } public func <? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> [String : B.DecodedType]? { return lhs?.jsonValue?[rhs]?.object.flatMap { $0.mapMaybe { lhs?.decode($0) } } } public func <?? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> B.DecodedType?? { return (lhs <? rhs) ?? nil } public func <?? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> [B.DecodedType]?? { return (lhs <? rhs) ?? nil } public func <?? <B : JSONFormatterType> (lhs : B?, rhs : JSONKeypath) -> [String : B.DecodedType]?? { return (lhs <? rhs) ?? nil } /// JSONValue decoding operators public func <? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> A? { return lhs?[rhs]?.value() } public func <? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> [A]? { return lhs?[rhs]?.value() } public func <? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> [String : A]? { return lhs?[rhs]?.value() } public func <?? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> A?? { return lhs <? rhs } public func <?? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> [A]?? { return lhs <? rhs } public func <?? <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) -> [String : A]?? { return lhs <? rhs } public func <! <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) throws -> A { if let result : A = (lhs <? rhs) { return result } else { throw JSONError.Custom("Could not find value at keypath \(rhs) in JSONValue : \(lhs)") } } public func <! <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) throws -> [A] { if let result : [A] = (lhs <? rhs) { return result } else { throw JSONError.Custom("Could not find value at keypath \(rhs) in JSONValue : \(lhs)") } } public func <! <A : FromJSON where A.T == A>(lhs : JSONValue?, rhs : JSONKeypath) throws -> [String : A] { if let result : [String : A] = (lhs <? rhs) { return result } else { throw JSONError.Custom("Could not find value at keypath \(rhs) in JSONValue : \(lhs)") } }
bsd-3-clause
63860876186e5673ce404fadd5824a15
29.548387
106
0.591341
3.338425
false
false
false
false
rob-brown/DataSourceCombinators
DataSourceCombinators/FilterableDataSource.swift
1
3292
// ~MMMMMMMM,. .,MMMMMMM .. // DNMMDMMMMMMMM,. ..MMMMNMMMNMMM, // MMM.. ...NMMM MMNMM ,MMM // NMM, , MMND MMMM .MM // MMN MMMMM MMM // .MM , MMMMMM , MMM // .MM MMM. MMMM MMM // .MM~ .MMM. NMMN. MMM // MMM MMMM: .M ..MMM .MM, // MMM.NNMMMMMMMMMMMMMMMMMMMMMMMMMM:MMM, // ,,MMMMMMMMMMMMMMM NMMDNMMMMMMMMN~, // MMMMMMMMM,, OMMM NMM . ,MMNMMMMN. // ,MMMND .,MM= NMM~ MMMMMM+. MMM. NMM. .:MMMMM. // MMMM NMM,MMMD MMM$ZZZMMM: .NMN.MMM NMMM // MMNM MMMMMM MMZO~:ZZZZMM~ MMNMMN .MMM // MMM MMMMM MMNZ~~:ZZZZZNM, MMMM MMN. // MM. .MMM. MMZZOZZZZZZZMM. MMMM MMM. // MMN MMMMN MMMZZZZZZZZZNM. MMMM MMM. // NMMM .MMMNMN .MM$ZZZZZZZMMN ..NMMMMM MMM // MMMMM MMM.MMM~ .MNMZZZZMMMD MMM MMM . . NMMN, // NMMMM: ..MM8 MMM, . MNMMMM: .MMM: NMM ..MMMMM // ...MMMMMMNMM MMM .. MMM. MNDMMMMM. // .: MMMMMMMMMMDMMND MMMMMMMMNMMMMM // NMM8MNNMMMMMMMMMMMMMMMMMMMMMMMMMMNMM // ,MMM NMMMDMMMMM NMM.,. ,MM // MMO ..MMM NMMM MMD // .MM. ,,MMM+.MMMM= ,MMM // .MM. MMMMMM~. MMM // MM= MMMMM.. .MMN // MMM MMM8 MMMN. MM, // +MMO MMMN, MMMMM, MMM // ,MMMMMMM8MMMMM, . MMNMMMMMMMMM. // .NMMMMNMM DMDMMMMMM import UIKit open class FilterableDataSource<Element>: ChainableDataSource<Element> { public typealias Context = Element public typealias Filter = ((Context?, [[Element]]) -> [[Element]]) open var context: Context? = nil { didSet(oldValue) { update() } } fileprivate let filter: Filter public init(_ dataSource: ChainableDataSource<Element>, filter: @escaping Filter) { self.filter = filter super.init(dataSource: dataSource) dataSource.registerForChanges() { self.update() } } // MARK: UITableViewDataSource open override func numberOfSections(in tableView: UITableView) -> Int { return collection.count } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return collection[section].count } // MARK: UICollectionViewDataSource open override func numberOfSections(in collectionView: UICollectionView) -> Int { return collection.count } open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collection[section].count } // MARK: Helpers fileprivate func update() { guard let dataSource = dataSource else { return } collection = filter(context, dataSource.collection) } }
mit
242b8367ae59569c09b55ecdc870199b
38.190476
119
0.492406
4.059186
false
false
false
false
chrisdhaan/CDYelpFusionKit
Source/CDYelpReview.swift
1
2138
// // CDYelpReview.swift // CDYelpFusionKit // // Created by Christopher de Haan on 5/7/17. // // Copyright © 2016-2022 Christopher de Haan <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(OSX) import UIKit #else import Foundation #endif public struct CDYelpReview: Decodable { public let id: String? public let text: String? public let url: String? public let rating: Int? public let timeCreated: String? public let user: CDYelpUser? enum CodingKeys: String, CodingKey { case id case text case url case rating case timeCreated = "time_created" case user } public func urlAsUrl() -> URL? { if let url = self.url, let asUrl = URL(string: url) { return asUrl } return nil } public func timeCreatedAsDate() -> Date? { if let timeCreated = self.timeCreated { let formatter = DateFormatter() return formatter.date(from: timeCreated) } return nil } }
mit
29c7b311b7e5022e59553e95963e779d
30.895522
81
0.677117
4.265469
false
false
false
false
amrap-labs/TeamupKit
Sources/TeamupKit/Utils/UrlUtils.swift
1
1673
// // UrlUtils.swift // TeamupKit // // Created by Merrick Sapsford on 14/06/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation extension Dictionary { /// Build string representation of HTTP parameter dictionary of keys and objects /// /// This percent escapes in compliance with RFC 3986 /// /// http://www.ietf.org/rfc/rfc3986.txt /// /// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped func stringFromHttpParameters() -> String { let parameterArray = self.map{ parameter -> String in let percentEscapedKey = (parameter.key as! String).addingPercentEncodingForURLQueryValue()! let percentEscapedValue = (parameter.value as? String ?? String(describing: parameter.value)).addingPercentEncodingForURLQueryValue()! return "\(percentEscapedKey)=\(percentEscapedValue)" } return parameterArray.joined(separator: "&") } } extension String { /// 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: Returns percent-escaped string. func addingPercentEncodingForURLQueryValue() -> String? { let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) } }
mit
922aa91d356d6d6e58eaad3011b112a6
35.347826
146
0.678828
4.97619
false
false
false
false
biohazardlover/ROer
Roer/StatusCalculatorNumberInputControl.swift
1
1973
import UIKit class StatusCalculatorNumberInputControl: UIControl { @IBOutlet var contentView: UIView! @IBOutlet var minusButton: UIButton! @IBOutlet var textField: UITextField! @IBOutlet var plusButton: UIButton! @IBAction func minusButtonClicked(_ minusButton: UIButton) { if numberInputElement.value > numberInputElement.min { numberInputElement.value -= 1 textField.text = String(numberInputElement.value) } } @IBAction func plusButtonClicked(_ plusButton: UIButton) { if numberInputElement.value < numberInputElement.max { numberInputElement.value += 1 textField.text = String(numberInputElement.value) } } override func awakeFromNib() { super.awakeFromNib() UINib(nibName: "StatusCalculatorNumberInputControl", bundle: nil).instantiate(withOwner: self, options: nil) addSubview(contentView) contentView.snp.makeConstraints { (make) in make.edges.equalTo(self) } } override var alignmentRectInsets : UIEdgeInsets { return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } var numberInputElement: StatusCalculator.NumberInputElement! { didSet { textField.text = String(numberInputElement.value) } } } extension StatusCalculatorNumberInputControl: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text, let value = Int(text) else { return true } if value < numberInputElement.min { numberInputElement.value = numberInputElement.min } else if value > numberInputElement.max { numberInputElement.value = numberInputElement.max } else { numberInputElement.value = value } return true } }
mit
8acd5f20b6041ee23385523b9ec3432b
28.893939
116
0.631019
5.219577
false
false
false
false
Jnosh/swift
test/SILGen/copy_lvalue_peepholes.swift
5
1957
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } typealias Int = Builtin.Int64 var zero = getInt() func getInt() -> Int { return zero } // CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes014init_var_from_B0{{[_0-9a-zA-Z]*}}F // CHECK: [[X:%.*]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[PBX:%.*]] = project_box [[X]] // CHECK: [[Y:%.*]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]] // CHECK: copy_addr [[READ]] to [initialization] [[PBY]] : $*Builtin.Int64 func init_var_from_lvalue(x: Int) { var x = x var y = x } // -- Peephole doesn't apply to computed lvalues var computed: Int { get { return zero } set {} } // CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes023init_var_from_computed_B0{{[_0-9a-zA-Z]*}}F // CHECK: [[GETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fg // CHECK: [[GOTTEN:%.*]] = apply [[GETTER]]() // CHECK: store [[GOTTEN]] to [trivial] {{%.*}} func init_var_from_computed_lvalue() { var y = computed } // CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes021assign_computed_from_B0{{[_0-9a-zA-Z]*}}F // CHECK: [[Y:%.*]] = alloc_box // CHECK: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBY]] // CHECK: [[Y_VAL:%.*]] = load [trivial] [[READ]] // CHECK: [[SETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fs // CHECK: apply [[SETTER]]([[Y_VAL]]) func assign_computed_from_lvalue(y: Int) { var y = y computed = y } // CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes24assign_var_from_computed{{[_0-9a-zA-Z]*}}F // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: assign {{%.*}} to [[WRITE]] func assign_var_from_computed(x: inout Int) { x = computed }
apache-2.0
ca76bd99e65630f3ae093d0175d1f18b
33.946429
100
0.612672
3.015408
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClientTests/Scenes/List/RepositoryListPresenterSpec.swift
1
4718
/* Copyright 2017 - André Gimenez Faria 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 Quick import Nimble import RxSwift @testable import MiniGitClient private class MockInteractor : RepositoryListInteractorType { var repositoriesStore : RepositoriesStoreType = RepositoriesStore.shared var shouldFail = false func repositories(fromPage page: Int) -> Observable<[Repository]> { if shouldFail { return Observable.error(APIRequestError.networkError) } else { var repositories = [Repository]() for _ in 0...10 { repositories.append(Repository()) } return Observable.just(repositories) } } } class RepositoryListPresenterSpec: QuickSpec { override func spec() { describe("The RepositoryListPresenter") { var presenter = RepositoryListPresenter() var mockInteractor = MockInteractor() var tableViewModel = RepositoryListTableViewModel() var viewController = RepositoryListViewController(nibName: nil, bundle: nil) beforeEach { presenter = RepositoryListPresenter() mockInteractor = MockInteractor() tableViewModel = RepositoryListTableViewModel() viewController = RepositoryListViewController(nibName: nil, bundle: nil) viewController.tableViewModel = tableViewModel viewController.presenter = presenter presenter.interactor = mockInteractor viewController.view.layoutIfNeeded() } context("after retrieving the repositories from the interactor", { it("changes the state to showing repositories on success") { expect(presenter.currentState.value) == RepositoryListState.showingRepositories } it("changes the state to showingError on first load") { mockInteractor.shouldFail = true presenter.repositories.value = [Repository]() presenter.currentState.value = .loadingFirst expect(presenter.currentState.value) == RepositoryListState.showingError } it("changes the state to showingRepositories after a failed second load") { mockInteractor.shouldFail = true presenter.currentState.value = .loadingMore expect(presenter.currentState.value) == RepositoryListState.showingRepositories } it("accumulates repositories after each load") { let firstLoadCount = presenter.repositories.value.count presenter.currentState.value = .loadingMore let secondLoadCount = presenter.repositories.value.count expect(secondLoadCount).to(beGreaterThan(firstLoadCount)) presenter.currentState.value = .loadingMore let thirdLoadCount = presenter.repositories.value.count expect(thirdLoadCount).to(beGreaterThan(secondLoadCount)) } it("updates the repository list table view") { presenter.repositories.value = [Repository()] expect(viewController.tableViewModel?.tableView(UITableView(), numberOfRowsInSection: 0)) == 1 } }) } } }
mit
8589cb0e9b8d73be99432dfe59831eac
44.355769
461
0.618826
6.280959
false
false
false
false
linkedin/LayoutKit
Sources/Views/ReloadableViewLayoutAdapter+UICollectionView.swift
1
3494
// Copyright 2016 LinkedIn Corp. // 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. import UIKit // MARK: - UICollectionViewDelegateFlowLayout extension ReloadableViewLayoutAdapter: UICollectionViewDelegateFlowLayout { /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return currentArrangement[indexPath.section].items[indexPath.item].frame.size } /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return currentArrangement[section].header?.frame.size ?? .zero } /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return currentArrangement[section].footer?.frame.size ?? .zero } } // MARK: - UICollectionViewDataSource extension ReloadableViewLayoutAdapter: UICollectionViewDataSource { /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentArrangement[section].items.count } /// - Warning: Subclasses that override this method must call super open func numberOfSections(in collectionView: UICollectionView) -> Int { return currentArrangement.count } /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = currentArrangement[indexPath.section].items[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) item.makeViews(in: cell.contentView) return cell } /// - Warning: Subclasses that override this method must call super open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifier, for: indexPath) let arrangement: LayoutArrangement? switch kind { case UICollectionView.elementKindSectionHeader: arrangement = currentArrangement[indexPath.section].header case UICollectionView.elementKindSectionFooter: arrangement = currentArrangement[indexPath.section].footer default: arrangement = nil assertionFailure("unknown supplementary view kind \(kind)") } arrangement?.makeViews(in: view) return view } }
apache-2.0
fd396684c17b590d9c2dca77ec6d85d2
49.637681
175
0.749284
5.842809
false
false
false
false
Mycose/CMLazyScrollViewController
Example/Pods/CMPageControl/CMPageControl/Classes/CMPageControl.swift
1
10504
// // CMPageControl.swift // CMPageControl // // Created by Clément Morissard on 26/10/16. // Copyright © 2016 Clément Morissard. All rights reserved. // import UIKit @objc public enum CMPageControlOrientation : Int { case Horizontal = 0 case Vertical = 1 } public protocol CMPageControlDelegate { func elementClicked(pageControl : CMPageControl, atIndex: Int) func shouldChangeIndex(from : Int, to : Int) -> Bool } @IBDesignable public class CMPageControl: UIControl { // MARK: - PRIVATE PROPERTIES fileprivate var currentView : UIView? fileprivate var views : [UIView?] = [] fileprivate var imageViews : [UIImageView?] = [] fileprivate var buttons : [UIButton?] = [] fileprivate var buttonWidth : CGFloat = 10.0 fileprivate func cleanViews() { for view in views { if let view = view { view.removeFromSuperview() views[view.tag] = nil } } for button in buttons { if let btn = button { btn.removeFromSuperview() buttons[btn.tag] = nil } } } // MARK: - PUBLIC PROPERTIES public var currentIndex : Int = 0 { didSet { if currentIndex < 0 || currentIndex > numberOfElements-1 { return } for view in views { if let view = view { if view.tag == currentIndex { currentView = view setSelectedStyleForView(view: view, animated: true) } else { setUnselectedStyleForView(view: view, animated: true) } } } } } @IBInspectable public var numberOfElements : Int = 0 { didSet { setup() } } @IBInspectable public var elementSpacing : CGFloat = 10.0 @IBInspectable public var elementWidth : CGFloat = 7.0 { didSet { buttonWidth = elementWidth * 1.5 } } @IBInspectable public var elementCornerRadius : CGFloat = 5.0 { didSet { if (isRounded == true) { for view in views { if let view = view { view.layer.masksToBounds = true view.layer.cornerRadius = elementCornerRadius } } } } } @IBInspectable public var isRounded : Bool = true { didSet { for view in views { if let view = view { if (isRounded == true) { view.layer.masksToBounds = true view.layer.cornerRadius = elementCornerRadius } else { view.layer.masksToBounds = false view.layer.cornerRadius = 0 } } } } } @IBInspectable public var elementImage : UIImage? { didSet { setup() } } @IBInspectable public var elementBackgroundColor : UIColor = UIColor.white.withAlphaComponent(0.2) { didSet { for view in views { if let view = view, view != currentView { view.backgroundColor = elementBackgroundColor } } } } @IBInspectable public var elementBorderColor : UIColor = UIColor.clear { didSet { for view in views { if let view = view, view != currentView { view.layer.borderColor = elementBorderColor.cgColor } } } } @IBInspectable public var elementBorderWidth : CGFloat = 0.0 { didSet { for view in views { if let view = view, view != currentView { view.layer.borderWidth = elementBorderWidth } } } } @IBInspectable public var elementSelectedImage : UIImage? { didSet { if let view = currentView as? UIImageView { view.image = elementSelectedImage } } } @IBInspectable public var elementSelectedBackgroundColor : UIColor = UIColor.white { didSet { if let view = currentView { view.backgroundColor = elementSelectedBackgroundColor } } } @IBInspectable public var elementSelectedBorderColor : UIColor = UIColor.clear { didSet { if let view = currentView { view.layer.borderColor = elementSelectedBorderColor.cgColor } } } @IBInspectable public var elementSelectedBorderWidth : CGFloat = 0.0 { didSet { if let view = currentView { view.layer.borderWidth = elementSelectedBorderWidth } } } @IBInspectable public var orientation : CMPageControlOrientation = .Horizontal { didSet { setup() } } public var delegate : CMPageControlDelegate? fileprivate func setup() { cleanViews() let nbSpace : Int = numberOfElements + 1 var spaceWidth : CGFloat = 0.0 var xPos : CGFloat = 0.0 var yPos : CGFloat = 0.0 views = Array(repeating: nil, count: numberOfElements) buttons = Array(repeating: nil, count: numberOfElements) for i in 0..<numberOfElements { // calculate x and y depending on if vertical or horizontal and depending on index if (orientation == .Horizontal) { spaceWidth = (frame.width - (CGFloat(numberOfElements) * elementWidth)) / CGFloat(nbSpace) xPos = (CGFloat(i) * elementWidth) + (CGFloat(i+1) * spaceWidth) yPos = (frame.height - elementWidth) / 2 } else { spaceWidth = (frame.height - (CGFloat(numberOfElements) * elementWidth)) / CGFloat(nbSpace) yPos = (CGFloat(i) * elementWidth) + (CGFloat(i+1) * spaceWidth) xPos = (frame.width - elementWidth) / 2 } var view : UIView = UIView() // if there is an image set, create UIImageView instead of UIView if let image = elementImage { let imageView = UIImageView(frame: CGRect(x: xPos, y: yPos, width: elementWidth, height: elementWidth)) imageView.contentMode = .scaleAspectFit imageView.image = image view = imageView } else { view = UIView(frame: CGRect(x: xPos, y: yPos, width: elementWidth, height: elementWidth)) view.backgroundColor = elementBackgroundColor view.layer.borderColor = elementBorderColor.cgColor view.layer.borderWidth = elementBorderWidth if (isRounded == true) { view.layer.masksToBounds = true view.layer.cornerRadius = elementCornerRadius } } addSubview(view) view.tag = i views[i] = view // button put over the indicator view if width != 0.0 (cant happen normally) // i prefer to use a button over the indicator view because else there is no way to control the clickable area. Here you can just set a bigger value for buttonWidth for a bigger clickable area if buttonWidth != 0.0 { let button = UIButton(frame: CGRect(x: 0, y: 0, width: buttonWidth, height: buttonWidth)) button.center = view.center button.tag = i button.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside) addSubview(button) buttons[i] = button } } currentIndex = 0 } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public init(frame: CGRect) { super.init(frame: frame) } override public func layoutSubviews() { let nbSpace : Int = numberOfElements - 1 let elementsWidth : CGFloat = CGFloat(numberOfElements) * elementWidth let elementsSpacing : CGFloat = CGFloat(nbSpace) * elementSpacing let frameWidth : CGFloat = (orientation == .Horizontal) ? self.frame.width : self.frame.height let posStart : CGFloat = (frameWidth - (elementsWidth + elementsSpacing)) / 2.0 var xPos : CGFloat = 0.0 var yPos : CGFloat = 0.0 for view in views { if let view = view { let index : CGFloat = CGFloat(view.tag) if (orientation == .Horizontal) { xPos = posStart + (index * elementWidth) + (index * elementSpacing) yPos = (frame.height - elementWidth) / 2 } else { yPos = posStart + (index * elementWidth) + (index * elementSpacing) xPos = (frame.width - elementWidth) / 2 } view.frame = CGRect(x: xPos, y: yPos, width: elementWidth, height: elementWidth) if let btn = buttons[view.tag] { btn.center = view.center } } } } @objc fileprivate func buttonClicked(sender : UIButton) { let shouldChange = delegate?.shouldChangeIndex(from: currentIndex, to: sender.tag) ?? true delegate?.elementClicked(pageControl: self, atIndex: sender.tag) if shouldChange == true { currentIndex = sender.tag } } fileprivate func setSelectedStyleForView(view : UIView, animated : Bool) { if let view = view as? UIImageView { if let image = elementSelectedImage { view.image = image } } view.backgroundColor = elementSelectedBackgroundColor view.layer.borderWidth = elementSelectedBorderWidth view.layer.borderColor = elementSelectedBorderColor.cgColor } fileprivate func setUnselectedStyleForView(view : UIView, animated : Bool) { if let view = view as? UIImageView { if let image = elementImage { view.image = image } } view.backgroundColor = elementBackgroundColor view.layer.borderWidth = elementBorderWidth view.layer.borderColor = elementBorderColor.cgColor } }
mit
55ee3e601b0fa852c2468b514c350237
32.983819
204
0.546996
5.216592
false
false
false
false
someoneAnyone/Nightscouter
Common/Protocols/ComplicationDataSourceGenerator.swift
1
8160
// // ComplicationDataSourceGenerator.swift // Nightscouter // // Created by Peter Ina on 3/10/16. // Copyright © 2016 Nothingonline. All rights reserved. // import Foundation public protocol ComplicationDataSourceGenerator { var oldestComplicationData: ComplicationTimelineEntry? { get } var latestComplicationData: ComplicationTimelineEntry? { get } var complicationUpdateInterval: TimeInterval { get } func nearest(calibration cals: [Calibration], forDate date: Date) -> Calibration? func generateComplicationData(with serverConfiguration: ServerConfiguration, sensorGlucoseValues: [SensorGlucoseValue], calibrations: [Calibration]) -> [ComplicationTimelineEntry] } // MARK: Complication Data Source public extension ComplicationDataSourceGenerator { var complicationUpdateInterval: TimeInterval { return 60.0 * 30.0 } var nextRequestedComplicationUpdateDate: Date { guard let latestComplicationData = latestComplicationData else { return Date(timeIntervalSinceNow: complicationUpdateInterval) } return latestComplicationData.date.addingTimeInterval(complicationUpdateInterval) } func nearest(calibration cals: [Calibration], forDate date: Date) -> Calibration? { if cals.isEmpty { return nil } var desiredIndex: Int? var minDate: TimeInterval = fabs(Date().timeIntervalSinceNow) for (index, cal) in cals.enumerated() { let dateInterval = fabs(cal.date.timeIntervalSince(date)) let compared = minDate < dateInterval if compared { minDate = dateInterval desiredIndex = index } } guard let index = desiredIndex else { print("NON-FATAL ERROR: No valid index was found... return first calibration if its there.") return cals.first } return cals[safe: index] } func generateComplicationData(with serverConfiguration: ServerConfiguration, sensorGlucoseValues: [SensorGlucoseValue], calibrations: [Calibration]) -> [ComplicationTimelineEntry] { let configuration = serverConfiguration let sgvs = sensorGlucoseValues // Init Complication Model Array for return as Timeline. var compModels: [ComplicationTimelineEntry] = [] // Get prfered Units for site. let units = configuration.displayUnits // Setup thresholds for proper color coding. let thresholds: Thresholds = configuration.settings?.thresholds ?? Thresholds(bgHigh: 300, bgLow: 70, bgTargetBottom: 60, bgTargetTop: 250) // Iterate through provided Sensor Glucose Values to create a timeline. for (index, sgv) in sgvs.enumerated() where index < 2 { // Create a color for a given SGV value. let sgvColor = thresholds.desiredColorState(forValue: sgv.mgdl) // Set the date required by the Complication Data Source (for Timeline) let date = sgv.date // Convet Sensor Glucose Value to a proper string. Always start with a mgd/L number then convert to a mmol/L var sgvString = sgv.mgdl.formattedForMgdl if units == .mmol { sgvString = sgv.mgdl.formattedForMmol } // // END of Delta Calculation // // Init Delta var. var delta: MgdlValue = 0 // Get the next index position which would be a previous or older reading. let previousIndex: Int = index + 1 // If the next index is a valid object and the number is safe. if let previousSgv = sgvs[safe: previousIndex] , sgv.isGlucoseValueOk { delta = sgv.mgdl - previousSgv.mgdl } // Convert to proper units if units == .mmol { delta = delta.toMmol } // Create strings if the sgv is ok. Otherwise clear it out. let deltaString = sgv.isGlucoseValueOk ? "(" + delta.formattedBGDelta(forUnits: units) + ")" : "" // END of Delta Calculation // // // Start of Raw Calculation // // Init Raw String var var rawString: String = "" // Get nearest calibration for a given sensor glucouse value's date. if let calibration = nearest(calibration: calibrations, forDate: sgv.date as Date) { // Calculate Raw BG for a given calibration. let raw = sgv.calculateRaw(withCalibration: calibration) //calculateRawBG(fromSensorGlucoseValue: sgv, calibration: calibration) var rawFormattedString = raw.formattedForMgdl // Convert to correct units. if units == .mmol { rawFormattedString = raw.formattedForMmol } // Create string representation of raw data. rawString = rawFormattedString } let compModel = ComplicationTimelineEntry(date: date, rawLabel: rawString, nameLabel: configuration.displayName, sgvLabel: sgvString, deltaLabel: deltaString, tintColor: sgvColor.colorValue, units: units, direction: sgv.direction ?? .none, noise: sgv.noise ?? Noise.unknown) compModels.append(compModel) } /* let settings = configuration.settings ?? ServerConfiguration().settings! // Get the latest model and use to create stale complication timeline entries. let model = compModels.max{ (lModel, rModel) -> Bool in return rModel.date.compare(lModel.date as Date) == .orderedDescending } if let model = model { // take last date and extend out 15 minutes. if settings.timeAgo.warn { let warnTime = settings.timeAgo.warnMins let warningStaleDate = model.date.addingTimeInterval(warnTime) let warnItem = ComplicationTimelineEntry(date: warningStaleDate, rawLabel: "Please update.", nameLabel: "Data missing.", sgvLabel: "Warning", deltaLabel: "", tintColor: DesiredColorState.warning.colorValue, units: .mgdl, direction: .none, noise: .none) compModels.append(warnItem) } if settings.timeAgo.urgent { // take last date and extend out 30 minutes. let urgentTime = settings.timeAgo.urgentMins let urgentStaleDate = model.date.addingTimeInterval(urgentTime) let urgentItem = ComplicationTimelineEntry(date: urgentStaleDate, rawLabel: "Please update.", nameLabel: "Data missing.", sgvLabel: "Urgent", deltaLabel: "", tintColor: DesiredColorState.alert.colorValue, units: .mgdl, direction: .none, noise: .none) compModels.append(urgentItem) } }*/ // compModels.sorted() return compModels } } extension Site: ComplicationDataSourceGenerator { @discardableResult public mutating func generateComplicationData() -> [ComplicationTimelineEntry] { //if !self.updateNow { return self.complicationTimeline } guard let configuration = self.configuration else { return [] } self.complicationTimeline = generateComplicationData(with: configuration, sensorGlucoseValues: sgvs, calibrations: cals) return self.complicationTimeline } public var latestComplicationData: ComplicationTimelineEntry? { let complicationModels: [ComplicationTimelineEntry] = self.complicationTimeline // ?? [] return sortByDate(complicationModels).first } public var oldestComplicationData: ComplicationTimelineEntry? { let complicationModels: [ComplicationTimelineEntry] = self.complicationTimeline // ?? [] return sortByDate(complicationModels).last } }
mit
5084edec0ad8e510f0659c8748a12de2
41.056701
286
0.624586
5.042645
false
true
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
Team UI/Browser/Browser/EEXCESSRecommendationCtrl.swift
1
1901
// // EexcessRecommendationCtrl.swift // Browser // // Created by Burak Erol on 10.12.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import Foundation class EEXCESSRecommendationCtrl { private var pRecommendations : [EEXCESSAllResponses]? var recommendations : [EEXCESSAllResponses]? { get { return pRecommendations } } init? (data : NSData) { let jsonT = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as AnyObject print(jsonT) guard let json = jsonT else { return nil } extractRecommendatins(json) } private func extractRecommendatins(json : AnyObject) { guard let jsonData = JSONData.fromObject(json) else { return } guard let allResults = jsonData["results"]?.array as [JSONData]! else { return } pRecommendations = [] for i in allResults { let allResponses = EEXCESSAllResponses() let result = i.object!["result"]?.array for res in result!{ let u = (res.object!["documentBadge"]?["uri"]?.string)! let p = (res.object!["documentBadge"]?["provider"]?.string)! let t = (res.object!["title"]?.string)! let l = (res.object!["language"]?.string)! let m = (res.object!["mediaType"]?.string)! let newRecommendation = EEXCESSSingleResponse(title: t, provider: p, uri: u, language: l, mediaType: m) allResponses.appendSingleResponse(newRecommendation) } pRecommendations?.append(allResponses) } } }
mit
678b40d24f637ec6a665a27582c07397
25.402778
119
0.521053
4.909561
false
false
false
false
cpuu/OTT
OTT/Profiles/ServiceCharacteristicProfileViewController.swift
1
4681
// // ServiceCharacteristicProfileViewController.swift // BlueCap // // Created by Troy Stribling on 8/5/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import BlueCapKit class ServiceCharacteristicProfileViewController : UITableViewController { var characteristicProfile: BCCharacteristicProfile? @IBOutlet var uuidLabel: UILabel! @IBOutlet var permissionReadableLabel: UILabel! @IBOutlet var permissionWriteableLabel: UILabel! @IBOutlet var permissionReadEncryptionLabel: UILabel! @IBOutlet var permissionWriteEncryptionLabel: UILabel! @IBOutlet var propertyBroadcastLabel: UILabel! @IBOutlet var propertyReadLabel: UILabel! @IBOutlet var propertyWriteWithoutResponseLabel: UILabel! @IBOutlet var propertyWriteLabel: UILabel! @IBOutlet var propertyNotifyLabel: UILabel! @IBOutlet var propertyIndicateLabel: UILabel! @IBOutlet var propertyAuthenticatedSignedWritesLabel: UILabel! @IBOutlet var propertyExtendedPropertiesLabel: UILabel! @IBOutlet var propertyNotifyEncryptionRequiredLabel: UILabel! @IBOutlet var propertyIndicateEncryptionRequiredLabel: UILabel! struct MainStoryboard { static let serviceCharacteristicProfileValuesSegue = "ServiceCharacteristicProfileValues" } required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let characteristicProfile = self.characteristicProfile { self.navigationItem.title = characteristicProfile.name self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) self.uuidLabel.text = characteristicProfile.UUID.UUIDString self.permissionReadableLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.Readable)) self.permissionWriteableLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.Writeable)) self.permissionReadEncryptionLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.ReadEncryptionRequired)) self.permissionWriteEncryptionLabel.text = self.booleanStringValue(characteristicProfile.permissionEnabled(CBAttributePermissions.WriteEncryptionRequired)) self.propertyBroadcastLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Broadcast)) self.propertyReadLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Read)) self.propertyWriteWithoutResponseLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.WriteWithoutResponse)) self.propertyWriteLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Write)) self.propertyNotifyLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Notify)) self.propertyIndicateLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.Indicate)) self.propertyAuthenticatedSignedWritesLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.AuthenticatedSignedWrites)) self.propertyExtendedPropertiesLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.ExtendedProperties)) self.propertyNotifyEncryptionRequiredLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.NotifyEncryptionRequired)) self.propertyIndicateEncryptionRequiredLabel.text = self.booleanStringValue(characteristicProfile.propertyEnabled(CBCharacteristicProperties.IndicateEncryptionRequired)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == MainStoryboard.serviceCharacteristicProfileValuesSegue { let viewController = segue.destinationViewController as! ServiceCharacteristicProfileValuesViewController viewController.characteristicProfile = self.characteristicProfile } } func booleanStringValue(value: Bool) -> String { return value ? "YES" : "NO" } }
mit
f1b3191b20ea0874bb065d8de4d647a6
53.430233
181
0.779748
5.800496
false
false
false
false
gradyzhuo/Acclaim
Sources/Logger/Implementation.swift
1
4208
// // File.swift // // // Created by Grady Zhuo on 2021/2/27. // import Foundation /* CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 TRACE = 5 NOTSET = 0 */ public struct StdoutLogging: LoggingType{ public internal(set) var level:LoggingLevel public internal(set) var namespace: String public internal(set) var streamer: WritableStreamer public init(level: LoggingLevel, namespace: String, streamer: WritableStreamer = ConsoleOutputStream.stdout) { self.level = level self.streamer = streamer self.namespace = namespace } } public struct StderrLogging: LoggingType{ public internal(set) var level:LoggingLevel public internal(set) var namespace: String public internal(set) var streamer: WritableStreamer public init(level: LoggingLevel, namespace: String, streamer: WritableStreamer = ConsoleOutputStream.stderr) { self.level = level self.streamer = streamer self.namespace = namespace } } //public struct StdLogging: LoggingType{ // public var level:LoggingLevel{ .debug } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} //public struct Critical: LoggingType{ // public static var level:LoggingLevel{ .critical } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Fatal: LoggingType{ // public static var level:LoggingLevel{ .fatal } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Error: LoggingType{ // public static var level:LoggingLevel{ .error } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Warnning: LoggingType{ // public static var level:LoggingLevel{ .warnning } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Warn: LoggingType{ // public static var level:LoggingLevel{ .warn } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // // //public struct Info: LoggingType{ // public static var level:LoggingLevel{ .info } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Debug: LoggingType{ // public static var level:LoggingLevel{ .debug } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} // //public struct Trace: LoggingType{ // public static var level:LoggingLevel{ .trace } // // public internal(set) var namespace: String // public internal(set) var steamer: LoggingStreamer // // public init(namespace: String, steamer: LoggingStreamer) { // self.steamer = steamer // self.namespace = namespace // } //} //
mit
03f3613e5c4ebc14b438344801f5341b
26.503268
114
0.663973
3.790991
false
false
false
false
davidkuchar/codepath-04-twitterredux
Twitter/TweetDetailsViewController.swift
1
3836
// // TweetDetailsViewController.swift // Twitter // // Created by David Kuchar on 5/25/15. // Copyright (c) 2015 David Kuchar. All rights reserved. // import UIKit class TweetDetailsViewController: UIViewController { @IBOutlet weak var retweetedImage: UIImageView! @IBOutlet weak var retweetedLabel: UILabel! @IBOutlet weak var userImageButton: UIButton! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var tweetMessageLabel: UILabel! @IBOutlet weak var dateTimeCreatedLabel: UILabel! @IBOutlet weak var numberOfRetweetsLabel: UILabel! @IBOutlet weak var numberOfFavoritesLabel: UILabel! @IBOutlet weak var usernameButton: UIButton! @IBOutlet weak var userImageTopConstraint: NSLayoutConstraint! @IBOutlet weak var userNameTopConstraint: NSLayoutConstraint! var tweet: Tweet? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if tweet != nil { if let retweetedByUser = tweet!.retweetedByUser { retweetedLabel.text = "\(retweetedByUser.name!) retweeted" retweetedLabel.hidden = false retweetedImage.hidden = false userImageTopConstraint.constant = 31 userNameTopConstraint.constant = 37 } else { retweetedLabel.hidden = true retweetedImage.hidden = true userImageTopConstraint.constant = 8 userNameTopConstraint.constant = 14 } if let user = tweet!.user { userImageButton.setBackgroundImageForState(UIControlState.Normal, withURL: NSURL(string: user.profileImageUrl!)) userImageButton.layer.cornerRadius = 3 userImageButton.clipsToBounds = true userNameLabel.text = user.name if let userTwitterHandle = user.screenname { usernameButton.setTitle("@\(userTwitterHandle)", forState: UIControlState.Normal) } } dateTimeCreatedLabel.text = tweet!.dateTimeCreated() tweetMessageLabel.text = tweet!.text numberOfRetweetsLabel.text = String(tweet!.retweets!) numberOfFavoritesLabel.text = String(tweet!.favorites!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onReply(sender: AnyObject) { println("reply!") performSegueWithIdentifier("newTweetFromDetailsSegue", sender: sender) } @IBAction func onRetweet(sender: AnyObject) { println("retweet!") tweet?.retweet() } @IBAction func onFavorite(sender: AnyObject) { println("favorite!") tweet?.createFavorite() } // 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. if segue.identifier == "newTweetFromDetailsSegue" { if let composeTweetViewContoller = segue.destinationViewController as? ComposeTweetViewController { composeTweetViewContoller.replyToTweet = tweet } } else if segue.identifier == "onOpenProfile" { if let profileViewContoller = segue.destinationViewController as? ProfileViewController { profileViewContoller.user = tweet!.user } } } }
mit
c60da6b347328f744cc53ffb02d9bf44
35.884615
128
0.635036
5.624633
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/LevelParser.swift
1
7327
// // LevelParser.swift // OnGettingThere // // Created by Benzi on 20/07/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation class LevelParser : NSObject, NSXMLParserDelegate { var xmlParser:NSXMLParser! var level:Level! var tileHeight = 0 var tileWidth = 0 var currentObjectGroup = LevelObjectGroup.None var currentLevelObject = LevelObject() var tokens = Stack<Token>() var gridIndex = 0 var wallIndex = 0 var blockRoundedIndex = 0 var cellRoundedIndex = 0 var zonemapIndex = 0 func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if(elementName=="map") { tokens.push(Token.Map) level.rows = (attributeDict["height"]! as NSString).integerValue level.columns = (attributeDict["width"]! as NSString).integerValue tileHeight = (attributeDict["tileheight"]! as NSString).integerValue tileWidth = (attributeDict["tilewidth"]! as NSString).integerValue level.initializeCells() } else if elementName == "layer" { let layerName = attributeDict["name"]! as NSString switch(layerName){ case "grid": tokens.push(Token.GridLayer) case "walls": tokens.push(Token.WallLayer) case "blockrounded": tokens.push(Token.RoundedBlockLayer) case "cellrounded": tokens.push(Token.RoundedCellLayer) case "zonemap": tokens.push(Token.zoneMap) default:break } } else if(elementName=="tile") { let currentLayer = tokens.top() var gid = UInt((attributeDict["gid"]! as NSString).integerValue) switch(currentLayer) { case Token.WallLayer: if gid > 0 { gid -= 1 } level.cellAt(wallIndex++).walls += gid case Token.GridLayer: if gid > 0 { gid -= 1 } level.cellAt(gridIndex++).walls += gid case Token.RoundedCellLayer: level.cellAt(cellRoundedIndex++).cellRoundedness = gid case Token.RoundedBlockLayer: level.cellAt(blockRoundedIndex++).blockRoundedness = gid case Token.zoneMap: var zone:UInt = 0 switch gid { case 34: zone = 1 case 37: zone = 2 case 38: zone = 3 case 41: zone = 4 case 42: zone = 5 case 43: zone = 6 case 44: zone = 7 default: break } // if zone > 0 { // let (c,r) = level.getColumnRow(zonemapIndex) // println("\(c),\(r) = gid:\(gid) --> zone:\(zone)") // } level.cellAt(zonemapIndex++).zone = zone default: break } return } else if(elementName=="property") { // a property can belong to any element // we try to identify by looking at the current token stack // to process which is which if tokens.top() == Token.Map { // set the top level properties of the map let name = attributeDict["name"]! as String let value = attributeDict["value"]! as NSString switch name { case "title": level.title = value as String case "mode": switch value { case "merged": level.zoneBehaviour = ZoneBehaviour.Mergeable case "standalone": level.zoneBehaviour = ZoneBehaviour.Standalone default:break } case "zone": self.level.initialZone = UInt(value.integerValue) default: level.conditions[name] = value as String } } else if tokens.top() == Token.Object { // this property belongs to a level object // copy in the name value pair to the dict currentLevelObject.properties[ (attributeDict["name"]! as String) ] = (attributeDict["value"]! as String) } } else if elementName == "objectgroup" { var name = attributeDict["name"]! as NSString switch(name) { case "players" : currentObjectGroup = LevelObjectGroup.Player case "cells" : currentObjectGroup = LevelObjectGroup.Cell case "goals" : currentObjectGroup = LevelObjectGroup.Item // TODO: remove this, kept for backward compatibility case "items" : currentObjectGroup = LevelObjectGroup.Item case "enemies" : currentObjectGroup = LevelObjectGroup.Enemy case "powerups" : currentObjectGroup = LevelObjectGroup.Powerup case "portals" : currentObjectGroup = LevelObjectGroup.Portal default: break } } else if(elementName=="object") { tokens.push(Token.Object) currentLevelObject = LevelObject() var x = (attributeDict["x"]! as NSString).integerValue var y = (attributeDict["y"]! as NSString).integerValue var type = attributeDict["type"]! as NSString let r = y / tileHeight let c = x / tileWidth currentLevelObject.group = currentObjectGroup currentLevelObject.type = type as String currentLevelObject.location = LocationComponent(row: r, column: c) } } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "object" { level.levelObjects.append(currentLevelObject) tokens.pop() } else if elementName == "layer" { tokens.pop() } else if elementName == "map" { tokens.pop() } } func parse() { xmlParser.parse() } init(levelItem:LevelItem) { xmlParser = NSXMLParser(contentsOfURL: levelItem.url) level = Level() level.info = levelItem super.init() xmlParser.delegate = self } class func parse(levelItem:LevelItem) -> Level { let parser = LevelParser(levelItem: levelItem) parser.parse() return parser.level } enum Token { case Map case Object case GridLayer case WallLayer case RoundedCellLayer case RoundedBlockLayer case zoneMap } }
isc
a146b7c6a7a7c03faf049e6b72a5fcdf
32.921296
173
0.512079
5.344274
false
false
false
false
ManueGE/Actions
actions/actions/UIView+Actions.swift
1
5027
// // UIView+Actions.swift // actions // // Created by Manu on 1/6/16. // Copyright © 2016 manuege. All rights reserved. // import UIKit /** Action where the parameter can be assigned manually */ private class CustomParametizedAction<T: NSObject>: Action { @objc let key = ProcessInfo.processInfo.globallyUniqueString @objc let selector: Selector = #selector(perform) let action: ((T) -> Void) weak var parameter: T? init(parameter: T?, action: @escaping (T) -> Void) { self.action = action self.parameter = parameter } @objc func perform() { guard let parameter = parameter else { return } action(parameter) } } /** The gestures that can be used to trigger actions in `UIView` */ public enum Gesture { /// A tap gesture with a single finger and the given number of touches case tap(Int) /// A swipe gesture with a single finger and the given direction case swipe(UISwipeGestureRecognizer.Direction) /// A tap gesture with the given number of touches and fingers case multiTap(taps: Int, fingers: Int) /// A swipe gesture with the given direction and number of fingers case multiSwipe(direction: UISwipeGestureRecognizer.Direction, fingers: Int) fileprivate func recognizer(action: Action) -> UIGestureRecognizer { switch self { case let .tap(taps): let recognizer = UITapGestureRecognizer(target: action, action: action.selector) recognizer.numberOfTapsRequired = taps return recognizer case let .swipe(direction): let recognizer = UISwipeGestureRecognizer(target: action, action: action.selector) recognizer.direction = direction return recognizer case let .multiTap(taps, fingers): let recognizer = UITapGestureRecognizer(target: action, action: action.selector) recognizer.numberOfTapsRequired = taps recognizer.numberOfTouchesRequired = fingers return recognizer case let .multiSwipe(direction, fingers): let recognizer = UISwipeGestureRecognizer(target: action, action: action.selector) recognizer.direction = direction recognizer.numberOfTouchesRequired = fingers return recognizer } } } /// Extension that provides methods to add actions to views extension UIView { /** Adds the given action as response to the gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func add<T: UIView>(gesture: Gesture, action: @escaping (T) -> Void) -> UIGestureRecognizer { let action = CustomParametizedAction(parameter: (self as! T), action: action) return add(gesture: gesture, action: action) } /** Adds the given action as response to the gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func add(gesture: Gesture, action: @escaping () -> Void) -> UIGestureRecognizer { let action = VoidAction(action: action) return add(gesture: gesture, action: action) } /** Adds the given action as response to a single tap gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func addTap<T: UIView>(action: @escaping (T) -> Void) -> UIGestureRecognizer { let action = CustomParametizedAction(parameter: (self as! T), action: action) return add(gesture: .tap(1), action: action) } /** Adds the given action as response to a single tap gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func addAction(action: @escaping () -> Void) -> UIGestureRecognizer { let action = VoidAction(action: action) return add(gesture: .tap(1), action: action) } @discardableResult private func add(gesture: Gesture, action: Action) -> UIGestureRecognizer{ retainAction(action, self) let gesture = gesture.recognizer(action: action) isUserInteractionEnabled = true addGestureRecognizer(gesture) return gesture } }
mit
88d2ace72437ac3dedc7b1075454115e
35.686131
104
0.664146
4.991063
false
false
false
false
kayak/attributions
Attributions/Attributions/LicenseReader.swift
1
2910
import Foundation struct LicenseReader { let attribution: Attribution private let licenseFiles: [String] init(attribution: Attribution, licenseFiles: [String]) { self.attribution = attribution self.licenseFiles = licenseFiles } func text() throws -> String { switch attribution.license { case .id(let id): return try readText(resource: id.appending(".txt")) case .text(let text): return text case .file(let file, let bundleID): let bundle = bundleFromIdentifier(bundleID) return try readText(resource: file, bundle: bundle) } } private func readText(resource: String) throws -> String { guard let path = licenseFiles.first(where: { $0.contains(resource) }) else { throw NSError.makeError(description: "Could not find file: \(resource)") } let data = try Data(contentsOf: URL(fileURLWithPath: path)) guard let text = String(data: data, encoding: .utf8) else { throw NSError.makeError(description: "Could not read from file: \(resource)") } return text } private func readText(resource: String, bundle: Bundle) throws -> String { let filename = (resource as NSString).deletingPathExtension let fileExtension = (resource as NSString).pathExtension guard let path = bundle.url(forResource: filename, withExtension: fileExtension) else { throw NSError.makeError(description: "Could not find file: \(resource)") } let data = try Data(contentsOf: path) guard let text = String(data: data, encoding: .utf8) else { throw NSError.makeError(description: "Could not read from file: \(resource)") } return text } func verifyLicenseExists() throws { switch attribution.license { case .id(let id): guard licenseFiles.first(where: { $0.contains("\(id).txt") }) != nil else { throw NSError.makeError(description: "Invalid license key \(id) for \(attribution.name)") } case .text(_): break case .file(let file, let bundleID): let bundle = bundleFromIdentifier(bundleID) let filename = (file as NSString).deletingPathExtension let fileExtension = (file as NSString).pathExtension guard bundle.url(forResource: filename, withExtension: fileExtension) != nil else { throw NSError.makeError(description: "Could not find license \(file) for \(attribution.name)") } } } private func bundleFromIdentifier(_ identifier: String?) -> Bundle { if let bundleID = identifier, let licenseBundle = Bundle(identifier: bundleID) { return licenseBundle } else { return .main } } }
apache-2.0
55c90648fccace4c8bc1a5fe310aa7f9
38.324324
110
0.610653
4.84193
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/19197-swift-constraints-constraintsystem-gettypeofmemberreference.swift
11
2402
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a<T: A class a( ) func g<S : { let a { class let b { func a<Int> class A : b { var d = A { } func a<C) { class for in { struct B<Int> { class B<T where T: B<H : b { let c = A class B<l : B<H : g { () { deinit { func a struct d { let b : B<l : A func a<l : b { struct B<H : A let b : A deinit { struct d { init { class } for c : A class deinit { } { var d { struct B<T: b protocol A { struct B<d = a( ) case c, deinit { case c, () { class class a<T: b> { } let b { func a<C) { class class (() { if true { protocol A { func a( ) var d { protocol A : B<d = A.a( ) { struct d { class class A { struct B<Int> protocol A { init( ) for c { class class a<l : g { class let a { case c, let c = a<H : Array<l : b { func a var d { class a { protocol A : g { var d { case c, case , class A { class class B<C) { class c { protocol A : { class A : B<Int> class let c = a<T where T: b { case , func g { protocol A { { class A { struct B<H : Array<H : Array<H : A deinit { func g<l : A class a class class B for in { deinit { case , var d { deinit { init { class func g<T where T: Array<T where B : b class { let b { func g () { case c, case , if true { deinit { init { { func b typealias b { func b class let a { deinit { class deinit { deinit { class protocol A { { { } protocol A { func g<H : Array<H : A class class a { var d { let c { { func g<S : e deinit { typealias b : b { func a<Int> case , case , let c : B<C) { func g protocol A { case c, struct B for in { class protocol A : b { func a<T: { protocol A { init { struct d { class func a deinit { struct d = a case , func g { class } func g<S : B<H : b { { class c : A case c, } enum A : B<l : B<l : A init { deinit { protocol A { var d { func g<T where B : B<T where T: b let b { func a<d = a var d = A struct B for in { func a( ) { class class case , let b : b> { struct B<S : b { protocol A : A func a<H : Array<C) { class a { () { let b : g { func g var d { var d { var d { { func a func a case c, { class B let c = A.a<S : g { case , { protocol A { { } class c : B<H : { func g init { init( ) { class A : b { class A func a<Int> protocol A { deinit { class B<d = a( ) { let a { deinit { class } deinit { protocol A { class (() { protocol A : b { typealias b : b let b { class c
mit
a0d55c830a9dafa15f0e3adab0fc1546
9.581498
87
0.59159
2.334305
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/BookComment/ViewModel/ZSBookCommentViewModel.swift
1
2596
// // ZSBookCommentViewModel.swift // zhuishushenqi // // Created by caonongyun on 2018/6/17. // Copyright © 2018年 QS. All rights reserved. // import Foundation import RxCocoa import RxSwift struct ZSBookCommentSection { var items: [BookCommentDetail] var comment:BookComment? var best:[BookCommentDetail]? } extension ZSBookCommentSection: SectionModelType{ init(original: ZSBookCommentSection, items: [BookCommentDetail]) { self = original self.items = items } typealias Item = BookCommentDetail } final class ZSBookCommentViewModel { // dataSource,监听 var section:Driver<[ZSBookCommentSection]>? // 首页的刷新命令,入参是当前的分类 let refreshCommand = ReplaySubject<Any>.create(bufferSize: 1) let requireMoreCommand = ReplaySubject<Any>.create(bufferSize: 1) fileprivate var bricks:BehaviorSubject<[BookCommentDetail]>? var refreshStatus: Variable<ZSRefreshStatus> = Variable(.none) fileprivate let disposeBag = DisposeBag() fileprivate var webService = ZSBookCommentService() init() { bricks = BehaviorSubject<[BookCommentDetail]>(value: []) section = bricks? .asObserver() .map({ (comment) -> [ZSBookCommentSection] in return [ZSBookCommentSection(items: comment, comment: BookComment(), best: comment)] }) .asDriver(onErrorJustReturn: []) refreshCommand.subscribe(onNext: { (event) in let detail = self.webService.fetchCommentDetail(id: "", type: .normal) let best = self.webService.fetchCommentBest(id: "") detail.asObservable().subscribe({ (event) in switch event { case let .error(error): QSLog(error) break case let .next(response): QSLog(response) break case .completed: break } }).disposed(by: self.disposeBag) best.asObservable().subscribe({ (event) in switch event { case let .error(error): QSLog(error) break case let .next(response): QSLog(response) break case .completed: break } }).disposed(by: self.disposeBag) }, onError: { (error) in }).disposed(by: disposeBag) } }
mit
825c17693e1a60ce302e18a519a8c08f
29.428571
100
0.56338
4.850095
false
false
false
false
burczyk/SwiftTeamSelect
SwiftTeamSelect/GameScene.swift
1
8609
// // GameScene.swift // SwiftTeamSelect // // Created by Kamil Burczyk on 16.06.2014. // Copyright (c) 2014 Sigmapoint. All rights reserved. // import SpriteKit class GameScene: SKScene { enum Zone { case Left, Center, Right } var players = [SKSpriteNode]() var leftPlayer: SKSpriteNode? var centerPlayer: SKSpriteNode? var rightPlayer: SKSpriteNode? var leftGuide : CGFloat { return round(view!.bounds.width / 6.0) } var rightGuide : CGFloat { return view!.bounds.width - leftGuide } var gap : CGFloat { return (size.width / 2 - leftGuide) / 2 } // Initialization override init(size: CGSize) { super.init(size:size) createPlayers() centerPlayer = players[players.count/2] setLeftAndRightPlayers() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func didMoveToView(view: SKView) { placePlayersOnPositions() calculateZIndexesForPlayers() } func createPlayers() { let flatUIColors = UIColor.flatUIColors() for i in 0..<9 { let player = SKSpriteNode(color: flatUIColors[i], size: CGSizeMake(100, 200)) players.append(player) } } func placePlayersOnPositions() { for i in 0..<players.count/2 { players[i].position = CGPointMake(leftGuide, size.height/2) } players[players.count/2].position = CGPointMake(size.width/2, size.height/2) for i in players.count/2 + 1..<players.count { players[i].position = CGPointMake(rightGuide, size.height/2) } for player in players { player.setScale(calculateScaleForX(player.position.x)) self.addChild(player) } } // Helper functions func calculateScaleForX(x:CGFloat) -> CGFloat { let minScale = CGFloat(0.5) if x <= leftGuide || x >= rightGuide { return minScale } if x < size.width/2 { let a = 1.0 / (size.width - 2 * leftGuide) let b = 0.5 - a * leftGuide return (a * x + b) } let a = 1.0 / (frame.size.width - 2 * rightGuide) let b = 0.5 - a * rightGuide return (a * x + b) } func calculateZIndexesForPlayers() { var playerCenterIndex : Int = players.count / 2 for i in 0..<players.count { if centerPlayer == players[i] { playerCenterIndex = i } } for i in 0...playerCenterIndex { players[i].zPosition = CGFloat(i) } for i in playerCenterIndex+1..<players.count { players[i].zPosition = centerPlayer!.zPosition * 2 - CGFloat(i) } } func movePlayerToX(player: SKSpriteNode, x: CGFloat, duration: NSTimeInterval) { let moveAction = SKAction.moveToX(x, duration: duration) let scaleAction = SKAction.scaleTo(calculateScaleForX(x), duration: duration) player.runAction(SKAction.group([moveAction, scaleAction])) } func movePlayerByX(player: SKSpriteNode, x: CGFloat) { let duration = 0.01 if CGRectGetMidX(player.frame) <= rightGuide && CGRectGetMidX(player.frame) >= leftGuide { player.runAction(SKAction.moveByX(x, y: 0, duration: duration), completion: { player.setScale(self.calculateScaleForX(CGRectGetMidX(player.frame))) }) if CGRectGetMidX(player.frame) < leftGuide { player.position = CGPointMake(leftGuide, player.position.y) } else if CGRectGetMidX(player.frame) > rightGuide { player.position = CGPointMake(rightGuide, player.position.y) } } } func zoneOfCenterPlayer() -> Zone { let gap = size.width / 2 - leftGuide switch CGRectGetMidX(centerPlayer!.frame) { case let x where x < leftGuide + gap/2: return .Left case let x where x > rightGuide - gap/2: return .Right default: return .Center } } func setLeftAndRightPlayers() { var playerCenterIndex : Int = players.count / 2 for i in 0..<players.count { if centerPlayer == players[i] { playerCenterIndex = i } } if playerCenterIndex > 0 && playerCenterIndex < players.count { leftPlayer = players[playerCenterIndex-1] } else { leftPlayer = nil } if playerCenterIndex > -1 && playerCenterIndex < players.count-1 { rightPlayer = players[playerCenterIndex+1] } else { rightPlayer = nil } } // Touch interactions override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let node = self.nodeAtPoint(touch.locationInNode(self)) if node == centerPlayer { let fadeOut = SKAction.fadeAlphaTo(0.5, duration: 0.15) let fadeIn = SKAction.fadeAlphaTo(1, duration: 0.15) centerPlayer!.runAction(fadeOut, completion: { self.centerPlayer!.runAction(fadeIn) }) } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { let duration = 0.01 let touch = touches.anyObject() as UITouch let newPosition = touch.locationInNode(self) let oldPosition = touch.previousLocationInNode(self) let xTranslation = newPosition.x - oldPosition.x if CGRectGetMidX(centerPlayer!.frame) > size.width/2 { if (leftPlayer != nil) { let actualTranslation = CGRectGetMidX(leftPlayer!.frame) + xTranslation > leftGuide ? xTranslation : leftGuide - CGRectGetMidX(leftPlayer!.frame) movePlayerByX(leftPlayer!, x: actualTranslation) } } else { if (rightPlayer != nil) { let actualTranslation = CGRectGetMidX(rightPlayer!.frame) + xTranslation < rightGuide ? xTranslation : rightGuide - CGRectGetMidX(rightPlayer!.frame) movePlayerByX(rightPlayer!, x: actualTranslation) } } movePlayerByX(centerPlayer!, x: xTranslation) } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let duration = 0.25 switch zoneOfCenterPlayer() { case .Left: if (rightPlayer != nil) { movePlayerToX(centerPlayer!, x: leftGuide, duration: duration) if (leftPlayer != nil) { movePlayerToX(leftPlayer!, x: leftGuide, duration: duration) } if (rightPlayer != nil) { movePlayerToX(rightPlayer!, x: size.width/2, duration: duration) } centerPlayer = rightPlayer setLeftAndRightPlayers() } else { movePlayerToX(centerPlayer!, x: size.width/2, duration: duration) } case .Right: if (leftPlayer != nil) { movePlayerToX(centerPlayer!, x: rightGuide, duration: duration) if (rightPlayer != nil) { movePlayerToX(rightPlayer!, x: rightGuide, duration: duration) } if (leftPlayer != nil) { movePlayerToX(leftPlayer!, x: size.width/2, duration: duration) } centerPlayer = leftPlayer setLeftAndRightPlayers() } else { movePlayerToX(centerPlayer!, x: size.width/2, duration: duration) } case .Center: movePlayerToX(centerPlayer!, x: size.width/2, duration: duration) if (leftPlayer != nil) { movePlayerToX(leftPlayer!, x: leftGuide, duration: duration) } if (rightPlayer != nil) { movePlayerToX(rightPlayer!, x: rightGuide, duration: duration) } } calculateZIndexesForPlayers() } }
mit
85a922b7bfef88445ed9d2d2a96ced47
30.534799
165
0.545592
4.653514
false
false
false
false
SheffieldKevin/SwiftSVG
SwiftSVG Demo/SVGView.swift
1
4004
// // SVGView.swift // SwiftSVGTestNT // // Created by Jonathan Wight on 2/25/15. // Copyright (c) 2015 No. All rights reserved. // import Cocoa import SwiftGraphics import SwiftSVG class SVGView: NSView { @IBOutlet var horizontalConstraint: NSLayoutConstraint? @IBOutlet var verticalConstraint: NSLayoutConstraint? var svgRenderer: SVGRenderer = SVGRenderer() var svgDocument: SVGDocument? = nil { didSet { if let svgDocument = svgDocument, let viewBox = svgDocument.viewBox { horizontalConstraint?.constant = viewBox.width verticalConstraint?.constant = viewBox.width } needsDisplay = true needsLayout = true } } required init?(coder: NSCoder) { super.init(coder: coder) addGestureRecognizer(NSClickGestureRecognizer(target: self, action: Selector("tap:"))) } override func layout() { super.layout() } override func drawRect(dirtyRect: NSRect) { let context = NSGraphicsContext.currentContext()!.CGContext CGContextSetTextMatrix(context, CGAffineTransformIdentity) // Drawing code here. let filter = CheckerboardGenerator() filter.inputCenter = CIVector(CGPoint: CGPointZero) filter.inputWidth = 20 filter.inputColor0 = CIColor(CGColor: CGColor.whiteColor()) filter.inputColor1 = CIColor(CGColor: CGColor.color(white: 0.8, alpha: 1)) let ciImage = filter.outputImage! let ciContext = CIContext(CGContext: context, options: nil) let image = ciContext.createCGImage(ciImage, fromRect: bounds) CGContextDrawImage(context, bounds, image) if let svgDocument = svgDocument { context.with() { CGContextScaleCTM(context, 1, -1) CGContextTranslateCTM(context, 0, -bounds.size.height) try! svgRenderer.renderDocument(svgDocument, renderer: context) } } CGContextStrokeRect(context, bounds) } func tap(gestureRecognizer: NSClickGestureRecognizer) { let location = gestureRecognizer.locationInView(self) if let element = try? elementForPoint(location) { if let element = element { elementSelected?(svgElement: element) } } } var elementSelected: ((svgElement: SVGElement) -> Void)? func elementForPoint(point: CGPoint) throws -> SVGElement? { guard let svgDocument = svgDocument else { return nil } let context = CGContext.bitmapContext(self.bounds) var index: UInt32 = 0 var elementsByIndex: [UInt32: SVGElement] = [: ] let svgRenderer = SVGRenderer() svgRenderer.callbacks.styleForElement = { (svgElement: SVGElement) -> Style? in elementsByIndex[index] = svgElement let red = CGFloat((index & 0xFF0000) >> 16) / 255 let green = CGFloat((index & 0x00FF00) >> 8) / 255 let blue = CGFloat((index & 0x0000FF) >> 0) / 255 // TODO: HACK let color = NSColor(red: red, green: green, blue: blue, alpha: 1.0).CGColor let style = Style(elements: [.fillColor(color)]) index = index + 1 return style } try svgRenderer.renderDocument(svgDocument, renderer: context) // println("Max index: \(index)") var data = CGBitmapContextGetData(context) data = data.advancedBy(Int(point.y) * CGBitmapContextGetBytesPerRow(context)) let pixels = UnsafePointer <UInt32> (data).advancedBy(Int(point.x)) let argb = pixels.memory let blue = (argb & 0xFF000000) >> 24 let green = (argb & 0x00FF0000) >> 16 let red = (argb & 0x0000FF00) >> 8 // let alpha = (argb & 0x000000FF) >> 0 let searchIndex = red << 16 | green << 8 | blue return elementsByIndex[searchIndex] } }
bsd-2-clause
be95efa7e16aad0210f2012e0ed9557d
31.290323
94
0.613886
4.612903
false
false
false
false
reesemclean/PixelSolver
PixelSolver/PixelSolver-Logic/PuzzleFormatParsing.swift
1
2067
// // PuzzleFormatParsing.swift // PixelSolver // // Created by Reese McLean on 12/28/14. // Copyright (c) 2014 Lunchbox Apps. All rights reserved. // import Foundation func parseLinesFromPuzzleFormatString(lines: [String]) -> (rows: [String], columns: [String])? { if let indexOfRowString = find(lines, "Rows") { if let indexOfColumnString = find(lines, "Columns") { if (indexOfColumnString > indexOfRowString) { let rows = Array(lines[Range(start: indexOfRowString + 1, end: indexOfColumnString)]) if let indexOfSolutionString = find(lines, "Solution") { if (indexOfSolutionString > indexOfColumnString) { let columns = Array(lines[Range(start: indexOfColumnString + 1, end: indexOfSolutionString)]) return (rows, columns) } } else { let columns = Array(lines[Range(start: indexOfColumnString + 1, end: lines.count)]) return (rows, columns) } } } } return nil } func parseSolutionLinesFromPuzzleFormatString(lines: [String]) -> [String]? { let possibleIndexOfSolutionString = find(lines, "Solution") if (possibleIndexOfSolutionString == nil) { return nil } let indexOfSolutionString = possibleIndexOfSolutionString! if let indexOfRowString = find(lines, "Rows") { if (indexOfRowString > indexOfSolutionString) { return nil; } } if let indexOfColumnString = find(lines, "Columns") { if (indexOfColumnString > indexOfSolutionString) { return nil; } } return Array(lines[Range(start: indexOfSolutionString + 1, end: lines.count)]) }
mit
f4a19044444bbf2b5847a35639dfb15e
27.328767
117
0.521529
5.041463
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/OutSocket.swift
1
1992
// // OutSocket.swift // Photo Management Studio // // Created by Darren Oster on 31/03/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import CocoaAsyncSocket class OutSocket: NSObject, GCDAsyncUdpSocketDelegate { let _ipAddress: String let _port: UInt16 var _socket:GCDAsyncUdpSocket! let _ipAddressData: NSData init(ipAddress: String, port: UInt16) { _ipAddress = ipAddress _port = port var ip = sockaddr_in() ip.sin_family = sa_family_t(AF_INET) ip.sin_port = _port.littleEndian inet_pton(AF_INET, _ipAddress, &ip.sin_addr) _ipAddressData = NSData.init(bytes: &ip, length: sizeofValue(ip)) super.init() setupConnection() } func setupConnection() { _socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) _socket.setPreferIPv4() do { try _socket.enableBroadcast(true) } catch { print("enableBroadcast failed") } } func send(message: [String: AnyObject]) { do { let data = try NSJSONSerialization.dataWithJSONObject(message, options: NSJSONWritingOptions(rawValue: 0)) _socket.sendData(data, toHost: _ipAddress, port: _port, withTimeout: -1, tag: 0) } catch { print("send: something went wrong") } } func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) { print("didConnectToAddress") } func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) { print("didNotConnect \(error)") } func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) { print("didSendDataWithTag") } func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) { print("didNotSendDataWithTag \(error)") } }
mit
a02e0d7450158c06c202fb07eae6439b
29.166667
118
0.618282
4.474157
false
false
false
false
BrobotDubstep/BurningNut
BurningNut/BurningNut/Scenes/GameScene.swift
1
18694
// // GameScene.swift // BurningNut // // Created by Tim Olbrich on 21.09.17. // Copyright © 2017 Tim Olbrich. All rights reserved. // import SpriteKit import GameplayKit import MultipeerConnectivity struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let RightSquirrel : UInt32 = 0x1 << 0 static let LeftSquirrel : UInt32 = 0x1 << 1 static let LeftBomb : UInt32 = 0x1 << 2 static let RightBomb : UInt32 = 0x1 << 3 static let Environment : UInt32 = 0x1 << 4 static let Frame : UInt32 = 0x1 << 5 } class GameScene: SKScene, SKPhysicsContactDelegate { var bombCounter = 0 let appDelegate = UIApplication.shared.delegate as! AppDelegate var rightPointLbl = SKLabelNode() var leftPointLbl = SKLabelNode() let leftSquirrel = SKSpriteNode(imageNamed: "minisquirrelRight") let rightSquirrel = SKSpriteNode(imageNamed: "minisquirrel") let middleTree = SKSpriteNode(imageNamed: "tree-2") let leftTree = SKSpriteNode(imageNamed: "tree-1") let rightTree = SKSpriteNode(imageNamed: "tree-1") let explosionSound = SKAction.playSoundFileNamed("explosion.mp3", waitForCompletion: true) var playerTurn = 1 var playerNumber = 0 var playerTurnLbl = SKLabelNode() var flugbahnCalc = CalcFlugbahn() var playerTurnTxt = "Du bist dran!" var direction = SKShapeNode() override func didMove(to view: SKView) { self.setupMatchfield() playerNumber = GameState.shared.playerNumber if(playerNumber == 1) { playerTurnLbl.text = playerTurnTxt } else { playerTurnLbl.text = "" } leftPointLbl.text = String(GameState.shared.leftScore) rightPointLbl.text = String(GameState.shared.rightScore) self.physicsWorld.gravity = CGVector.init(dx: 0.0, dy: -6) self.physicsWorld.contactDelegate = self self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) self.physicsBody?.categoryBitMask = PhysicsCategory.Frame self.physicsBody?.contactTestBitMask = PhysicsCategory.LeftSquirrel | PhysicsCategory.RightSquirrel NotificationCenter.default.addObserver(self, selector: #selector(bombAttack(notification:)), name: NSNotification.Name("bomb"), object: nil) } @objc func bombAttack(notification: NSNotification) { guard let text = notification.userInfo?["position"] as? String else { return } var squirrel = SKSpriteNode() if(playerTurn == 1) { squirrel = leftSquirrel } else { squirrel = rightSquirrel } addBomb(player: squirrel, position: CGPointFromString(text)) } func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.categoryBitMask == PhysicsCategory.Frame || contact.bodyB.categoryBitMask == PhysicsCategory.Frame { if(contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel) { bombCounter = 1 GameState.shared.rightScore += 1 rightPointLbl.text = String(GameState.shared.rightScore) if(playerNumber == 1) { playerTurnLbl.text = "Du wurdest getroffen" } else { playerTurnLbl.text = "Treffer!" } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } else if(contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel) { bombCounter = 1 GameState.shared.leftScore += 1 leftPointLbl.text = String(GameState.shared.leftScore) if(playerNumber == 2) { playerTurnLbl.text = "Du wurdest getroffen" } else { playerTurnLbl.text = "Treffer!" } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } if( GameState.shared.leftScore == 3 || GameState.shared.rightScore == 3) { gameOver() } } else if let bodyOne = contact.bodyA.node as? SKSpriteNode, let bodyTwo = contact.bodyB.node as? SKSpriteNode { bombExplode(bodyOne: bodyOne, bodyTwo: bodyTwo) if contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel || contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel { if(contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel) { bombCounter = 1 GameState.shared.rightScore += 1 rightPointLbl.text = String(GameState.shared.rightScore) if(playerNumber == 1) { playerTurnLbl.text = "Du wurdest getroffen" } else { playerTurnLbl.text = "Treffer!" } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } else if(contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel) { bombCounter = 1 GameState.shared.leftScore += 1 leftPointLbl.text = String(GameState.shared.leftScore) if(playerNumber == 2) { playerTurnLbl.text = "Du wurdest getroffen" } else { playerTurnLbl.text = "Treffer!" } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } if( GameState.shared.leftScore == 3 || GameState.shared.rightScore == 3) { gameOver() } } } } func gameOver(){ let loseAction = SKAction.run() { var playerBool: Bool let reveal = SKTransition.flipHorizontal(withDuration: 0.5) if(self.playerTurn == 1) { playerBool = true } else { playerBool = false } let gameOverScene = GameOverScene(size: self.size, won: playerBool) self.view?.presentScene(gameOverScene, transition: reveal) } run(loseAction) } func bombExplode(bodyOne: SKSpriteNode, bodyTwo: SKSpriteNode) { let explosion = SKSpriteNode(imageNamed: "explosion") explosion.position = bodyOne.position explosion.size = CGSize(width: 60, height: 60) explosion.zPosition = 1 addChild(explosion) run(explosionSound) explosion.run( SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ]) ) bodyOne.removeFromParent() bodyTwo.removeFromParent() bombCounter = 0 if(self.playerTurn == 1) { self.playerTurn = 2 if(self.playerNumber == 2) { self.playerTurnLbl.text = self.playerTurnTxt } else { self.playerTurnLbl.text = "" } } else { self.playerTurn = 1 self.playerTurnLbl.text = "" if(playerNumber == 1) { playerTurnLbl.text = playerTurnTxt } else { playerTurnLbl.text = "" } } } func bombDidNotHit(leBomb: SKSpriteNode) -> SKAction { return SKAction.run { let explosion = SKSpriteNode(imageNamed: "explosion") explosion.position = leBomb.position explosion.size = CGSize(width: 60, height: 60) explosion.zPosition = 1 self.addChild(explosion) self.run(self.explosionSound) explosion.run( SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ]) ) leBomb.removeFromParent() self.bombCounter = 0 if(self.playerTurn == 1) { self.playerTurn = 2 if(self.playerNumber == 2) { self.playerTurnLbl.text = self.playerTurnTxt } else { self.playerTurnLbl.text = "" } } else { self.playerTurn = 1 self.playerTurnLbl.text = "" if(self.playerNumber == 1) { self.playerTurnLbl.text = self.playerTurnTxt } else { self.playerTurnLbl.text = "" } } } } func addBomb(player: SKSpriteNode, position: CGPoint) { var physicsCategory: UInt32 var bombCategory: UInt32 var loopFrom, loopTo: CGFloat var loopStep: CGFloat if(player == leftSquirrel) { physicsCategory = PhysicsCategory.RightSquirrel bombCategory = PhysicsCategory.LeftBomb loopFrom = leftSquirrel.position.x loopTo = rightSquirrel.position.x loopStep = 1 } else { physicsCategory = PhysicsCategory.LeftSquirrel bombCategory = PhysicsCategory.RightBomb loopFrom = rightSquirrel.position.x loopTo = leftSquirrel.position.x loopStep = -1 } if(bombCounter == 0) { let bomb = SKSpriteNode(imageNamed: "bomb") bomb.position = CGPoint(x: player.position.x, y: player.position.y) bomb.size = CGSize(width: 15, height: 30) bomb.zPosition = 1 bomb.physicsBody = SKPhysicsBody(rectangleOf: bomb.size) bomb.physicsBody?.categoryBitMask = bombCategory bomb.physicsBody?.contactTestBitMask = physicsCategory | PhysicsCategory.Environment //bomb.physicsBody?.collisionBitMask = physicsCategory bomb.physicsBody?.affectedByGravity = false addChild(bomb) bombCounter += 1 //let moveBomb = SKAction.move(to: CGPoint(x: position.x, y: position.y), duration: 4) let bezierPath = UIBezierPath() bezierPath.move(to: player.position) for i in stride(from: loopFrom, to: loopTo, by: loopStep) { let nextPoint = flugbahnCalc.flugkurve(t: CGFloat(i), x: player.position.x, y: player.position.y, x_in: position.x, y_in: position.y, player: loopStep) bezierPath.addLine(to: CGPoint(x: CGFloat(i), y: nextPoint)) } //bezierPath.close() let moveBomb = SKAction.follow(bezierPath.cgPath, asOffset: false, orientToPath: false, duration: 3) let rotateBomb = SKAction.rotate(byAngle: -20, duration: 3) let removeBomb = bombDidNotHit(leBomb: bomb) let groupBomb = SKAction.group([moveBomb, rotateBomb]) //bomb.run(SKAction.repeatForever(groupBomb)) bomb.run(SKAction.sequence([groupBomb, removeBomb])) } } func resetGameScene() { if let view = self.view as SKView? { if let scene = SKScene(fileNamed: "GameScene") { scene.scaleMode = .aspectFill view.presentScene(scene) } view.ignoresSiblingOrder = true // view.showsFPS = true // view.showsNodeCount = true } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if(playerNumber == playerTurn) { direction.removeFromParent() var currentPlayer: SKSpriteNode guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) if(playerTurn == 1) { currentPlayer = leftSquirrel } else { currentPlayer = rightSquirrel } addBomb(player: currentPlayer, position: touchLocation) appDelegate.multiplayerManager.sendData(position: NSStringFromCGPoint(touchLocation)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if(playerNumber == playerTurn) { direction.removeFromParent() var currentPlayer: SKSpriteNode guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) let bezierPath = UIBezierPath() if(playerTurn == 1) { currentPlayer = leftSquirrel let a = atan((touchLocation.y - currentPlayer.position.y) / (touchLocation.x - currentPlayer.position.x)) let x = currentPlayer.position.x + 160 * cos(a) let y = currentPlayer.position.y + 160 * sin(a) bezierPath.move(to: currentPlayer.position) bezierPath.addLine(to: CGPoint(x: x, y: y)) } else { currentPlayer = rightSquirrel let a = atan((touchLocation.y - currentPlayer.position.y) / (touchLocation.x - currentPlayer.position.x)) let x = currentPlayer.position.x - 160 * cos(a) let y = currentPlayer.position.y - 160 * sin(a) bezierPath.move(to: currentPlayer.position) bezierPath.addLine(to: CGPoint(x: x, y: y)) } direction.path = bezierPath.cgPath direction.fillColor = .white direction.lineWidth = 2 direction.zPosition = 0 addChild(direction) } } func setupMatchfield() { playerTurnLbl.position = CGPoint(x: 0, y: 135) playerTurnLbl.zPosition = 7 playerTurnLbl.fontColor = UIColor.black addChild(playerTurnLbl) leftPointLbl.position = CGPoint(x: -310, y: 135) leftPointLbl.zPosition = 7 leftPointLbl.fontColor = UIColor.black addChild(leftPointLbl) rightPointLbl.position = CGPoint(x: 310, y: 135) rightPointLbl.zPosition = 7 rightPointLbl.fontColor = UIColor.black addChild(rightPointLbl) leftSquirrel.position = CGPoint(x: -300.839, y: -89.305) leftSquirrel.size = CGSize(width: 51.321, height: 59.464) leftSquirrel.anchorPoint.x = 0.5 leftSquirrel.anchorPoint.y = 0.5 leftSquirrel.zPosition = 1 leftSquirrel.physicsBody = SKPhysicsBody(rectangleOf: leftSquirrel.size) //leftSquirrel.physicsBody?.isDynamic = false leftSquirrel.physicsBody?.categoryBitMask = PhysicsCategory.LeftSquirrel leftSquirrel.physicsBody?.contactTestBitMask = PhysicsCategory.RightBomb | PhysicsCategory.Frame leftSquirrel.physicsBody?.collisionBitMask = PhysicsCategory.Environment addChild(leftSquirrel) rightSquirrel.position = CGPoint(x: 300.839, y: -89.305) rightSquirrel.size = CGSize(width: 51.321, height: 59.464) rightSquirrel.anchorPoint.x = 0.5 rightSquirrel.anchorPoint.y = 0.5 rightSquirrel.zPosition = 1 rightSquirrel.physicsBody = SKPhysicsBody(rectangleOf: rightSquirrel.size) //rightSquirrel.physicsBody?.isDynamic = false rightSquirrel.physicsBody?.categoryBitMask = PhysicsCategory.RightSquirrel rightSquirrel.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.Frame rightSquirrel.physicsBody?.collisionBitMask = PhysicsCategory.Environment addChild(rightSquirrel) middleTree.position = CGPoint(x: 0, y: -4.238) middleTree.size = CGSize(width: 124.354, height: 221.849) middleTree.anchorPoint.x = 0.5 middleTree.anchorPoint.y = 0.5 middleTree.zPosition = 1 middleTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: middleTree.size.height)) middleTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment middleTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb middleTree.physicsBody?.collisionBitMask = PhysicsCategory.Environment //middleTree.physicsBody?.affectedByGravity = false addChild(middleTree) leftTree.position = CGPoint(x: -147.94, y: -62.205) leftTree.size = CGSize(width: 119.261, height: 173.357) leftTree.anchorPoint.x = 0.5 leftTree.anchorPoint.y = 0.5 leftTree.zPosition = 1 leftTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: leftTree.size.height)) leftTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment leftTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb leftTree.physicsBody?.collisionBitMask = PhysicsCategory.Environment //leftTree.physicsBody?.affectedByGravity = false addChild(leftTree) rightTree.position = CGPoint(x: 147.94, y: -62.205) rightTree.size = CGSize(width: 119.261, height: 173.357) rightTree.anchorPoint.x = 0.5 rightTree.anchorPoint.y = 0.5 rightTree.zPosition = 1 rightTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: rightTree.size.height)) rightTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment rightTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb rightTree.physicsBody?.collisionBitMask = PhysicsCategory.Environment //rightTree.physicsBody?.affectedByGravity = false addChild(rightTree) } }
mit
e3aa3d8b36f1cbc4d1e0a6b4f9850e44
39.461039
168
0.569358
4.941316
false
false
false
false
codestergit/swift
stdlib/public/core/Sequence.swift
3
56011
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Iterator.Element, Iterator.Element) -> Iterator.Element /// ) -> Iterator.Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.characters.count > element.characters.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints "Butterfly" /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. /// /// - SeeAlso: `IteratorProtocol`, `Collection` public protocol Sequence { //@available(*, unavailable, renamed: "Iterator") //typealias Generator = () /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator : IteratorProtocol /// A type that represents a subsequence of some of the sequence's elements. associatedtype SubSequence // FIXME(ABI)#104 (Recursive Protocol Constraints): // FIXME(ABI)#105 (Associated Types with where clauses): // associatedtype SubSequence : Sequence // where // Iterator.Element == SubSequence.Iterator.Element, // SubSequence.SubSequence == SubSequence // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Returns an iterator over the elements of this sequence. func makeIterator() -> Iterator /// A value less than or equal to the number of elements in /// the sequence, calculated nondestructively. /// /// - Complexity: O(1) var underestimatedCount: Int { get } /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.characters.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `includeElement` allowed. func filter( _ isIncluded: (Iterator.Element) throws -> Bool ) rethrows -> [Iterator.Element] /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. func forEach(_ body: (Iterator.Element) throws -> Void) rethrows // Note: The complexity of Sequence.dropFirst(_:) requirement // is documented as O(n) because Collection.dropFirst(_:) is // implemented in O(n), even though the default // implementation for Sequence.dropFirst(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. func dropFirst(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func dropLast(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. func prefix(_ maxLength: Int) -> SubSequence /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number /// of elements in the sequence, the result contains all the elements in /// the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of this sequence with /// at most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func suffix(_ maxLength: Int) -> SubSequence /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print( /// line.characters.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " }) /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? /// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and /// return its result. Otherwise, return `nil`. func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> /// Copy `self` into an unsafe buffer, returning a partially-consumed /// iterator with any elements that didn't fit remaining. func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @_inlineable public func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. @_versioned @_fixed_layout internal class _DropFirstSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal var _iterator: Base @_versioned internal let _limit: Int @_versioned internal var _dropped: Int @_versioned @_inlineable internal init(_iterator: Base, limit: Int, dropped: Int = 0) { self._iterator = _iterator self._limit = limit self._dropped = dropped } @_versioned @_inlineable internal func makeIterator() -> _DropFirstSequence<Base> { return self } @_versioned @_inlineable internal func next() -> Base.Element? { while _dropped < _limit { if _iterator.next() == nil { _dropped = _limit return nil } _dropped += 1 } return _iterator.next() } @_versioned @_inlineable internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already taken from the underlying sequence. @_fixed_layout @_versioned internal class _PrefixSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal let _maxLength: Int @_versioned internal var _iterator: Base @_versioned internal var _taken: Int @_versioned @_inlineable internal init(_iterator: Base, maxLength: Int, taken: Int = 0) { self._iterator = _iterator self._maxLength = maxLength self._taken = taken } @_versioned @_inlineable internal func makeIterator() -> _PrefixSequence<Base> { return self } @_versioned @_inlineable internal func next() -> Base.Element? { if _taken >= _maxLength { return nil } _taken += 1 if let next = _iterator.next() { return next } _taken = _maxLength return nil } @_versioned @_inlineable internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence( _iterator: _iterator, maxLength: Swift.min(maxLength, self._maxLength), taken: _taken)) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. @_fixed_layout @_versioned internal class _DropWhileSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal var _iterator: Base @_versioned internal var _nextElement: Base.Element? @_versioned @_inlineable internal init( iterator: Base, nextElement: Base.Element?, predicate: (Base.Element) throws -> Bool ) rethrows { self._iterator = iterator self._nextElement = nextElement ?? _iterator.next() while try _nextElement.flatMap(predicate) == true { _nextElement = _iterator.next() } } @_versioned @_inlineable internal func makeIterator() -> _DropWhileSequence<Base> { return self } @_versioned @_inlineable internal func next() -> Base.Element? { guard _nextElement != nil else { return _iterator.next() } let next = _nextElement _nextElement = nil return next } @_versioned @_inlineable internal func drop( while predicate: (Base.Element) throws -> Bool ) rethrows -> AnySequence<Base.Element> { // If this is already a _DropWhileSequence, avoid multiple // layers of wrapping and keep the same iterator. return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: _nextElement, predicate: predicate)) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @_inlineable public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.characters.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `includeElement` allowed. @_inlineable public func filter( _ isIncluded: (Iterator.Element) throws -> Bool ) rethrows -> [Iterator.Element] { var result = ContiguousArray<Iterator.Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func suffix(_ maxLength: Int) -> AnySequence<Iterator.Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Iterator.Element] = [] ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i += 1 i %= maxLength } } if i != ringBuffer.startIndex { let s0 = ringBuffer[i..<ringBuffer.endIndex] let s1 = ringBuffer[0..<i] return AnySequence([s0, s1].joined()) } return AnySequence(ringBuffer) } /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.characters.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [AnySequence<Iterator.Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [AnySequence<Iterator.Element>] = [] var subSequence: [Iterator.Element] = [] @discardableResult func appendSubsequence() -> Bool { if subSequence.isEmpty && omittingEmptySubsequences { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplits == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var iterator = self.makeIterator() while let element = iterator.next() { if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplits { break } } else { subSequence.append(element) } } while let element = iterator.next() { subSequence.append(element) } appendSubsequence() return result } /// Returns a value less than or equal to the number of elements in /// the sequence, nondestructively. /// /// - Complexity: O(*n*) @_inlineable public var underestimatedCount: Int { return 0 } @_inlineable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return nil } @_inlineable public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_inlineable public func forEach( _ body: (Iterator.Element) throws -> Void ) rethrows { for element in self { try body(element) } } } @_versioned @_fixed_layout internal enum _StopIteration : Error { case stop } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @_inlineable public func first( where predicate: (Iterator.Element) throws -> Bool ) rethrows -> Iterator.Element? { var foundElement: Iterator.Element? do { try self.forEach { if try predicate($0) { foundElement = $0 throw _StopIteration.stop } } } catch is _StopIteration { } return foundElement } } extension Sequence where Iterator.Element : Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.characters.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [AnySequence<Iterator.Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence where SubSequence : Sequence, SubSequence.Iterator.Element == Iterator.Element, SubSequence.SubSequence == SubSequence { /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1). @_inlineable public func dropFirst(_ n: Int) -> AnySequence<Iterator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) } /// Returns a subsequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast(_ n: Int) -> AnySequence<Iterator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Iterator.Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Iterator.Element] = [] var ringBuffer: [Iterator.Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = ringBuffer.index(after: i) % n } } return AnySequence(result) } /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. /// - SeeAlso: `prefix(while:)` @_inlineable public func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> AnySequence<Iterator.Element> { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @_inlineable public func prefix(_ maxLength: Int) -> AnySequence<Iterator.Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Iterator.Element>()) } return AnySequence( _PrefixSequence(_iterator: makeIterator(), maxLength: maxLength)) } /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. /// - SeeAlso: `drop(while:)` @_inlineable public func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> AnySequence<Iterator.Element> { var result: [Iterator.Element] = [] for element in self { guard try predicate(element) else { break } result.append(element) } return AnySequence(result) } } extension Sequence { /// Returns a subsequence containing all but the first element of the /// sequence. /// /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the /// sequence. /// /// - Complexity: O(1) @_inlineable public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast() -> SubSequence { return dropLast(1) } } extension Sequence { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are /// initialized. @_inlineable public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @_fixed_layout public struct IteratorSequence< Base : IteratorProtocol > : IteratorProtocol, Sequence { /// Creates an instance whose iterator is a copy of `base`. @_inlineable public init(_ base: Base) { _base = base } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @_inlineable public mutating func next() -> Base.Element? { return _base.next() } @_versioned internal var _base: Base } @available(*, unavailable, renamed: "IteratorProtocol") public typealias GeneratorType = IteratorProtocol @available(*, unavailable, renamed: "Sequence") public typealias SequenceType = Sequence extension Sequence { @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument") public func split(_ maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Sequence where Iterator.Element : Equatable { @available(*, unavailable, message: "call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Iterator.Element>] { Builtin.unreachable() } } @available(*, unavailable, renamed: "IteratorSequence") public struct GeneratorSequence<Base : IteratorProtocol> {}
apache-2.0
ab12dbf3fef39a9aca1da306c0ffb3cf
35.94657
149
0.63284
4.287431
false
false
false
false
shaps80/InkKit
Example/InkKit/CanvasViewController.swift
1
5376
/* Copyright © 13/05/2016 Shaps Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import InkKit final class CanvasView: UIView { // private var table: Grid! @IBOutlet var slider: UISlider! @IBAction func valueChanged(_ slider: UISlider) { setNeedsDisplay() } override func draw(_ dirtyRect: CGRect) { super.draw(dirtyRect) let bgFrame = dirtyRect let titleBarHeight: CGFloat = 44 let margin: CGFloat = 0 let topGuide = titleBarHeight let barFrame = CGRect(x: 0, y: 0, width: bgFrame.width, height: topGuide) let tableFrame = CGRect(x: 0, y: barFrame.maxY + margin, width: bgFrame.width, height: bgFrame.maxY - barFrame.height) guard let context = CGContext.current else { return } context.fill(rect: bgFrame, color: Color(hex: "1c3d64")!) // Table let grid = Grid(colCount: 6, rowCount: 9, bounds: tableFrame) let path = grid.path(include: [.columns, .rows]) context.stroke(path: path, startColor: Color(white: 1, alpha: 0.15), endColor: Color(white: 1, alpha: 0.05), angleInDegrees: 90) // Cell let rect = grid.boundsForRange(sourceColumn: 2, sourceRow: 3, destinationColumn: 4, destinationRow: 6) drawCell(in: rect, title: "4x6", includeBorder: true, includeShadow: true) // Navigation Bar context.draw(shadow: .outer, path: BezierPath(rect: barFrame), color: Color(white: 0, alpha: 0.4), radius: 5, offset: CGSize(width: 0, height: 1)) context.fill(rect: barFrame, color: Color(hex: "ff0083")!) "InkKit".drawAligned(to: barFrame, attributes: [ .foregroundColor: Color.white.uiColor, .font: Font(name: "Avenir-Book", size: 20)! ]) backIndicatorImage().draw(in: CGRect(x: 20, y: 11, width: 12, height: 22)) grid.enumerateCells { (index, col, row, bounds) in "\(index)".drawAligned(to: bounds, attributes: [ .font: Font(name: "Avenir-Book", size: 12)!, .foregroundColor: Color(white: 1, alpha: 0.5).uiColor ]) } drawInnerGrid(in: grid.boundsForRange(sourceColumn: 1, sourceRow: 1, destinationColumn: 1, destinationRow: 1)) } func drawInnerGrid(in bounds: CGRect) { let grid = Grid(colCount: 3, rowCount: 3, bounds: bounds) let path = grid.path(include: [ .outline, .columns, .rows ]) Color.white.setStroke() path.stroke() } func drawCell(in bounds: CGRect, title: String, includeBorder: Bool = false, includeShadow: Bool = false) { guard let context = CGContext.current else { return } let path = BezierPath(roundedRect: bounds, cornerRadius: 4) context.fill(path: path, color: Color(hex: "ff0083")!.with(alpha: 0.3)) if includeShadow { context.draw(shadow: .inner, path: path, color: Color(white: 0, alpha: 0.3), radius: 20, offset: CGSize(width: 0, height: 5)) } if includeBorder { context.stroke(border: .inner, path: path, color: Color(hex: "ff0083")!, thickness: 2) } title.drawAligned(to: bounds, attributes: [ .foregroundColor: Color.white.uiColor, .font: Font(name: "Avenir-Medium", size: 15)! ]) } func backIndicatorImage() -> Image { return Image.draw(width: 12, height: 22, attributes: nil, drawing: { (context, rect, attributes) in attributes.lineWidth = 2 attributes.strokeColor = Color.white let bezierPath = BezierPath() bezierPath.move(to: CGPoint(x: rect.maxX, y: rect.minY)) bezierPath.addLine(to: CGPoint(x: rect.maxX - 10, y: rect.midY)) bezierPath.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) attributes.apply(to: bezierPath) bezierPath.stroke() }) } } final class CanvasViewController: UIViewController { @IBOutlet var canvasView: CanvasView! override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) animate() } func animate() { canvasView.slider.value += 1; canvasView.setNeedsDisplay() if canvasView.slider.value == canvasView.slider.maximumValue { return } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { self.animate() } } }
mit
78cc014b793617779a4aa9ca56798e7f
34.130719
150
0.673302
3.955114
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Maps/Map reference scale/MapReferenceScaleLayerSelectionViewController.swift
1
4397
// // Copyright © 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 UIKit import ArcGIS /// The delegate of a `MapReferenceScaleLayerSelectionViewController`. protocol MapReferenceScaleLayerSelectionViewControllerDelegate: AnyObject { /// Tells the delegate that the given layer was selected. /// /// - Parameters: /// - controller: The controller sending the message. /// - layer: The layer that was selected. func mapReferenceScaleLayerSelectionViewController(_ controller: MapReferenceScaleLayerSelectionViewController, didSelect layer: AGSLayer) /// Tells the delegate the the given layer was deselected. /// /// - Parameters: /// - controller: The controller sending the message. /// - layer: The layer that was deselected. func mapReferenceScaleLayerSelectionViewController(_ controller: MapReferenceScaleLayerSelectionViewController, didDeselect layer: AGSLayer) } /// A view controller that manages an interface for selecting layers from a /// list. class MapReferenceScaleLayerSelectionViewController: UITableViewController { /// The layers shown in the table view. var layers = [AGSLayer]() { didSet { guard isViewLoaded else { return } tableView.reloadData() } } /// The delegate of the view controller. weak var delegate: MapReferenceScaleLayerSelectionViewControllerDelegate? /// The index paths of the selected layers. private var indexPathsForSelectedRows = Set<IndexPath>() /// Selects the given layer in the list. /// /// - Parameter layer: A layer. func selectLayer(_ layer: AGSLayer) { guard let row = layers.firstIndex(of: layer) else { return } let indexPath = IndexPath(row: row, section: 0) indexPathsForSelectedRows.insert(indexPath) } /// Returns the appropriate accessory type for the cell at the given index /// path. /// /// - Parameter indexPath: An index path. /// - Returns: An accessory type. If the corresponding layer is selected, /// the type is `checkmark`. Otherwise the type is `none`. private func accessoryTypeForCell(at indexPath: IndexPath) -> UITableViewCell.AccessoryType { return indexPathsForSelectedRows.contains(indexPath) ? .checkmark : .none } } extension MapReferenceScaleLayerSelectionViewController /* UITableViewDataSource */ { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return layers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LayerCell", for: indexPath) cell.textLabel?.text = layers[indexPath.row].name cell.accessoryType = accessoryTypeForCell(at: indexPath) return cell } } extension MapReferenceScaleLayerSelectionViewController /* UITableViewDelegate */ { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let layer = layers[indexPath.row] let cell = tableView.cellForRow(at: indexPath) if indexPathsForSelectedRows.contains(indexPath) { indexPathsForSelectedRows.remove(indexPath) cell?.accessoryType = accessoryTypeForCell(at: indexPath) delegate?.mapReferenceScaleLayerSelectionViewController(self, didDeselect: layer) } else { indexPathsForSelectedRows.insert(indexPath) cell?.accessoryType = accessoryTypeForCell(at: indexPath) delegate?.mapReferenceScaleLayerSelectionViewController(self, didSelect: layer) } } }
apache-2.0
a2196f2f80a01e9222e76405023aa717
41.269231
144
0.709281
5.245823
false
false
false
false
jasperscholten/programmeerproject
JasperScholten-project/FormsListVC.swift
1
6366
// // FormsListVC.swift // JasperScholten-project // // Created by Jasper Scholten on 19-01-17. // Copyright © 2017 Jasper Scholten. All rights reserved. // // This ViewController deals with management of an organisation's reviewforms. New forms can be created, but existing forms can also be deleted. import UIKit import Firebase class FormsListVC: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Constants and variables let formsRef = FIRDatabase.database().reference(withPath: "Forms") let questionsRef = FIRDatabase.database().reference(withPath: "Questions") var nameInput = String() var organisation = String() var organisationID = String() var forms = [Form]() var formID = String() // MARK: - Outlets @IBOutlet weak var formsListTableView: UITableView! // MARK: - UIViewController lifecycle override func viewDidLoad() { super.viewDidLoad() // Retrieve available reviewforms from Firebase. formsRef.observe(.value, with: { snapshot in var newForms: [Form] = [] for item in snapshot.children { let formData = Form(snapshot: item as! FIRDataSnapshot) if formData.organisationID == self.organisationID { newForms.append(formData) } } self.forms = newForms self.formsListTableView.reloadData() }) } // MARK: - Tableview Population func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return forms.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = formsListTableView.dequeueReusableCell(withIdentifier: "formListCell", for: indexPath) as! FormListCell cell.formName.text = forms[indexPath.row].formName return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { formsListTableView.deselectRow(at: indexPath, animated: true) nameInput = forms[indexPath.row].formName formID = forms[indexPath.row].formID performSegue(withIdentifier: "newForm", sender: nil) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let form = forms[indexPath.row].formID formsRef.child(form).removeValue { (error, ref) in if error != nil { self.alertSingleOption(titleInput: "Er is iets misgegaan met verwijderen van het formulier", messageInput: error as! String) self.deleteFormQuestions(formID: form) } } } } // MARK: - Actions @IBAction func addNewForm(_ sender: Any) { addNewForm() } // MARK: - Functions func addNewForm() { let alert = UIAlertController(title: "Nieuwe vragenlijst", message: "Wil je een nieuwe vragenlijst gaan opstellen?", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Lijstnaam" } let newFormAction = UIAlertAction(title: "OK", style: .default) { action in let text = alert.textFields?[0].text if text != nil && text!.characters.count>0 { self.addFormToFirebase(text: text!) } else { self.formNameError() } } let cancelAction = UIAlertAction(title: "Annuleren", style: .default) alert.addAction(newFormAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } func addFormToFirebase(text: String) { let newRef = self.formsRef.childByAutoId() let newFormID = newRef.key self.nameInput = text self.formID = newFormID let form = Form(formName: text, formID: newFormID, organisationID: self.organisationID) newRef.setValue(form.toAnyObject()) self.performSegue(withIdentifier: "newForm", sender: nil) } func formNameError() { let alert = UIAlertController(title: "Lege naam", message: "Geef de nieuwe lijst een naam om 'm te kunnen aanmaken.", preferredStyle: .alert) let acceptAction = UIAlertAction(title: "OK", style: .default) { action in self.addNewForm() } alert.addAction(acceptAction) self.present(alert, animated: true, completion: nil) } func deleteFormQuestions(formID: String) { // Find questions of deleted form, then delete these as well. questionsRef.observe(.value, with: { snapshot in for item in snapshot.children { let question = Questions(snapshot: item as! FIRDataSnapshot) if question.formID == formID { self.questionsRef.child(question.questionID).removeValue { (error, ref) in if error != nil { self.alertSingleOption(titleInput: "Er is iets misgegaan met verwijderen van het formulier", messageInput: error as! String) } } } } }) } // Segue details of newly created form. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let choice = segue.destination as? AddFormVC { choice.form = nameInput choice.organisation = organisation choice.organisationID = organisationID choice.formID = formID } } }
apache-2.0
726bd43bf14bbfeee71be9fcb2b8338b
38.534161
145
0.554595
5.075758
false
false
false
false
masters3d/xswift
exercises/trinary/Sources/TrinaryExample.swift
1
943
#if os(Linux) import Glibc #elseif os(OSX) import Darwin #endif extension Int { init(_ value: Trinary) { self = value.toDecimal } } struct Trinary { private var stringValue = "" fileprivate var toDecimal: Int = 0 private func isValidTrinary() -> Bool { return (Int(stringValue) ?? -1) > -1 ? true : false } private func tri2int(_ input: String) -> Int { let orderedInput = Array(input.characters.reversed()) let enumarated = orderedInput.enumerated() var tempInt: Int = 0 for (inx, each) in enumarated { let tempCharInt = Int("\(each)") ?? 0 let tempTriPower = Int(pow(Double(3), Double(inx))) tempInt += tempTriPower * tempCharInt } return tempInt } init( _ sv: String) { self.stringValue = sv if isValidTrinary() { self.toDecimal = tri2int(sv) } } }
mit
00b87a24033c194f9dbd8fdeef689220
22.575
63
0.562036
3.817814
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/Categories/UIView+Additions.swift
1
1018
import Foundation public extension UIView { func removeAllSubviews() { let subviewsToRemove = self.subviews for view in subviewsToRemove { view.removeFromSuperview() } } @discardableResult func addBlurEffect(with style: UIBlurEffect.Style) -> UIVisualEffectView { backgroundColor = UIColor.clear let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) addSubview(blurEffectView) blurEffectView.autoPinEdgesToSuperviewEdges() sendSubviewToBack(blurEffectView) return blurEffectView } func hl_didHitViewOfClass(allowedClasses: [UIView.Type], point: CGPoint) -> UIView? { var hitView = hitTest(point, with: nil) while hitView != nil { if allowedClasses.contains(where: { $0 == type(of: hitView!) }) { return hitView } hitView = hitView?.superview } return nil } }
mit
654fd121da0054c4b38517785e56c40b
28.941176
89
0.630648
5.414894
false
false
false
false
yaobanglin/viossvc
viossvc/General/Base/SegmentedViewController.swift
3
4279
// // SegmentedViewController.swift // viossvc // // Created by yaowang on 2016/10/28. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation @objc protocol SegmentedViewControllerProtocol { optional func segmentedViewController(index:Int) -> UIViewController?; optional func segmentedViewControllerIdentifiers() -> [String]!; } class SegmentedViewController: UIViewController , SegmentedViewControllerProtocol { @IBOutlet weak var segmentedControl: UISegmentedControl! private var courrentShowController:UIViewController? = nil; private var dictViewControllers:Dictionary<Int,UIViewController!> = Dictionary<Int,UIViewController!>(); override func viewDidLoad() { super.viewDidLoad(); initSegmentedControl(); reloadViewControllers(); } final func reloadViewControllers() { for(_,viewController) in dictViewControllers { viewController.willMoveToParentViewController(nil); viewController.removeFromParentViewController(); } dictViewControllers.removeAll(); segmentedControl.sendActionsForControlEvents(.ValueChanged); } func contentRect() -> CGRect { var rect:CGRect = view.frame; rect.origin.y = 0.0; return rect; } final func didActionChangeValue(sender: AnyObject) { if sender.isKindOfClass(UISegmentedControl) { showViewController(segmentedControl.selectedSegmentIndex); } } final func showViewController(index:Int) { segmentedControl.selectedSegmentIndex = index; _showViewController(getViewControllerAtIndex(index)); } final func _showViewController(viewController:UIViewController?) { if viewController != nil { if courrentShowController != nil { segmentedControl.userInteractionEnabled = false self.transitionFromViewController(courrentShowController!, toViewController: viewController!, duration: 0.1, options: .CurveEaseInOut, animations: nil, completion: { (Bool) in if Bool { self.segmentedControl.userInteractionEnabled = true viewController?.didMoveToParentViewController(self); self.courrentShowController = viewController!; } }); } else { self.courrentShowController = viewController!; view .addSubview(viewController!.view); } } } final func getViewControllerAtIndex(index:Int) -> UIViewController? { var viewController:UIViewController? = dictViewControllers[index]; if viewController == nil { viewController = createViewController(index); if viewController != nil { dictViewControllers[index] = viewController; addChildViewController(viewController!); viewController!.view.frame = contentRect(); } } return viewController; } final func createViewController(index:Int) -> UIViewController? { let svcProtocol:SegmentedViewControllerProtocol = self as SegmentedViewControllerProtocol; if( svcProtocol.segmentedViewController != nil ) { return svcProtocol.segmentedViewController?(index); } if( svcProtocol.segmentedViewControllerIdentifiers != nil ) { let identifiers:[String]! = svcProtocol.segmentedViewControllerIdentifiers!(); return storyboard?.instantiateViewControllerWithIdentifier(identifiers[index]); } return nil; } private func initSegmentedControl() { let textAttr = [NSForegroundColorAttributeName:UIColor.whiteColor()/*,NSFontAttributeName:UIFont.systemFontOfSize(15)*/]; segmentedControl.setTitleTextAttributes(textAttr, forState: UIControlState.Normal); segmentedControl.setTitleTextAttributes(textAttr, forState: UIControlState.Selected); segmentedControl.addTarget(self, action: #selector(didActionChangeValue(_:)), forControlEvents:.ValueChanged); } }
apache-2.0
3b2a84e407b9eab18e7ebe89b7dce156
36.182609
191
0.654116
6.224163
false
false
false
false
johannes82/OpenHome
OpenHome/AccessoryTableViewController.swift
1
4610
// // AccessoryTableViewController.swift // OpenHome // // Created by Johannes on 10.05.16. // Copyright © 2016 Johannes Steudle. All rights reserved. // import UIKit import HomeKit class AccessoryTableViewController: UITableViewController, HMHomeManagerDelegate { let homeManager = HMHomeManager() var activeHome: HMHome? var currentAccessory: HMAccessory? var selectedAccessoryIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() homeManager.delegate = self print("selectedAccessoryIndex \(selectedAccessoryIndex)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "accessoryId", for: indexPath) if indexPath.row == 0 { cell.textLabel?.text = "Name: " cell.detailTextLabel?.text = currentAccessory?.name } else if indexPath.row == 1 { cell.textLabel?.text = "Description: " cell.detailTextLabel?.text = currentAccessory?.description } else if indexPath.row == 2 { cell.textLabel?.text = "Room: " cell.detailTextLabel?.text = currentAccessory?.room?.name } else if indexPath.row == 3 { cell.textLabel?.text = "Category: " cell.detailTextLabel?.text = currentAccessory?.category.localizedDescription } else if indexPath.row == 4 { cell.textLabel?.text = "Services: " cell.detailTextLabel?.text = "\(currentAccessory?.services.count)" } else { print("Unknown row") } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. 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. } */ // MARK: - HomeManager Delegate func homeManagerDidUpdateHomes(_ manager: HMHomeManager) { print("homeManagerDidUpdateHomes") activeHome = homeManager.primaryHome currentAccessory = activeHome?.accessories[selectedAccessoryIndex] print("Current accessory \(currentAccessory)") tableView.reloadData() } }
mit
c44761164d6e4ecf1eca662d93a889d1
36.169355
158
0.68171
5.255416
false
false
false
false
ja-mes/experiments
iOS/Times Tables/Times Tables/AppDelegate.swift
1
6102
// // AppDelegate.swift // Times Tables // // Created by James Brown on 8/4/16. // Copyright © 2016 James Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.Times_Tables" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Times_Tables", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
942def10a05fcd492adecc8b1c0165e0
53.963964
291
0.71939
5.894686
false
false
false
false
digice/ioscxn
Swift/Test/Test.swift
1
1074
// // Test.swift // iOSCxn // // Created by Digices LLC on 6/8/17. // Copyright © 2017 Digices LLC. All rights reserved. // import Foundation class Test { // MARK: - Properties var id: Int? var created: Int? var updated: Int? var first: String? var last: String? // MARK: - Test (self) // init empty object init() { } // ./init // initialize from user interface init(first: String, last: String) { self.first = first self.last = last } // ./initWithFirstandLast // init from json response init(dict: [String:Any]) { if let i = dict["id"] as? String { if let iNum = Int(i) { self.id = iNum } } if let c = dict["created"] as? String { if let cNum = Int(c) { self.created = cNum } } if let u = dict["updated"] as? String { if let uNum = Int(u) { self.updated = uNum } } if let f = dict["first"] as? String { self.first = f } if let l = dict["last"] as? String { self.last = l } } // ./initWithDict }
mit
8002f6b114f5d665d9814098aa2d37b5
14.550725
54
0.535881
3.271341
false
false
false
false
Codility-BMSTU/Codility
Codility/Codility/OBAPIManager.swift
1
9503
// // OBAPIManager.swift // Codility // // Created by Кирилл Володин on 15.09.17. // Copyright © 2017 Кирилл Володин. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class OBAPIManager { class func creditCardsInfoRequest(request: OBCreditCardInfoRequest) -> Void { // let parameters: Parameters = [ // "RqUID": "123e4567-e89b-12d3-a456-426655440000", // "CardName": "" // ] let parameters: Parameters = [ "RqUID": request.rqUID, "CardName": request.cardName ] self.request(URL: OBURLRouter.getCreditCardsInfoURL, method: .post, parameters: parameters, onSuccess: creditCardsInfoOnSuccess, onError: defaultOnError) } private class func creditCardsInfoOnSuccess(json: JSON) -> Void { print(json) let response = OBCreditCardInfoResponse(json: json) NotificationCenter.default.post(name: .creditCardsInfoCallback, object: nil, userInfo: ["data": response]) } class func creditsInfoRequest(request: OBCreditsInfoRequest) -> Void { // let parameters: Parameters = [ // "RqUID": "123e4567-e89b-12d3-a456-426655440000", // "CreditName": "" // ] let parameters: Parameters = [ "RqUID": request.rqUID, "CreditName": request.creditName ] self.request(URL: OBURLRouter.getCreditsInfoURL, method: .post, parameters: parameters, onSuccess: creditsInfoOnSuccess, onError: defaultOnError) } private class func creditsInfoOnSuccess(json: JSON) -> Void { print(json) let response = OBCreditsInfoResponse(json: json) NotificationCenter.default.post(name: .creditsInfoCallback, object: nil, userInfo: ["data": response]) } class func depositsInfoRequest(request: OBDepositsInfoRequest) -> Void { // let parameters: Parameters = [ // "RqUID": "123e4567-e89b-12d3-a456-426655440000", // "CreditName": "" // ] let parameters: Parameters = [ "RqUID": request.rqUID, "DepositName": request.depositName ] self.request(URL: OBURLRouter.getDepositsInfoURL, method: .post, parameters: parameters, onSuccess: depositsInfoOnSuccess, onError: defaultOnError) } private class func depositsInfoOnSuccess(json: JSON) -> Void { print(json) let response = OBDepositsInfoResponse(json: json) NotificationCenter.default.post(name: .depositsInfoCallback, object: nil, userInfo: ["data": response]) } class func myCardsRequest() -> Void { let parameters: Parameters = [ : ] self.request(URL: OBURLRouter.getMyCardsURL, method: .get, parameters: parameters, onSuccess: myCardsOnSuccess, onError: defaultOnError) } private class func myCardsOnSuccess(json: JSON) -> Void { print(json) let response = OBMyCardsResponse(json: json) OBDatabaseManager.saveCards(response: response) // for card in response.cards { // let myInforequest = OBMyCardInfoRequest() // } NotificationCenter.default.post(name: .myCardsCallback, object: nil, userInfo: ["data": response]) } class func myCardInfoRequest(request: OBMyCardInfoRequest) -> Void { let parameters: Parameters = [ "CardId": request.id ] self.request(URL: OBURLRouter.getMyCardInfoURL, method: .post, parameters: parameters, onSuccess: myCardInfoOnSuccess, onError: defaultOnError) } private class func myCardInfoOnSuccess(json: JSON) -> Void { print(json) let response = OBMyCardInfoResponse(json: json) NotificationCenter.default.post(name: .myCardInfoCallback, object: nil, userInfo: ["data": response]) } //balance class func myCardBalanceRequest(request: OBMyCardBalanceRequest) -> Void { let parameters: Parameters = [ "CardId": request.id ] self.request(URL: OBURLRouter.getMyCardBalanceURL, method: .post, parameters: parameters, onSuccess: myCardBalanceOnSuccess, onError: defaultOnError) } private class func myCardBalanceOnSuccess(json: JSON) -> Void { print(json) let response = OBMyCardBalanceResponse(json: json) NotificationCenter.default.post(name: .myCardBalanceCallback, object: nil, userInfo: ["data": response]) } //history class func myCardHistoryRequest(request: OBMyCardHistoryRequest) -> Void { let parameters = [ "CardId": "44" ] // var headers = Alamofire.SessionManager.defaultHTTPHeaders // headers["User-Agent"] = "iPhone" self.request(URL: OBURLRouter.getMyCardHistoryURL, method: .post, parameters: parameters, onSuccess: myCardHistoryOnSuccess, onError: defaultOnError) } private class func myCardHistoryOnSuccess(json: JSON) -> Void { print(json) let response = OBMyCardHistoryResponse(json: json) NotificationCenter.default.post(name: .myCardHistoryCallback, object: nil, userInfo: ["data": response]) } //invoicing class func createInvoiceRequest(request: OBCreateInvoiceRequest) -> Void { let parameters: Parameters = [ "RqUID": "123e4567-e89b-12d3-a456-426655440000", "InvoiceCreateNumber": 123456789, "InvoiceCreateDate": "01.01.2017", "InvoiceCreateSum": request.invoiceCreateSum, "InvoiceCreatePayerINN": request.invoiceCreatePayerINN, "InvoiceCreatePayerAcc": request.invoiceCreatePayerAcc, "InvoiceCreatePayerBIK": request.invoiceCreatePayerBIK, "InvoiceCreatePayerCorrAcc": request.invoiceCreatePayerCorrAcc, "InvoiceCreatePayerBankname": request.invoiceCreatePayerBankname, "InvoiceCreatePayeeINN": request.invoiceCreatePayeeINN, "InvoiceCreatePayeeAcc": request.invoiceCreatePayeeAcc, "InvoiceCreatePayeeBIK": request.invoiceCreatePayeeBIK, "InvoiceCreatePayeeCorrAcc": request.invoiceCreatePayeeCorrAcc, "InvoiceCreatePayeeBankname": request.invoiceCreatePayeeBankname // // "RqUID": "123e4567-e89b-12d3-a456-426655440000", // "InvoiceCreateNumber": "123456789", // "InvoiceCreateDate": "01.01.2017", // "InvoiceCreateSum": "1000.00", // "InvoiceCreatePayerINN": "500100732259", // "InvoiceCreatePayerAcc": "40702810438290000000", // "InvoiceCreatePayerBIK": "044525985", // "InvoiceCreatePayerCorrAcc": "30101810300000000985", // "InvoiceCreatePayerBankname": "ПАО Банк «ФК Открытие»", // "InvoiceCreatePayeeINN": "500100732260", // "InvoiceCreatePayeeAcc": "40702810138170000000", // "InvoiceCreatePayeeBIK": "044525985", // "InvoiceCreatePayeeCorrAcc": "30101810300000000985", // "InvoiceCreatePayeeBankname": "ПАО Банк «ФК Открытие»" ] self.requestPOST(URL: OBURLRouter.getCreateInvoiceURL, method: .post, parameters: parameters, onSuccess: createInvoiceOnSuccess, onError: defaultOnError) } private class func createInvoiceOnSuccess(json: JSON) -> Void { print(json) let response = OBCreateInvoiceResponse(json: json) NotificationCenter.default.post(name: .createInvoiceCallback, object: nil, userInfo: ["data": response]) } private class func defaultOnSuccess(json: JSON) -> Void{ print(json) } private class func defaultOnError(error: Any) -> Void { print(error) } private class func request(URL: String, method: HTTPMethod, parameters: Parameters, onSuccess: @escaping (JSON) -> Void , onError: @escaping (Any) -> Void) -> Void { Alamofire.request(URL, method: method, parameters: parameters).responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) onSuccess(json) case .failure(let error): onError(error) } } } private class func requestPOST(URL: String, method: HTTPMethod, parameters: Parameters, onSuccess: @escaping (JSON) -> Void , onError: @escaping (Any) -> Void) -> Void { Alamofire.request(URL, method: method, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) onSuccess(json) case .failure(let error): onError(error) } } } }
apache-2.0
27b2ac51bba2b58b00d2273853d67e51
37.210526
173
0.599703
4.39181
false
false
false
false
mukeshthawani/UXMPDFKit
Pod/Classes/Renderer/PDFThumbnailViewController.swift
1
4033
// // PDFThumbnailViewController.swift // Pods // // Created by Chris Anderson on 11/14/16. // // import UIKit public protocol PDFThumbnailViewControllerDelegate { func thumbnailCollection(_ collection: PDFThumbnailViewController, didSelect page: Int) } open class PDFThumbnailViewController: UIViewController { var document: PDFDocument! var collectionView: UICollectionView! private var flowLayout: UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20) layout.minimumLineSpacing = 0.0 layout.minimumInteritemSpacing = 0.0 return layout } var delegate: PDFThumbnailViewControllerDelegate? public init(document: PDFDocument) { super.init(nibName: nil, bundle: nil) self.document = document } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func viewDidLoad() { super.viewDidLoad() collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout) collectionView.delegate = self collectionView.dataSource = self self.collectionView.register(PDFThumbnailViewCell.self, forCellWithReuseIdentifier: "ThumbnailCell") self.setupUI() } func setupUI() { self.title = "Pages" self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(PDFThumbnailViewController.tappedDone)) view.addSubview(collectionView) collectionView.backgroundColor = UIColor.white collectionView.alwaysBounceVertical = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } @IBAction func tappedDone() { self.dismiss(animated: true, completion: nil) } } extension PDFThumbnailViewController: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let document = self.document else { return 0 } return document.pageCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "ThumbnailCell", for: indexPath) as! PDFThumbnailViewCell let page = indexPath.row + 1 cell.configure(document: document, page: page) return cell } } extension PDFThumbnailViewController: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.delegate?.thumbnailCollection(self, didSelect: indexPath.row + 1) } } extension PDFThumbnailViewController: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let bounds = document.boundsForPDFPage(indexPath.row + 1) return CGSize(width: 100, height: 100 / bounds.width * bounds.height) } }
mit
4571b1882266756e250ca0d0d70250cc
35.333333
167
0.672948
5.861919
false
false
false
false
x-du/VeriJSON-Swift
VeriJSON/VeriJSON.swift
1
12880
// // VeriJSON.swift // VeriJSON-Swift // // Created by Du, Xiaochen (Harry) on 3/6/15. // Copyright (c) 2015 Where Here. All rights reserved. // import Foundation #if os(iOS) import UIKit typealias SKColor = UIColor #elseif os(OSX) import Cocoa typealias SKColor = NSColor #endif enum VeriJSONErrorCode : Int { case InvalidPattern = 1 } let VeriJSONErrorDomain = "VeriJSONErrorDomain" public class VeriJSON { public func verifyJSON(json:AnyObject?, pattern:AnyObject?) -> Bool { do { try verifyJSONThrow(json, pattern: pattern) return true } catch { return false } } func verifyJSONThrow(json:AnyObject?, pattern:AnyObject?) throws { var error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil) if let pattern: AnyObject = pattern { if let json: AnyObject = json { let patternStack:NSMutableArray = NSMutableArray(array:[""]) let valid = verifyValue(json, pattern: pattern, permitNull: false, patternStack: patternStack) if (!valid && true) { error = buildErrorFromPatternStack(patternStack) } if valid { return } throw error } else { //json missing -> Reject any throw error } } else { //pattern missing -> Accept any return } } internal func verifyValue(value:AnyObject, pattern:AnyObject, permitNull:Bool, patternStack:NSMutableArray) -> Bool { switch value { case _ as NSNull: return permitNull case let value as NSDictionary: if let pattern = pattern as? NSDictionary { return verifyObject(value, pattern: pattern, patternStack: patternStack) } else { return false } case let value as NSArray: if let pattern = pattern as? NSArray { return verifyArray(value, pattern:pattern, patternStack: patternStack) } else { return false } default: if let pattern = pattern as? NSString { return verifyBaseValue(value, pattern:pattern as String, patternStack:patternStack) } else { return false } } } internal func verifyObject(value:NSDictionary, pattern:NSDictionary, patternStack:NSMutableArray) -> Bool { var valid = true pattern.enumerateKeysAndObjectsUsingBlock { (attributeName, attributePattern, stop) -> Void in patternStack.addObject(attributeName) let attributeValid = self.verifyObject(value,attributeName:attributeName as! NSString, attributePattern:attributePattern, patternStack:patternStack) if attributeValid { patternStack.removeLastObject() } else { valid = false stop.memory = true } } return valid } internal func verifyObject(object:NSDictionary, attributeName:NSString, attributePattern:AnyObject, patternStack:NSMutableArray) -> Bool { let isOptional = self.isOptionalAttribute(attributeName) let name = self.strippedAttributeName(attributeName) if let value: AnyObject = object.objectForKey(name) { return self.verifyValue(value, pattern: attributePattern, permitNull: isOptional, patternStack: patternStack) } return isOptional } internal func verifyArray(array:NSArray, pattern:NSArray, patternStack:NSMutableArray) -> Bool { if pattern.count == 0 { return true // Pattern is empty array. It accepts any size of array. } else if array.count == 0 { return false //Pattern is not empty. It rejects empty array. } //Here, both array Pattern and array are not empty if let valuePattern: AnyObject? = pattern.firstObject { var valid = true array.enumerateObjectsUsingBlock { (value, index, stop) -> Void in if !self.verifyValue(value, pattern: valuePattern!, permitNull: false, patternStack: patternStack) { valid = false stop.memory = true } } return valid } else { return false } } internal func verifyBaseValue(value:AnyObject, pattern:String, patternStack:NSMutableArray) -> Bool { patternStack.addObject(pattern) var valid = false if "string" == pattern || pattern.hasPrefix("string:") { if let value = value as? NSString { valid = verifyString(value as String, pattern:pattern) } else { valid = false } } else if "number" == pattern || pattern.hasPrefix("number:") { if let value = value as? NSNumber { valid = verifyNumber(value, pattern: pattern) } else { valid = false } } else if "int" == pattern || pattern.hasPrefix("int:") { if let value = value as? NSNumber { if isNumberFromInt(value) { valid = verifyNumber(value, pattern: pattern) } else { valid = false } } else { valid = false } } else if "bool" == pattern { if let _ = value as? NSNumber { valid = true } else { valid = false } } else if "url" == pattern { valid = verifyURL(value) } else if "url:http" == pattern { valid = verifyHTTPURL(value) } else if "email" == pattern { valid = verifyEmail(value) } else if "color" == pattern { valid = verifyColor(value) } else if "*" == pattern { valid = !(value is NSArray && value is NSDictionary) } else if pattern.hasPrefix("[") { //Multipal types. Only support basic type names. Doesn't support regular expression completely. let pattern = pattern.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " \t\n\r][")) let types = pattern.componentsSeparatedByString("|") for type in types { valid = verifyBaseValue(value, pattern: type, patternStack: patternStack) if valid {break} } } if valid { patternStack.removeLastObject() } return valid } internal func isNumberFromInt(value:NSNumber) -> Bool { let numberType = CFNumberGetType(value) return numberType == CFNumberType.IntType || numberType == CFNumberType.ShortType || numberType == CFNumberType.SInt8Type || numberType == CFNumberType.SInt16Type || numberType == CFNumberType.SInt32Type || numberType == CFNumberType.SInt64Type || numberType == CFNumberType.LongType || numberType == CFNumberType.LongLongType } internal func verifyNumber(value:NSNumber, pattern: NSString) -> Bool { let components = pattern.componentsSeparatedByString(":") if components.count < 2 { return true } var valid = true; let range = (components[1] as String).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let rangeValues = range.componentsSeparatedByString(",") if (rangeValues.count == 2) { let minStr = rangeValues[0] let maxStr = rangeValues[1] let min = (minStr.utf16.count == 0) ? -FLT_MIN : (minStr as NSString).floatValue let max = (maxStr.utf16.count == 0) ? -FLT_MAX : (maxStr as NSString).floatValue valid = min <= value.floatValue && max >= value.floatValue } return valid } internal func verifyString(value:String, pattern:String) -> Bool { let components = pattern.componentsSeparatedByString(":") if components.count > 1 { if let regexPattern = components[1] as String? { if let regex = try? NSRegularExpression(pattern: regexPattern, options: NSRegularExpressionOptions(rawValue: 0)) { let numMatches = regex.numberOfMatchesInString(value, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, value.utf16.count)) return numMatches > 0 } } return false } else { return true } } internal func verifyURL(value:AnyObject) -> Bool { return urlFromValue(value) != nil } internal func verifyHTTPURL(value:AnyObject) -> Bool { if let url = urlFromValue(value) { let scheme = url.scheme.lowercaseString let host = url.host return host != nil && (scheme == "http" || scheme == "https") && host!.utf16.count > 0 } else { return false } } internal func verifyEmail(value:AnyObject) -> Bool { if let value = value as? NSString { let emailRegex = "[^@\\s]+@[^.@\\s]+(\\.[^.@\\s]+)+" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex) return emailTest.evaluateWithObject(value) } return false } internal func verifyColor(value:AnyObject) -> Bool { var color:SKColor? if let value = value as? NSString { color = colorWithHexString(value as String) } else if let value = value as? NSNumber { if (value.longValue >= 0 && value.longValue <= 0xFFFFFF) { color = colorWithInt32(value.unsignedIntValue) } else { color = nil } } return color != nil } internal func colorWithInt32(rgbValue: UInt32) -> SKColor? { let r = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let g = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0 let b = CGFloat((rgbValue & 0x0000FF) >> 16) / 255.0 return SKColor(red: r, green: g, blue: b, alpha: 1.0) } internal func colorWithHexString(hex:String) -> SKColor? { var hexNumber: String = "" if hex.hasPrefix("0x") || hex.hasPrefix("0X") { hexNumber = hex.substringFromIndex(hex.startIndex.advancedBy(2)) } if hexNumber.utf16.count != 6 { return nil } let rgbValue = intValueFromHex(hexNumber) return colorWithInt32(rgbValue) } internal func intValueFromHex(hexString:String) -> UInt32 { var result:UInt32 = 0 NSScanner(string:hexString).scanHexInt(&result) return result } internal func urlFromValue(value:AnyObject) -> NSURL? { if let value = value as? String { let value = value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if value.utf16.count == 0 { return nil } else { return NSURL(string: value) } } else { return nil } } internal func isOptionalAttribute(name:NSString) -> Bool { return name.hasSuffix("?") } internal func strippedAttributeName(name:NSString) -> NSString { if isOptionalAttribute(name) { return name.substringToIndex(name.length-1) } else { return name } } internal func buildErrorFromPatternStack(patternStack:NSArray) -> NSError { let path = buildPathFromPatternStack(patternStack) let localizedDescription = "Invalid pattern \(path)" let userInfo = [NSLocalizedDescriptionKey: localizedDescription] return NSError(domain: VeriJSONErrorDomain, code: VeriJSONErrorCode.InvalidPattern.rawValue, userInfo:userInfo) } internal func buildPathFromPatternStack(patternStack:NSArray) -> String { return patternStack.componentsJoinedByString(".") } }
apache-2.0
9247417e884e3d9993c0cf4bf0ed3c7e
31.776081
160
0.547748
5.166466
false
false
false
false
Urinx/SomeCodes
Swift/The Swift Programming Language/16.Automatic_Reference_Counting.playground/section-1.swift
1
3054
// P.546 // Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name println("\(name) is being initialized") } deinit { println("\(name) is being deinitialized") } } var reference1: Person? var reference2: Person? var reference3: Person? reference1 = Person(name: "John Appleseed") reference2 = reference1 reference3 = reference1 reference1 = nil reference2 = nil reference3 = nil // P.552 // Strong Reference Cycles Between Class Instances class Person2 { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } var tenant: Person2? deinit { println("Apartment #\(number) is being deinitialized") } } var john: Person2? var number73: Apartment? john = Person2(name: "John Appleseed") number73 = Apartment(number: 73) john!.apartment = number73 number73!.tenant = john john = nil number73 = nil // P.558 // Resolving Strong Reference Cycles Between Class Instances class Customer { let name: String var card: CreditCard? init(name: String) { self.name = name } deinit { println("\(name) is being deinitialized") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number: UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { println("Card #\(number) is being deinitialized") } } var john2: Customer? = Customer(name: "John Appleseed") john2!.card = CreditCard(number: 1234_5678_9012_3456, customer: john2!) john2 = nil // Unowned References and Implicitly Unwrapped Optional Properties class Country { let name: String let capitalCity: City! init(name: String, capitalName: String) { self.name = name self.capitalCity = City(name: capitalName, country: self) } } class City { let name: String unowned let country: Country init(name: String, country: Country) { self.name = name self.country = country } } var country = Country(name: "Canada", capitalName: "Ottawa") println("\(country.name)'s capital city is called \(country.capitalCity.name)") // P.576 // Strong Reference Cycles for Closures class HTMLElement { let name: String let text: String? var asHTML: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(text)</\(self.name)>" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { println("\(name) is being deinitialized") } } var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world") println(paragraph!.asHTML()) paragraph = nil
gpl-2.0
40cec7fd12c1394fc22bb0c0b904d1c9
20.208333
79
0.62279
3.890446
false
false
false
false
nvh0412/Movie-Flick
FlickMovie/AppDelegate.swift
1
3415
// // AppDelegate.swift // FlickMovie // // Created by Hòa Nguyễn Văn on 5/21/16. // Copyright © 2016 SkyUnity. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyBoard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyBoard.instantiateViewControllerWithIdentifier("MovieNavigationController") as! UINavigationController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MovieViewController nowPlayingViewController.endpoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "playingTabBar") let topRatedNavigationController = storyBoard.instantiateViewControllerWithIdentifier("MovieNavigationController") as! UINavigationController let topRatedViewController = topRatedNavigationController.topViewController as! MovieViewController topRatedViewController.endpoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "ratedTabBar") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
9aff7724fc890425fcce275e3216359a
49.895522
285
0.764516
5.899654
false
false
false
false
nextcloud/ios
iOSClient/Security/NCEndToEndMetadata.swift
1
10549
// // NCEndToEndMetadata.swift // Nextcloud // // Created by Marino Faggiana on 13/11/17. // Copyright © 2017 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import NextcloudKit class NCEndToEndMetadata: NSObject { struct e2eMetadata: Codable { struct metadataKeyCodable: Codable { let metadataKeys: [String: String] let version: Int } struct sharingCodable: Codable { let recipient: [String: String] } struct encryptedFileAttributes: Codable { let key: String let filename: String let mimetype: String let version: Int } struct filesCodable: Codable { let initializationVector: String let authenticationTag: String? let metadataKey: Int // Number of metadataKey let encrypted: String // encryptedFileAttributes } let files: [String: filesCodable] let metadata: metadataKeyCodable let sharing: sharingCodable? } @objc static let shared: NCEndToEndMetadata = { let instance = NCEndToEndMetadata() return instance }() // -------------------------------------------------------------------------------------------- // MARK: Encode / Decode JSON Metadata // -------------------------------------------------------------------------------------------- @objc func encoderMetadata(_ recordsE2eEncryption: [tableE2eEncryption], privateKey: String, serverUrl: String) -> String? { let jsonEncoder = JSONEncoder() var files: [String: e2eMetadata.filesCodable] = [:] var version = 1 var metadataKeysDictionary: [String: String] = [:] for recordE2eEncryption in recordsE2eEncryption { // *** metadataKey *** // Encode64 for Android compatibility let metadatakey = (recordE2eEncryption.metadataKey.data(using: .utf8)?.base64EncodedString())! guard let metadataKeyEncryptedData = NCEndToEndEncryption.sharedManager().encryptAsymmetricString(metadatakey, publicKey: nil, privateKey: privateKey) else { return nil } let metadataKeyEncryptedBase64 = metadataKeyEncryptedData.base64EncodedString() metadataKeysDictionary["\(recordE2eEncryption.metadataKeyIndex)"] = metadataKeyEncryptedBase64 // *** File *** let encrypted = e2eMetadata.encryptedFileAttributes(key: recordE2eEncryption.key, filename: recordE2eEncryption.fileName, mimetype: recordE2eEncryption.mimeType, version: recordE2eEncryption.version) do { // Create "encrypted" let encryptedJsonData = try jsonEncoder.encode(encrypted) let encryptedJsonString = String(data: encryptedJsonData, encoding: .utf8) guard let encryptedEncryptedJson = NCEndToEndEncryption.sharedManager().encryptEncryptedJson(encryptedJsonString, key: recordE2eEncryption.metadataKey) else { print("Serious internal error in encoding metadata") return nil } let e2eMetadataFilesKey = e2eMetadata.filesCodable(initializationVector: recordE2eEncryption.initializationVector, authenticationTag: recordE2eEncryption.authenticationTag, metadataKey: 0, encrypted: encryptedEncryptedJson) files.updateValue(e2eMetadataFilesKey, forKey: recordE2eEncryption.fileNameIdentifier) } catch let error { print("Serious internal error in encoding metadata ("+error.localizedDescription+")") return nil } version = recordE2eEncryption.version } // Create Json metadataKeys // e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: ["0":metadataKeyEncryptedBase64], version: version) let e2eMetadataKey = e2eMetadata.metadataKeyCodable(metadataKeys: metadataKeysDictionary, version: version) // Create final Json e2emetadata let e2emetadata = e2eMetadata(files: files, metadata: e2eMetadataKey, sharing: nil) do { let jsonData = try jsonEncoder.encode(e2emetadata) let jsonString = String(data: jsonData, encoding: .utf8) print("JSON String : " + jsonString!) return jsonString } catch let error { print("Serious internal error in encoding metadata ("+error.localizedDescription+")") return nil } } @discardableResult @objc func decoderMetadata(_ e2eMetaDataJSON: String, privateKey: String, serverUrl: String, account: String, urlBase: String, userId: String) -> Bool { let jsonDecoder = JSONDecoder() let data = e2eMetaDataJSON.data(using: .utf8) // let dataQuickLook = (data as! NSData) do { // *** metadataKey *** let decode = try jsonDecoder.decode(e2eMetadata.self, from: data!) let files = decode.files let metadata = decode.metadata // let sharing = decode.sharing ---> V 2.0 var metadataKeysDictionary: [String: String] = [:] for metadataKeyDictionaryEncrypted in metadata.metadataKeys { guard let metadataKeyEncryptedData: NSData = NSData(base64Encoded: metadataKeyDictionaryEncrypted.value, options: NSData.Base64DecodingOptions(rawValue: 0)) else { return false } guard let metadataKeyBase64 = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(metadataKeyEncryptedData as Data?, privateKey: privateKey) else { return false } // Initialize a `Data` from a Base-64 encoded String let metadataKeyBase64Data = Data(base64Encoded: metadataKeyBase64, options: NSData.Base64DecodingOptions(rawValue: 0))! let metadataKey = String(data: metadataKeyBase64Data, encoding: .utf8) metadataKeysDictionary[metadataKeyDictionaryEncrypted.key] = metadataKey } // *** File *** for file in files { let fileNameIdentifier = file.key let filesCodable = file.value as e2eMetadata.filesCodable let encrypted = filesCodable.encrypted let metadataKey = metadataKeysDictionary["\(filesCodable.metadataKey)"] guard let encryptedFileAttributesJson = NCEndToEndEncryption.sharedManager().decryptEncryptedJson(encrypted, key: metadataKey) else { return false } do { let encryptedFileAttributes = try jsonDecoder.decode(e2eMetadata.encryptedFileAttributes.self, from: encryptedFileAttributesJson.data(using: .utf8)!) if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@", account, fileNameIdentifier)) { let metadata = tableMetadata.init(value: metadata) let object = tableE2eEncryption() object.account = account object.authenticationTag = filesCodable.authenticationTag ?? "" object.fileName = encryptedFileAttributes.filename object.fileNameIdentifier = fileNameIdentifier object.fileNamePath = CCUtility.returnFileNamePath(fromFileName: encryptedFileAttributes.filename, serverUrl: serverUrl, urlBase: urlBase, userId: userId, account: account) object.key = encryptedFileAttributes.key object.initializationVector = filesCodable.initializationVector object.metadataKey = metadataKey! object.metadataKeyIndex = filesCodable.metadataKey object.mimeType = encryptedFileAttributes.mimetype object.serverUrl = serverUrl object.version = encryptedFileAttributes.version // If exists remove records NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNamePath == %@", object.account, object.fileNamePath)) NCManageDatabase.shared.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", object.account, object.fileNameIdentifier)) // Write file parameter for decrypted on DB NCManageDatabase.shared.addE2eEncryption(object) // Update metadata on tableMetadata metadata.fileNameView = encryptedFileAttributes.filename metadata.fileNameWithoutExt = (encryptedFileAttributes.filename as NSString).deletingPathExtension let results = NKCommon.shared.getInternalType(fileName: encryptedFileAttributes.filename, mimeType: metadata.contentType, directory: metadata.directory) metadata.contentType = results.mimeType metadata.iconName = results.iconName metadata.classFile = results.classFile NCManageDatabase.shared.addMetadata(metadata) } } catch let error { print("Serious internal error in decoding metadata ("+error.localizedDescription+")") } } } catch let error { print("Serious internal error in decoding metadata ("+error.localizedDescription+")") return false } return true } }
gpl-3.0
7b30678bce1a9288cb339ae25512df9e
42.407407
239
0.621919
5.395396
false
false
false
false
andreamazz/Tropos
Sources/TroposCore/Models/WeatherUpdate.swift
1
4971
import CoreLocation import Foundation private let TRCurrentConditionsKey = "TRCurrentConditions" private let TRYesterdaysConditionsKey = "TRYesterdaysConditions" private let TRPlacemarkKey = "TRPlacemark" private let TRDateKey = "TRDateAt" @objc(TRWeatherUpdate) public final class WeatherUpdate: NSObject, NSCoding { @objc public let date: Date @objc public let placemark: CLPlacemark private let currentConditionsJSON: [String: Any] fileprivate let yesterdaysConditionsJSON: [String: Any] @objc public init( placemark: CLPlacemark, currentConditionsJSON: [String: Any], yesterdaysConditionsJSON: [String: Any], date: Date ) { self.date = date self.placemark = placemark self.currentConditionsJSON = currentConditionsJSON self.yesterdaysConditionsJSON = yesterdaysConditionsJSON super.init() } @objc public convenience init( placemark: CLPlacemark, currentConditionsJSON: [String: Any], yesterdaysConditionsJSON: [String: Any] ) { self.init( placemark: placemark, currentConditionsJSON: currentConditionsJSON, yesterdaysConditionsJSON: yesterdaysConditionsJSON, date: Date() ) } fileprivate lazy var currentConditions: [String: Any] = { return self.currentConditionsJSON["currently"] as? [String: Any] ?? [:] }() fileprivate lazy var forecasts: [[String: Any]] = { let daily = self.currentConditionsJSON["daily"] as? [String: Any] return daily?["data"] as? [[String: Any]] ?? [] }() fileprivate var todaysForecast: [String: Any] { return forecasts.first ?? [:] } public required init?(coder: NSCoder) { guard let currentConditions = coder.decodeObject(forKey: TRCurrentConditionsKey) as? [String: Any], let yesterdaysConditions = coder.decodeObject(forKey: TRYesterdaysConditionsKey) as? [String: Any], let placemark = coder.decodeObject(forKey: TRPlacemarkKey) as? CLPlacemark, let date = coder.decodeObject(forKey: TRDateKey) as? Date else { return nil } self.currentConditionsJSON = currentConditions self.yesterdaysConditionsJSON = yesterdaysConditions self.placemark = placemark self.date = date } public func encode(with coder: NSCoder) { coder.encode(currentConditionsJSON, forKey: TRCurrentConditionsKey) coder.encode(yesterdaysConditionsJSON, forKey: TRYesterdaysConditionsKey) coder.encode(placemark, forKey: TRPlacemarkKey) coder.encode(date, forKey: TRDateKey) } } public extension WeatherUpdate { @objc var city: String? { return placemark.locality } @objc var state: String? { return placemark.administrativeArea } @objc var conditionsDescription: String? { return currentConditions["icon"] as? String } @objc var precipitationType: String { return (todaysForecast["precipType"] as? String) ?? "rain" } @objc var currentTemperature: Temperature { let rawTemperature = (self.currentConditions["temperature"] as? NSNumber)?.intValue ?? 0 return Temperature(fahrenheitValue: rawTemperature) } @objc var currentHigh: Temperature { let rawHigh = (todaysForecast["temperatureMax"] as? NSNumber)?.intValue ?? 0 if rawHigh > currentTemperature.fahrenheitValue { return Temperature(fahrenheitValue: rawHigh) } else { return currentTemperature } } @objc var currentLow: Temperature { let rawLow = (todaysForecast["temperatureMin"] as? NSNumber)?.intValue ?? 0 if rawLow < currentTemperature.fahrenheitValue { return Temperature(fahrenheitValue: rawLow) } else { return currentTemperature } } @objc var yesterdaysTemperature: Temperature? { let currently = yesterdaysConditionsJSON["currently"] as? [String: Any] let rawTemperature = currently?["temperature"] as? NSNumber guard let fahrenheitValue = rawTemperature?.intValue else { return .none } return Temperature(fahrenheitValue: fahrenheitValue) } @objc var precipitationPercentage: Double { return (todaysForecast["precipProbability"] as? NSNumber)?.doubleValue ?? 0 } @objc var windSpeed: Double { return (currentConditions["windSpeed"] as? NSNumber)?.doubleValue ?? 0 } @objc var windBearing: Double { return (currentConditions["windBearing"] as? NSNumber)?.doubleValue ?? 0 } var dailyForecasts: [DailyForecast] { return (1...3).compactMap { if forecasts.indices.contains($0) { return DailyForecast(json: forecasts[$0]) } else { return nil } } } }
mit
f7fce7dbfdcf375221ca31dc94e6623b
32.362416
111
0.64997
4.729781
false
false
false
false
LittoCats/coffee-mobile
CoffeeMobile/Base/Router/CMRouter.swift
1
1939
// // CMRouter.swift // CoffeeMobile // // Created by 程巍巍 on 5/20/15. // Copyright (c) 2015 Littocats. All rights reserved. // import Foundation protocol CMRouterProtocol { func dispatch(#event: CMRouter.Event, context: AnyObject?) } struct CMRouter { typealias Event = NSURL private static var RouterMap: [String: protocol<CMRouterProtocol>] = [ "CMCT": CTRouter(), // control 主要负责页面的跳转 "CMCM": CommandRouter() // command 负责与界面无关的功能 ] static func post(event: Event, params: [String: AnyObject]? = nil, context: AnyObject? = nil) { var URL = event if params != nil { if let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + NSURL.QueryParser.query(params!) URL = URLComponents.URL! } } if let scheme = URL.scheme { if let router = RouterMap[scheme.uppercaseString] { router.dispatch(event: URL, context: context) } } } static func register(#router: protocol<CMRouterProtocol>, withScheme scheme: String) ->Bool{ RouterMap[scheme] = router return true } } extension CMRouter { struct CTRouter: CMRouterProtocol { init(){ CMRouter.register(router: self, withScheme: "HTTPS") CMRouter.register(router: self, withScheme: "HTTP") } func dispatch(#event: CMRouter.Event, context: AnyObject?){ if let scheme = event.scheme { } } } } extension CMRouter { struct CommandRouter: CMRouterProtocol { func dispatch(#event: CMRouter.Event, context: AnyObject?){ } } }
apache-2.0
f1b09832ca6ccbe92ae33ec63984dddc
28.625
177
0.591557
4.386574
false
false
false
false
utrillavictor/utubeclone
youtube/HomeController.swift
1
2468
// // ViewController.swift // youtube // // Created by Victor Cordero Utrilla on 4/28/17. // Copyright © 2017 utrillavictor. All rights reserved. // import UIKit class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Home" navigationController?.navigationBar.isTranslucent = false let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)) titleLabel.text = "Home" titleLabel.textColor = UIColor.white titleLabel.font = UIFont.systemFont(ofSize: 18) navigationItem.titleView = titleLabel collectionView?.backgroundColor = UIColor.white collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: "cellId") collectionView?.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0) collectionView?.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0) setupMenuBar() } let menuBar: MenuBar = { let mb = MenuBar() return mb }() private func setupMenuBar() { view.addSubview(menuBar) view.addConstraintsWithFormat(format: "H:|[v0]|", views: menuBar) view.addConstraintsWithFormat(format: "V:|[v0(50)]|", views: menuBar) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = (view.frame.width - 16 - 16) * 9 / 16 // substracted lef/right margin and scaled 9/16 for the aspect ratio return CGSize(width: view.frame.width, height: height + 16 + 68) // 68 was calculated by adding all the vertical constraints of the bottom elements } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
apache-2.0
eedd2cd76c8ea9d6ac8d321db194a023
38.790323
170
0.69315
5.065708
false
false
false
false
krevis/MIDIApps
Applications/SysExLibrarian/DetailsWindowController.swift
1
9879
/* Copyright (c) 2002-2021, Kurt Revis. 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. */ import Cocoa import SnoizeMIDI class DetailsWindowController: GeneralWindowController { static func showWindow(forEntry entry: LibraryEntry) { var controller = controllers.first(where: { $0.entry == entry }) if controller == nil { let newController = DetailsWindowController(entry: entry) controllers.append(newController) controller = newController } controller?.showWindow(nil) } init(entry: LibraryEntry) { self.entry = entry self.cachedMessages = entry.messages super.init(window: nil) shouldCascadeWindows = true NotificationCenter.default.addObserver(self, selector: #selector(self.entryWillBeRemoved(_:)), name: .libraryEntryWillBeRemoved, object: entry) NotificationCenter.default.addObserver(self, selector: #selector(self.entryNameDidChange(_:)), name: .libraryEntryNameDidChange, object: entry) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var windowNibName: NSNib.Name? { return "Details" } deinit { NotificationCenter.default.removeObserver(self) } override func windowDidLoad() { super.windowDidLoad() // Setting the autosave name in the nib causes it to not restore to the exact original position. // Doing it here works more consistently. Suggested by: https://stackoverflow.com/a/30101966/1218876 splitView.autosaveName = "Details" synchronizeTitle() messagesTableView.reloadData() if cachedMessages.count > 0 { messagesTableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) } dataController.editable = false dataController.savable = false dataController.addRepresenter(dataLayoutRep) let innerReps: [HFRepresenter] = [ HFLineCountingRepresenter(), HFHexTextRepresenter(), HFStringEncodingTextRepresenter(), HFVerticalScrollerRepresenter() ] innerReps.forEach { dataController.addRepresenter($0) } innerReps.forEach { dataLayoutRep.addRepresenter($0) } let layoutView = dataLayoutRep.view() layoutView.frame = dataContainerView.bounds layoutView.autoresizingMask = [.width, .height] dataContainerView.addSubview(layoutView) if let window = window { // Tweak the window's minSize to match the data layout. let bytesPerLine = dataLayoutRep.maximumBytesPerLineForLayout(inProposedWidth: window.minSize.width) let minWidth = dataLayoutRep.minimumViewWidth(forBytesPerLine: bytesPerLine) window.minSize = NSSize(width: minWidth, height: window.minSize.height) // Then ensure the window is sized to fit the layout and that minSize var windowFrame = window.frame windowFrame.size = minimumWindowSize(windowFrame.size) window.setFrame(windowFrame, display: true) } synchronizeMessageDataDisplay() } // MARK: Private static private var controllers: [DetailsWindowController] = [] private let entry: LibraryEntry private let cachedMessages: [SystemExclusiveMessage] @IBOutlet private var splitView: NSSplitView! @IBOutlet private var messagesTableView: NSTableView! @IBOutlet private var dataContainerView: NSView! @IBOutlet private var md5ChecksumField: NSTextField! @IBOutlet private var sha1ChecksumField: NSTextField! private let dataController = HFController() private let dataLayoutRep = HFLayoutRepresenter() private func synchronizeMessageDataDisplay() { let selectedRow = messagesTableView.selectedRow let data: Data if selectedRow >= 0 { data = cachedMessages[selectedRow].receivedDataWithStartByte } else { data = Data() } let byteSlice = HFFullMemoryByteSlice(data: data) let byteArray = HFBTreeByteArray() byteArray.insertByteSlice(byteSlice, in: HFRange(location: 0, length: 0)) dataController.byteArray = byteArray md5ChecksumField.stringValue = data.count > 0 ? data.md5HexHash : "" sha1ChecksumField.stringValue = data.count > 0 ? data.sha1HexHash : "" } private func minimumWindowSize(_ proposedWindowFrameSize: NSSize) -> NSSize { // Resize to a size that will exactly fit the layout, with no extra space on the trailing side. let layoutView = dataLayoutRep.view() let proposedSizeInLayoutCoordinates = layoutView.convert(proposedWindowFrameSize, from: nil) let resultingWidthInLayoutCoordinates = dataLayoutRep.minimumViewWidthForLayout(inProposedWidth: proposedSizeInLayoutCoordinates.width) var resultingSize = layoutView.convert(NSSize(width: resultingWidthInLayoutCoordinates, height: proposedSizeInLayoutCoordinates.height), to: nil) // But ensure we don't get smaller than the window's minSize. if let window = window { resultingSize.width = Swift.max(resultingSize.width, window.minSize.width) resultingSize.height = Swift.max(resultingSize.height, window.minSize.height) } return resultingSize } private func synchronizeTitle() { window?.title = entry.name ?? "" window?.representedFilename = entry.path ?? "" } @objc private func entryWillBeRemoved(_ notification: Notification) { close() } @objc private func entryNameDidChange(_ notification: Notification) { synchronizeTitle() } } extension DetailsWindowController /* NSWindowDelegate */ { func windowWillClose(_ notification: Notification) { Self.controllers.removeAll { $0 == self } } func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { minimumWindowSize(frameSize) } } extension DetailsWindowController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { cachedMessages.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { guard row < cachedMessages.count else { return nil } let message = cachedMessages[row] switch tableColumn?.identifier.rawValue { case "index": return row + 1 case "manufacturer": return message.manufacturerName case "sizeDecimal": return MessageFormatter.formatLength(message.receivedDataWithStartByteLength, usingOption: .decimal) case "sizeHex": return MessageFormatter.formatLength(message.receivedDataWithStartByteLength, usingOption: .hexadecimal) case "sizeAbbreviated": return String.abbreviatedByteCount(message.receivedDataWithStartByteLength) default: return nil } } } extension DetailsWindowController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { synchronizeMessageDataDisplay() } func tableView(_ tableView: NSTableView, selectionIndexesForProposedSelection proposedSelectionIndexes: IndexSet) -> IndexSet { // Don't allow an empty selection if proposedSelectionIndexes.count == 0 { return tableView.selectedRowIndexes } else { return proposedSelectionIndexes } } } private let minMessagesViewHeight = CGFloat(40.0) private let minDataViewHeight = CGFloat(80.0) extension DetailsWindowController: NSSplitViewDelegate { func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat { proposedMinimumPosition + minMessagesViewHeight } func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat { proposedMaximumPosition - minDataViewHeight } func splitView(_ splitView: NSSplitView, resizeSubviewsWithOldSize oldSize: NSSize) { splitView.adjustSubviews() guard splitView.subviews.count >= 2 else { return } let view1 = splitView.subviews[0] let view2 = splitView.subviews[1] let v1Frame = view1.frame let v2Frame = view2.frame let dividerThickness = splitView.dividerThickness let boundsHeight = splitView.bounds.size.height if v1Frame.size.height < minMessagesViewHeight { view1.frame = CGRect(x: v1Frame.origin.x, y: 0, width: v1Frame.size.width, height: minMessagesViewHeight ) view2.frame = CGRect(x: v2Frame.origin.x, y: minMessagesViewHeight + dividerThickness, width: v2Frame.size.width, height: boundsHeight - (dividerThickness + minMessagesViewHeight) ) } else if v2Frame.size.height < minDataViewHeight { view1.frame = CGRect(x: v1Frame.origin.x, y: 0, width: v1Frame.size.width, height: boundsHeight - (dividerThickness + minDataViewHeight) ) view2.frame = CGRect(x: v2Frame.origin.x, y: boundsHeight - minDataViewHeight, width: v2Frame.size.width, height: minDataViewHeight ) } } }
bsd-3-clause
3024fbcf31d3933ecd6cbbf876154c10
36.706107
164
0.662516
4.971817
false
false
false
false
IMcD23/Proton
Source/AppKitBridge/UIViewController/UIViewController.swift
1
3097
// // UIViewController.swift // Pods // // Created by Ian McDowell on 4/14/16. // // import AppKit //internal var viewControllerNavigationControllerMap = [UIViewController: UINavigationController]() var token: dispatch_once_t = 0 //internal extension NSViewController { // // public override class func initialize() { // if self !== NSViewController.self { // return // } // // dispatch_once(&token) { // let originalSelector = #selector(NSViewController.loadView) // let swizzledSelector = #selector(NSViewController.swizzled_loadView) // // let originalMethod = class_getInstanceMethod(self, originalSelector) // let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) // // let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) // // if didAddMethod { // class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) // } else { // method_exchangeImplementations(originalMethod, swizzledMethod) // } // } // } // // func swizzled_loadView() { // // } // //} public protocol NSLoadView { func loadView() func viewDidLoad() func viewDidAppear() } public class NSCustomViewController: NSViewController { internal var bridgedController: NSLoadView? public override func viewDidLoad() { super.viewDidLoad() bridgedController?.viewDidLoad() } public override func viewDidAppear() { super.viewDidAppear() bridgedController?.viewDidAppear() } public override func loadView() { bridgedController?.loadView() } } public class BridgedUIViewController<T: NSCustomViewController>: BridgedUIResponder<T>, NSLoadView { public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init() self.bridgedView.bridgedController = self } public override init?(existingValue: T?) { super.init(existingValue: existingValue) } public var view: UIView! { set { self.bridgedView.view = newValue.bridgedView } get { return UIView(existingValue: self.bridgedView.view) } } public var navigationController: UINavigationController? { get { return nil//viewControllerNavigationControllerMap[self] } } public var navigationItem: UINavigationItem = UINavigationItem(title: nil) public var title: String? { set { self.bridgedView.title = newValue } get { return self.bridgedView.title } } public func loadView() { } public func viewDidLoad() { } public func viewDidAppear() { } }
mit
3ecd911f2db35f590dc03256ce64981a
24.816667
154
0.605747
5.127483
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatRoomModule/ViewController/JCChatRoomListViewController.swift
1
11286
// // JCChatRoomListViewController.swift // JChat // // Created by xudong.rao on 2019/4/16. // Copyright © 2019 HXHG. All rights reserved. // import UIKit import MJRefresh class JCChatRoomListViewController: UIViewController { fileprivate var index = 0 fileprivate var pageCount = 20 fileprivate lazy var chatRoomList: [JMSGChatRoom] = [] fileprivate lazy var listTableView: UITableView = { var contacterView = UITableView(frame: .zero, style: .plain) contacterView.delegate = self contacterView.dataSource = self contacterView.separatorStyle = .none contacterView.sectionIndexColor = UIColor(netHex: 0x2dd0cf) contacterView.sectionIndexBackgroundColor = .clear return contacterView }() // 搜索控制器 fileprivate lazy var searchController: UISearchController = { let rootVC = JCCRSearchResultViewController() let resultNav = JCNavigationController(rootViewController:rootVC) var searchVC = UISearchController(searchResultsController:resultNav) searchVC.delegate = self searchVC.searchResultsUpdater = rootVC // 设置开始搜索时导航条是否隐藏 searchVC.hidesNavigationBarDuringPresentation = true // 设置开始搜索时背景是否显示 searchVC.dimsBackgroundDuringPresentation = false let searchBar = searchVC.searchBar searchBar.sizeToFit() searchBar.delegate = self searchBar.searchBarStyle = .minimal searchBar.placeholder = "请输入 roomID" searchVC.searchBar.returnKeyType = .search searchBar.setSearchFieldBackgroundImage(UIImage.createImage(color: .white, size: CGSize(width: UIScreen.main.bounds.size.width, height: 31)), for: .normal) return searchVC } () override func viewDidLoad() { super.viewDidLoad() self.title = "聊天室" view.backgroundColor = UIColor(netHex: 0xe8edf3) if #available(iOS 10.0, *) { navigationController?.tabBarItem.badgeColor = UIColor(netHex: 0xEB424C) } listTableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height) listTableView.backgroundColor = UIColor(netHex: 0xe8edf3) view.addSubview(listTableView) let header = MJRefreshNormalHeader() header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh)) listTableView.mj_header = header let footer = MJRefreshAutoNormalFooter() footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh)) listTableView.mj_footer = footer listTableView.mj_footer.isHidden = true listTableView.mj_header.beginRefreshing(); } // 顶部刷新 @objc func headerRefresh() { index = 0 let time: TimeInterval = 0.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { self._getChatRoomList(complete: { (isSuccess) in // }); } } // 底部加载 @objc func footerRefresh() { print("上拉刷新 index = \(index)") index += pageCount let time: TimeInterval = 1.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { self._getChatRoomList(complete: { (isSuccess) in DispatchQueue.main.async { if !isSuccess { self.index -= self.pageCount } } }); } } typealias DataComplete = (Bool) -> Void // SDK 接口获取数据 func _getChatRoomList(complete: @escaping DataComplete) { JMSGChatRoom.getListWithAppKey(nil, start: index, count: pageCount) { (result, error) in if error != nil { self.index -= 1 self.listTableView.mj_footer.endRefreshing(); complete(false) return } DispatchQueue.main.async { if self.index == 0 { self.chatRoomList.removeAll() } if let rooms = result as? [JMSGChatRoom] { let count = self.chatRoomList.count var indexPaths: [IndexPath] = [] for index in 0..<rooms.count { let room = rooms[index] self.chatRoomList.append(room) let row = count + index let indexPath = IndexPath(row: row, section: 0) indexPaths.append(indexPath) } if self.index != 0 { self.listTableView.insertRows(at: indexPaths, with: .bottom) }else{ self.listTableView.reloadData() if self.chatRoomList.count > 0 { self.listTableView.tableHeaderView = self.searchController.searchBar self.listTableView.mj_footer.isHidden = false } } if rooms.count == 0 { self.listTableView.mj_footer.isHidden = true complete(false) }else{ complete(true) } }else{ complete(false) } self.listTableView.mj_footer.endRefreshing(); self.listTableView.mj_header.endRefreshing(); } } } } extension JCChatRoomListViewController : UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chatRoomList.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 66.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellid = "JCChatRoomListTableViewCell" var cell: JCChatRoomListTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? JCChatRoomListTableViewCell if cell == nil { cell = JCChatRoomListTableViewCell(style: .subtitle, reuseIdentifier: cellid) } let room = chatRoomList[indexPath.row] cell?.nameLabel.text = room.displayName() cell?.descLabel.text = room.desc return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let room = chatRoomList[indexPath.row] MBProgressHUD_JChat.show(text: "loading···", view: self.view) JMSGChatRoom.leaveChatRoom(withRoomId: room.roomID) { (result, error) in printLog("leave the chat room,error:\(String(describing: error))") let con = JMSGConversation.chatRoomConversation(withRoomId: room.roomID) if con == nil { printLog("enter the chat room first") JMSGChatRoom.enterChatRoom(withRoomId: room.roomID) { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if let con1 = result as? JMSGConversation { let vc = JCChatRoomChatViewController(conversation: con1, room: room) self.navigationController?.pushViewController(vc, animated: true) }else{ printLog("\(String(describing: error))") if let error = error as NSError? { if error.code == 851003 {//member has in the chatroom JMSGConversation.createChatRoomConversation(withRoomId: room.roomID) { (result, error) in if let con = result as? JMSGConversation { let vc = JCChatRoomChatViewController(conversation: con, room: room) self.navigationController?.pushViewController(vc, animated: true) } } } } } } }else{ printLog("go straight to the chat room session") let vc = JCChatRoomChatViewController(conversation: con!, room: room) self.navigationController?.pushViewController(vc, animated: true) } } } } // 搜索控制器代理 extension JCChatRoomListViewController: UISearchControllerDelegate { func willPresentSearchController(_ searchController: UISearchController) { listTableView.isHidden = true navigationController?.tabBarController?.tabBar.isHidden = true } func willDismissSearchController(_ searchController: UISearchController) { listTableView.isHidden = false let nav = searchController.searchResultsController as! JCNavigationController nav.isNavigationBarHidden = true nav.popToRootViewController(animated: false) navigationController?.tabBarController?.tabBar.isHidden = false } func didDismissSearchController(_ searchController: UISearchController){ let nav = searchController.searchResultsController as! JCNavigationController let searchResultVC = nav.viewControllers.first as! JCCRSearchResultViewController if searchResultVC.selectChatRoom != nil { let vc = JCChatRoomInfoTableViewController.init(nibName: "JCChatRoomInfoTableViewController", bundle: nil) vc.chatRoom = searchResultVC.selectChatRoom vc.isFromSearch = true self.navigationController?.pushViewController(vc, animated: true) } } } // searBar delegate extension JCChatRoomListViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print("\(String(describing: searchBar.text))") let nav = searchController.searchResultsController as! JCNavigationController let vc = nav.topViewController as! JCCRSearchResultViewController vc._searchChatRoom(searchBar.text ?? "") } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { print("search bar cancel") let nav = searchController.searchResultsController as! JCNavigationController let vc = nav.topViewController as! JCCRSearchResultViewController vc._clearHistoricalRecord() vc.selectChatRoom = nil } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true for view in (searchBar.subviews.first?.subviews)! { if view is UIButton { let cancelButton = view as! UIButton cancelButton.setTitleColor(UIColor(netHex: 0x2dd0cf), for: .normal) break } } } }
mit
88e851279acfd26417b3a299de679a81
40.158672
163
0.596468
5.473013
false
false
false
false
CodeKitchenBV/handbalapp
handbalapp/handbalapp/NewsViewController.swift
1
5125
// // NewsViewController.swift // handbalapp // // Created by Marko Heijnen on 1/29/17. // Copyright © 2017 CodeKitchen B.V. All rights reserved. // import Carlos import UIKit // MARK: Structs struct NewsItem { let title: String let content: String let date: Date? let url: String let thumbnail: String? let image: String? let source: String } class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: Properties let PostCellIdentifier = "NewsCell" let PullToRefreshString = "Pull to Refresh" let cache = CacheProvider.sharedImageCache let dateFormatter = DateFormatter() var newsItems: [NewsItem]! = [] var retrieving: Bool! var refreshControl: UIRefreshControl! @IBOutlet weak var tableView: UITableView! // MARK: Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) newsItems = [] retrieving = false refreshControl = UIRefreshControl() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() configureUI() retrieveNewsItems() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Functions func configureUI() { refreshControl.addTarget(self, action: #selector(self.retrieveNewsItems), for: .valueChanged) refreshControl.attributedTitle = NSAttributedString(string: PullToRefreshString) tableView.insertSubview(refreshControl, at: 0) } func retrieveNewsItems() { if ( retrieving == true ) { return } UIApplication.shared.isNetworkActivityIndicatorVisible = true retrieving = true HandbalProvider.request(.getNews) { result in switch result { case let .success(response): do { if let json = try response.mapJSON() as? NSArray { var newsItems: [NewsItem]! = [] for item in json { newsItems.append(self.extractNewsItem(item as! Dictionary)) } self.newsItems = newsItems self.tableView.reloadData() } else { } } catch { } self.retrieveNewsItemsDone() case let .failure(error): guard let error = error as? CustomStringConvertible else { break } self.retrieveNewsItemsDone() } } } func retrieveNewsItemsDone() { self.refreshControl.endRefreshing() self.retrieving = false UIApplication.shared.isNetworkActivityIndicatorVisible = false } func extractNewsItem(_ item: Dictionary<String, Any>) -> NewsItem { let title = item["title"] as! String let content = item["content"] as! String let date = dateFormatter.date(from: item["date"] as! String) let url = item["link"] as! String let source = item["source"] as! String let thumbnail = item["thumbnail"] as? String let image = item["image"] as? String return NewsItem(title: title, content: content, date: date, url: url, thumbnail: thumbnail, image: image, source: source) } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PostCellIdentifier) as UITableViewCell! cell?.tag = indexPath.row let item = newsItems[indexPath.row] cell?.textLabel?.text = item.title cell?.imageView?.image = nil cache.get(NSURL(string: item.thumbnail!)! as URL).onSuccess { value in if (cell?.tag == indexPath.row) { cell?.imageView?.image = value cell?.setNeedsLayout() } } return cell! } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "NewsView", sender: indexPath) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if ( segue.identifier == "NewsView" ) { if let viewController:NewsItemController = segue.destination as? NewsItemController { let indexPath = self.tableView.indexPathForSelectedRow viewController.item = newsItems[(indexPath?.row)!] } } } }
gpl-3.0
a99a26fbc29aaca5f6a3bb039a11f418
29.5
129
0.581772
5.354232
false
false
false
false
dpereira411/GCTabView
GCTabView-swift/NavigationViewController.swift
1
2516
// // NavigationViewController.swift // GCTabView-swift // // Created by Daniel Pereira on 15/11/14. // Copyright (c) 2014 Daniel Pereira. All rights reserved. // import Cocoa class NavigationViewController: NSViewController, TabBarViewControllerDelegate { var tab: TabBarViewController? var views: TabViewController? override func viewDidLoad() { super.viewDidLoad() let view0 = TabBarItem() view0.setStateImage(StyleKit.imageOfListRegular, state: TabBarItemState.Regular) view0.setStateImage(StyleKit.imageOfListBold, state: TabBarItemState.Bold) view0.setStateImage(StyleKit.imageOfListTinted, state: TabBarItemState.Tinted) self.tab?.addItem(view0) let view1 = TabBarItem() view1.setStateImage(StyleKit.imageOfSearchRegular, state: TabBarItemState.Regular) view1.setStateImage(StyleKit.imageOfSearchBold, state: TabBarItemState.Bold) view1.setStateImage(StyleKit.imageOfSearchTinted, state: TabBarItemState.Tinted) self.tab?.addItem(view1) let view2 = TabBarItem() view2.setStateImage(StyleKit.imageOfChronoRegular, state: TabBarItemState.Regular) view2.setStateImage(StyleKit.imageOfChronoBold, state: TabBarItemState.Bold) view2.setStateImage(StyleKit.imageOfChronoTinted, state: TabBarItemState.Tinted) self.tab?.addItem(view2) let view3 = TabBarItem() view3.setStateImage(StyleKit.imageOfFavoritesRegular, state: TabBarItemState.Regular) view3.setStateImage(StyleKit.imageOfStarBold, state: TabBarItemState.Bold) view3.setStateImage(StyleKit.imageOfStarTinted, state: TabBarItemState.Tinted) self.tab?.addItem(view3) self.tab?.updateButtons() } override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "tab": self.tab = (segue.destinationController as TabBarViewController) self.tab?.delegate = self case "views": self.views = (segue.destinationController as TabViewController) default: break } } } func didSelectIndex(index: Int) { if index < self.views?.tabViewItems.count { self.views?.selectedTabViewItemIndex = index } } }
mit
55bb54b931b1521e751c325ba6e1ab5d
31.675325
93
0.65938
4.819923
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/ScrollExample/SimpleScrollView.swift
1
6331
import UIKit class SimpleScrollView: UIView { var contentView: UIView? { didSet { oldValue?.removeFromSuperview() if let contentView = contentView { addSubview(contentView) contentView.frame = CGRect(origin: contentOrigin, size: contentSize) } } } var contentSize: CGSize = .zero { didSet { contentView?.frame.size = contentSize } } var contentOffset: CGPoint = .zero { didSet { contentView?.frame.origin = contentOrigin } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private private enum State { case `default` case dragging(initialOffset: CGPoint) } private var contentOrigin: CGPoint { return CGPoint(x: -contentOffset.x, y: -contentOffset.y) } private var contentOffsetBounds: CGRect { let width = contentSize.width - bounds.width let height = contentSize.height - bounds.height return CGRect(x: 0, y: 0, width: width, height: height) } private let panRecognizer = UIPanGestureRecognizer() private var lastPan: Date? private var state: State = .default private var contentOffsetAnimation: TimerAnimation? private func setup() { addGestureRecognizer(panRecognizer) panRecognizer.addTarget(self, action: #selector(handlePanRecognizer)) } @objc private func handlePanRecognizer(_ sender: UIPanGestureRecognizer) { let newPan = Date() switch sender.state { case .began: stopOffsetAnimation() state = .dragging(initialOffset: contentOffset) case .changed: let translation = sender.translation(in: self) if case .dragging(let initialOffset) = state { contentOffset = clampOffset(initialOffset - translation) } case .ended: state = .default // Pan gesture recognizers report a non-zero terminal velocity even // when the user had stopped dragging: // https://stackoverflow.com/questions/19092375/how-to-determine-true-end-velocity-of-pan-gesture // In virtually all cases, the pan recognizer seems to call this // handler at intervals of less than 100ms while the user is // dragging, so if this call occurs outside that window, we can // assume that the user had stopped, and finish scrolling without // deceleration. let userHadStoppedDragging = newPan.timeIntervalSince(lastPan ?? newPan) >= 0.1 let velocity: CGPoint = userHadStoppedDragging ? .zero : sender.velocity(in: self) completeGesture(withVelocity: -velocity) case .cancelled, .failed: state = .default case .possible: break @unknown default: fatalError() } lastPan = newPan } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) // Freeze the scroll view at its current position so that the user can // interact with its content or scroll it. stopOffsetAnimation() } private func stopOffsetAnimation() { contentOffsetAnimation?.invalidate() contentOffsetAnimation = nil } private func startDeceleration(withVelocity velocity: CGPoint) { let d = UIScrollView.DecelerationRate.normal.rawValue let parameters = DecelerationTimingParameters(initialValue: contentOffset, initialVelocity: velocity, decelerationRate: d, threshold: 0.5) let destination = parameters.destination let intersection = getIntersection(rect: contentOffsetBounds, segment: (contentOffset, destination)) let duration: TimeInterval if let intersection = intersection, let intersectionDuration = parameters.duration(to: intersection) { duration = intersectionDuration } else { duration = parameters.duration } contentOffsetAnimation = TimerAnimation( duration: duration, animations: { [weak self] _, time in self?.contentOffset = parameters.value(at: time) }, completion: { [weak self] finished in guard finished && intersection != nil else { return } let velocity = parameters.velocity(at: duration) self?.bounce(withVelocity: velocity) }) } private func bounce(withVelocity velocity: CGPoint) { let restOffset = contentOffset.clamped(to: contentOffsetBounds) let displacement = contentOffset - restOffset let threshold = 0.5 / UIScreen.main.scale let spring = Spring(mass: 1, stiffness: 100, dampingRatio: 1) let parameters = SpringTimingParameters(spring: spring, displacement: displacement, initialVelocity: velocity, threshold: threshold) contentOffsetAnimation = TimerAnimation( duration: parameters.duration, animations: { [weak self] _, time in self?.contentOffset = restOffset + parameters.value(at: time) }) } private func clampOffset(_ offset: CGPoint) -> CGPoint { let rubberBand = RubberBand(dims: bounds.size, bounds: contentOffsetBounds) return rubberBand.clamp(offset) } private func completeGesture(withVelocity velocity: CGPoint) { if contentOffsetBounds.containsIncludingBorders(contentOffset) { startDeceleration(withVelocity: velocity) } else { bounce(withVelocity: velocity) } } }
mit
9c6ba4fbec4ff2118f13d7d237065742
34.971591
110
0.586005
5.563269
false
false
false
false
shial4/VaporGCM
Sources/VaporGCM/DeviceGroup.swift
1
1942
// // DeviceGroup.swift // VaporGCM // // Created by Shial on 12/04/2017. // // import JSON ///Request operation type public enum DeviceGroupOperation: String { ///Create a device group case create = "create" ///Add devices from an existing group case add = "add" ///Remove devices from an existing group. ///If you remove all existing registration tokens from a device group, FCM deletes the device group. case remove = "remove" } ///With device group messaging, you can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group. public struct DeviceGroup { ///Operation parameter for the request public let operation: DeviceGroupOperation ///name or identifier public let notificationKeyName: String ///deviceToken Device token or topic to which message will be send public let registrationIds: [String] /** Create DeviceGroup instance - parameter operation: Operation parameter for the request - parameter name: Name or identifier - parameter registrationIds: Device token or topic to which message will be send */ public init(operation: DeviceGroupOperation, name: String, registrationIds: [String]) { self.operation = operation self.notificationKeyName = name self.registrationIds = registrationIds } public func makeJSON() throws -> JSON { let json = try JSON([ "operation": operation.rawValue.makeNode(in: nil), "notification_key_name": notificationKeyName.makeNode(in: nil), "registration_ids": try registrationIds.makeNode(in: nil) ].makeNode(in: nil)) return json } }
mit
c85986bcce5de8962db79d740b774654
36.346154
355
0.69207
4.668269
false
false
false
false
Lobooo/NavigationDrawer
NavigationDrawer/DrawerViewController.swift
1
1873
// // DrawerViewController.swift // NavigationDrawer-Swift // // Created by Nishan on 2/25/16. // Copyright © 2016 Nishan. All rights reserved. // import UIKit class DrawerViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let menuItem = ["Home","Favourites","Recommended","Feedback","Settings"] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItem.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") cell?.textLabel?.text = menuItem[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { NavigationDrawer.sharedInstance.toggleNavigationDrawer { () -> Void in if indexPath.row != 0 { let vc = self.storyboard?.instantiateViewController(withIdentifier: "TestViewController") as! TestViewController vc.text = self.menuItem[indexPath.row] self.navigationController?.viewControllers = [vc] } else { let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") self.navigationController?.viewControllers = [vc!] } } } }
mit
95eb51b3011fc5ca13f44adc85e35e42
27.363636
124
0.61859
5.68997
false
false
false
false
tardieu/swift
validation-test/compiler_crashers_2_fixed/0057-rdar29587093.swift
65
366
// RUN: %target-swift-frontend %s -emit-ir protocol P { associatedtype A func f() } extension P where A == Int { func f() { print("cool") } } extension P { func f() { print("semi-uncool") } func g() { f() } } struct X<T> : P { typealias A = T } extension X where A == Int { func f() { print("cool2") } } X<Int>().f() X<Int>().g()
apache-2.0
89ec51b85c303b18e6f30d329c5456c8
11.2
42
0.521858
2.671533
false
false
false
false
MatrixHero/FlowSlideMenu
FlowSlideMenu/AppDelegate.swift
1
2613
// // AppDelegate.swift // FlowSlideMenu // // Created by LL on 15/11/3. // Copyright © 2015 LL. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let storyboard = UIStoryboard(name: "Main",bundle:nil) let leftvc = storyboard.instantiateViewControllerWithIdentifier("leftvc") let mainvc = storyboard.instantiateViewControllerWithIdentifier("mainvc") let slideMenuController = LLFlowSlideMenuVC(mainViewController: mainvc, leftViewController: leftvc) self.window?.rootViewController = slideMenuController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
20702febca6ffe2713d7222400ba108f
44.824561
285
0.740429
5.72807
false
false
false
false
lucdion/aide-devoir
sources/AideDevoir/Classes/UI/Common/FastShadowCornersView.swift
1
9384
// // FastShadowCornersView.swift // LuxuryRetreats // // Created by Luc Dion on 16-02-14. // Copyright © 2016 Mirego. All rights reserved. // import UIKit /** UIView's subclass supporting fast drop shadows and round corners. Drop Shadow ================ The class use CALayer.shadowPath to optimize the performance of shadows. While a shadow can be drawn without specifying a shadowPath, for performance reasons you should always specify one. The default layer shadow use pixels shadow, i.e. it must check all view's pixels to determine its shadows. This implementation simply creates a shadowPath that follows the view's frame. See section "Links related to drop shadow performance" below for more infos. Rounded corners ================ The class can also add round corners to ALL or only to a list of selected corners (TopLeft, TopRight, BottomLeft, BottomRight). This class support simultaneously a drop shadow for rounded corners view. Surprisingly it is not that trivial to support both using a single view. The class use an extra CALayer mask to resolve this limitation. Borders ================ To change the view's border, the method setBorder(width, color) must be used! Usage of the view.layer's borderWidth and borderColor properties directly won't display a border correctly. Usage examples: ================ myView.showShadow(true) myView.showShadow(true, radius: 5, opacity: 0.7, offset: CGSize(width: 3, height: 3), color: .grayColor()) myView.showShadow(true, color: .blueColor()) myView.showRoundCorners(true, radius: 5) myView.showRoundCorners(true, roundingCorners: [.TopLeft, .TopRight]) myView.showRoundCorners(false) myView.setBorder(width: 5, color: .redColor()) Links related to drop shadow performance: - Apple Improving Animation Performance (https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/ImprovingAnimationPerformance/ImprovingAnimationPerformance.html) Specify a Shadow Path When Adding a Shadow to Your Layer ========================================================= "Letting Core Animation determine the shape of a shadow can be expensive and impact your app’s performance. Rather than letting Core Animation determine the shape of the shadow, specify the shadow shape explicitly using the shadowPath property of CALayer. When you specify a path object for this property, Core Animation uses that shape to draw and cache the shadow effect. For layers whose shape never changes or rarely changes, this greatly improves performance by reducing the amount of rendering done by Core Animation." - iPad drop shadow performance (https://www.omnigroup.com/blog/ipad_drop_shadow_performance_test) OPERATION TYPE -> Resize/Once Slide/Once Resize/User Slide/User SHADOW TYPE CALayer Shadow Slow Slow Slow Slow CALayer Shadow, rasterized Slow Fast Slow Fast CALayer, shadow path Fast Fast Fast Fast "Don't turn on CALayer shadows unless either enable rasterization on and aren't going to be changing the view's size, or are willing to do the extra bookkeeping to maintain a shadowPath. Generic CALayer shadows are stunningly slow if all you need is a rectangle, but the shadowPath hint makes them very zippy." */ class FastShadowCornersView: UIView { fileprivate var isShadowVisible = false fileprivate var shadowRadius = 0.f fileprivate var cornersRadius = 0.f fileprivate var roundingCorners = UIRectCorner.allCorners fileprivate var roundCornersLayer: CALayer? fileprivate var borderWidth = 0.f fileprivate var borderColor = UIColor.clear fileprivate var borderLayer: CAShapeLayer? fileprivate var localBackgroundColor: UIColor? override var backgroundColor: UIColor? { set { localBackgroundColor = newValue if let roundCornersLayer = roundCornersLayer { // The roundCornersLayer is active => set it's background color instead of the view's background. roundCornersLayer.backgroundColor = localBackgroundColor?.cgColor } else { super.backgroundColor = localBackgroundColor } } get { return localBackgroundColor } } // Disable the the shadowPath optimization. In case where you need to animate the bounds of the view, you may need to disable this feature. var disableShadowPath = false { didSet { if disableShadowPath { layer.shadowPath = nil } else { setNeedsLayout() } } } init () { super.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Add a drop shadow to the view. */ func showShadow(_ show: Bool = true, radius: CGFloat = 3, opacity: CGFloat = 0.6, offset: CGSize = CGSize(width: 1, height: 1), color: UIColor = .black) { isShadowVisible = show shadowRadius = radius layer.shadowColor = color.cgColor layer.shadowOffset = offset layer.shadowOpacity = Float(opacity) layer.shadowPath = nil setNeedsLayout() } /** Set rounds corner to the view. Round corner can be applied to ALL or only to selected corners (TopLeft, TopRight, BottomLeft, BottomRight). Note that round corners will also be applied to the drop shadow. */ func showRoundCorners(_ show: Bool = true, radius: CGFloat = 3, roundingCorners: UIRectCorner = .allCorners) { self.cornersRadius = radius self.roundingCorners = roundingCorners if show { if roundCornersLayer == nil { roundCornersLayer = CALayer() roundCornersLayer!.masksToBounds = true layer.insertSublayer(roundCornersLayer!, at: 0) // The view must now be transparent, the roundCornersLayer will now show the background color. super.backgroundColor = .clear roundCornersLayer?.backgroundColor = localBackgroundColor?.cgColor } } else if let roundCornersLayer = roundCornersLayer { roundCornersLayer.removeFromSuperlayer() backgroundColor = localBackgroundColor self.roundCornersLayer = nil self.roundingCorners = .allCorners } setNeedsLayout() } /** Set the view's border. WARNING: Using the view.layer's borderWidth and borderColor directly won't display a border correctly. This method must be used instead. - parameter width: border's width - parameter color: border's color. */ func setBorder(_ width: CGFloat, color: UIColor) { borderWidth = width borderColor = color if let roundCornersLayer = roundCornersLayer { // In the case where we use a roundCornersLayer and a border exists, we must add another layer (borderLayer) to display the border. if borderWidth > 0 { if borderLayer == nil { borderLayer = CAShapeLayer() roundCornersLayer.addSublayer(borderLayer!) } } else { borderLayer?.removeFromSuperlayer() borderLayer = nil } } else { // No roundCornersLayer => Use default view's layer. layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } setNeedsLayout() } } // PMARK: UIView's override extension FastShadowCornersView { override func layoutSubviews() { super.layoutSubviews() // 1) Handle Shadow path if isShadowVisible && !disableShadowPath { // Update the shadow path to match new view's bounds. layer.shadowPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii: CGSize(width: shadowRadius, height: shadowRadius)).cgPath } // 2) Handle round corners layer if let roundCornersLayer = roundCornersLayer { // Update the roundCornersLayer mask to match new view's bounds. let shapeLayer = CAShapeLayer() shapeLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii: CGSize(width: cornersRadius, height: cornersRadius)).cgPath roundCornersLayer.mask = shapeLayer roundCornersLayer.frame = bounds // 3) Handle border. In the case where a roundCornersLayer is used and a border exist, we must update the borderLayer if let borderLayer = borderLayer, borderWidth > 0 { borderLayer.lineWidth = borderWidth borderLayer.strokeColor = borderColor.cgColor borderLayer.fillColor = UIColor.clear.cgColor borderLayer.frame = bounds borderLayer.path = shapeLayer.path } } } }
apache-2.0
23d65ff421353b8f9dc860600081c08d
40.325991
537
0.646306
5.342255
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressUITests/Screens/PostsScreen.swift
1
2827
import UITestsFoundation import XCTest private struct ElementStringIDs { static let draftsButton = "drafts" static let publishedButton = "published" static let autosaveVersionsAlert = "autosave-options-alert" } class PostsScreen: BaseScreen { enum PostStatus { case published case drafts } private var currentlyFilteredPostStatus: PostStatus = .published init() { super.init(element: XCUIApplication().tables["PostsTable"]) showOnly(.published) } @discardableResult func showOnly(_ status: PostStatus) -> PostsScreen { switch status { case .published: XCUIApplication().buttons[ElementStringIDs.publishedButton].tap() case .drafts: XCUIApplication().buttons[ElementStringIDs.draftsButton].tap() } currentlyFilteredPostStatus = status return self } func selectPost(withSlug slug: String) -> EditorScreen { // Tap the current tab item to scroll the table to the top showOnly(currentlyFilteredPostStatus) let cell = expectedElement.cells[slug] XCTAssert(cell.waitForExistence(timeout: 5)) scrollElementIntoView(element: cell, within: expectedElement) cell.tap() dismissAutosaveDialogIfNeeded() let editorScreen = EditorScreen() editorScreen.dismissDialogsIfNeeded() return EditorScreen() } /// If there are two versions of a local post, the app will ask which version we want to use when editing. /// We always want to use the local version (which is currently the first option) private func dismissAutosaveDialogIfNeeded() { let autosaveDialog = XCUIApplication().alerts[ElementStringIDs.autosaveVersionsAlert] if autosaveDialog.exists { autosaveDialog.buttons.firstMatch.tap() } } } struct EditorScreen { var isGutenbergEditor: Bool { let blockEditorElement = "add-block-button" return XCUIApplication().buttons[blockEditorElement].waitForExistence(timeout: 3) } var isAztecEditor: Bool { let aztecEditorElement = "Azctec Editor Navigation Bar" return XCUIApplication().navigationBars[aztecEditorElement].exists } private var blockEditor: BlockEditorScreen { return BlockEditorScreen() } private var aztecEditor: AztecEditorScreen { return AztecEditorScreen(mode: .rich) } func dismissDialogsIfNeeded() { if self.isGutenbergEditor { blockEditor.dismissNotificationAlertIfNeeded(.accept) } } func close() { if isGutenbergEditor { self.blockEditor.closeEditor() } if isAztecEditor { self.aztecEditor.closeEditor() } } }
gpl-2.0
72df64a4fbdc8aea181c550b33d6b61d
26.182692
110
0.661832
4.849057
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift
6
2702
// // ShareReplay1.swift // Rx // // Created by Krunoslav Zaher on 10/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // optimized version of share replay for most common case final class ShareReplay1<Element> : Observable<Element> , ObserverType , SynchronizedUnsubscribeType { typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType private let _source: Observable<Element> private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? private var _stopped = false private var _stopEvent = nil as Event<Element>? private var _observers = Bag<AnyObserver<Element>>() init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = self._element { observer.on(.next(element)) } if let stopEvent = self._stopEvent { observer.on(stopEvent) return Disposables.create() } let initialCount = self._observers.count let disposeKey = self._observers.insert(AnyObserver(observer)) if initialCount == 0 { let connection = SingleAssignmentDisposable() _connection = connection connection.disposable = self._source.subscribe(self) } return SubscriptionDisposable(owner: self, key: disposeKey) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return } if _observers.count == 0 { _connection?.dispose() _connection = nil } } func on(_ event: Event<E>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(_ event: Event<E>) { if _stopped { return } switch event { case .next(let element): _element = element case .error, .completed: _stopEvent = event _stopped = true _connection?.dispose() _connection = nil } _observers.on(event) } }
mit
e01c9c4cb781a41d1b343c3ef9252ce2
25.742574
96
0.597927
4.656897
false
false
false
false
Stickbuilt/SBGestureTableView
SBGestureTableView/SBGestureTableViewCell.swift
1
8909
// // SBGestureTableViewCell.swift // SBGestureTableView-Swift // // Created by Ben Nichols on 10/3/14. // Copyright (c) 2014 Stickbuilt. All rights reserved. // import UIKit class SBGestureTableViewCell: UITableViewCell { var actionIconsFollowSliding = true var actionIconsMargin: CGFloat = 20.0 var actionNormalColor = UIColor(white: 0.85, alpha: 1) var leftSideView = SBGestureTableViewCellSideView() var rightSideView = SBGestureTableViewCellSideView() var firstLeftAction: SBGestureTableViewCellAction? { didSet { if (firstLeftAction?.fraction == 0) { firstLeftAction?.fraction = 0.3 } } } var secondLeftAction: SBGestureTableViewCellAction? { didSet { if (secondLeftAction?.fraction == 0) { secondLeftAction?.fraction = 0.7 } } } var firstRightAction: SBGestureTableViewCellAction? { didSet { if (firstRightAction?.fraction == 0) { firstRightAction?.fraction = 0.3 } } } var secondRightAction: SBGestureTableViewCellAction? { didSet { if (secondRightAction?.fraction == 0) { secondRightAction?.fraction = 0.7 } } } var currentAction: SBGestureTableViewCellAction? override var center: CGPoint { get { return super.center } set { super.center = newValue updateSideViews() } } override var frame: CGRect { get { return super.frame } set { super.frame = newValue updateSideViews() } } private var gestureTableView: SBGestureTableView! private let panGestureRecognizer = UIPanGestureRecognizer() func setup() { panGestureRecognizer.addTarget(self, action: "slideCell:") panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } override func didMoveToSuperview() { gestureTableView = superview?.superview as? SBGestureTableView } func percentageOffsetFromCenter() -> (Double) { let diff = fabs(frame.size.width/2 - center.x); return Double(diff / frame.size.width); } func percentageOffsetFromEnd() -> (Double) { let diff = fabs(frame.size.width/2 - center.x); return Double((frame.size.width - diff) / frame.size.width); } override func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) { let panGestureRecognizer = gestureRecognizer as! UIPanGestureRecognizer let velocity = panGestureRecognizer.velocityInView(self) let horizontalLocation = panGestureRecognizer.locationInView(self).x if fabs(velocity.x) > fabs(velocity.y) && horizontalLocation > CGFloat(gestureTableView.edgeSlidingMargin) && horizontalLocation < frame.size.width - CGFloat(gestureTableView.edgeSlidingMargin) && gestureTableView.isEnabled { return true; } } else if gestureRecognizer.isKindOfClass(UILongPressGestureRecognizer) { if gestureTableView.didMoveCellFromIndexPathToIndexPathBlock == nil { return true; } } return false; } func actionForCurrentPosition() -> SBGestureTableViewCellAction? { let fraction = fabs(frame.origin.x/frame.size.width) if frame.origin.x > 0 { if secondLeftAction != nil && fraction > secondLeftAction!.fraction { return secondLeftAction! } else if firstLeftAction != nil && fraction > firstLeftAction!.fraction { return firstLeftAction! } } else if frame.origin.x < 0 { if secondRightAction != nil && fraction > secondRightAction!.fraction { return secondRightAction! } else if firstRightAction != nil && fraction > firstRightAction!.fraction { return firstRightAction! } } return nil } func performChanges() { let action = actionForCurrentPosition() if let action = action { if frame.origin.x > 0 { leftSideView.backgroundColor = action.color leftSideView.iconImageView.image = action.icon } else if frame.origin.x < 0 { rightSideView.backgroundColor = action.color rightSideView.iconImageView.image = action.icon } } else { if frame.origin.x > 0 { leftSideView.backgroundColor = actionNormalColor leftSideView.iconImageView.image = firstLeftAction!.icon } else if frame.origin.x < 0 { rightSideView.backgroundColor = actionNormalColor rightSideView.iconImageView.image = firstRightAction!.icon } } if let image = leftSideView.iconImageView.image { leftSideView.iconImageView.alpha = frame.origin.x / (actionIconsMargin*2 + image.size.width) } if let image = rightSideView.iconImageView.image { rightSideView.iconImageView.alpha = -(frame.origin.x / (actionIconsMargin*2 + image.size.width)) } if currentAction != action { action?.didHighlightBlock?(gestureTableView, self) currentAction?.didUnhighlightBlock?(gestureTableView, self) currentAction = action } } func hasAnyLeftAction() -> Bool { return firstLeftAction != nil || secondLeftAction != nil } func hasAnyRightAction() -> Bool { return firstRightAction != nil || secondRightAction != nil } func setupSideViews() { leftSideView.iconImageView.contentMode = actionIconsFollowSliding ? UIViewContentMode.Right : UIViewContentMode.Left rightSideView.iconImageView.contentMode = actionIconsFollowSliding ? UIViewContentMode.Left : UIViewContentMode.Right superview?.insertSubview(leftSideView, atIndex: 0) superview?.insertSubview(rightSideView, atIndex: 0) } func slideCell(panGestureRecognizer: UIPanGestureRecognizer) { if !hasAnyLeftAction() || !hasAnyRightAction() { return } var horizontalTranslation = panGestureRecognizer.translationInView(self).x if panGestureRecognizer.state == UIGestureRecognizerState.Began { setupSideViews() } else if panGestureRecognizer.state == UIGestureRecognizerState.Changed { if (!hasAnyLeftAction() && frame.size.width/2 + horizontalTranslation > frame.size.width/2) || (!hasAnyRightAction() && frame.size.width/2 + horizontalTranslation < frame.size.width/2) { horizontalTranslation = 0 } performChanges() center = CGPointMake(frame.size.width/2 + horizontalTranslation, center.y) } else if panGestureRecognizer.state == UIGestureRecognizerState.Ended { if (currentAction == nil && frame.origin.x != 0) || !gestureTableView.isEnabled { gestureTableView.cellReplacingBlock?(gestureTableView, self) } else { currentAction?.didTriggerBlock(gestureTableView, self) } currentAction = nil } } func updateSideViews() { leftSideView.frame = CGRectMake(0, frame.origin.y, frame.origin.x, frame.size.height) if let image = leftSideView.iconImageView.image { leftSideView.iconImageView.frame = CGRectMake(actionIconsMargin, 0, max(image.size.width, leftSideView.frame.size.width - actionIconsMargin*2), leftSideView.frame.size.height) } rightSideView.frame = CGRectMake(frame.origin.x + frame.size.width, frame.origin.y, frame.size.width - (frame.origin.x + frame.size.width), frame.size.height) if let image = rightSideView.iconImageView.image { rightSideView.iconImageView.frame = CGRectMake(rightSideView.frame.size.width - actionIconsMargin, 0, min(-image.size.width, actionIconsMargin*2 - rightSideView.frame.size.width), rightSideView.frame.size.height) } } }
mit
ec9755feabbf23b3c002ba104ab57fba
38.776786
224
0.630486
5.06481
false
false
false
false
uasys/swift
test/ClangImporter/enum-objc.swift
6
1445
// RUN: %target-swift-frontend -emit-sil %s -import-objc-header %S/Inputs/enum-objc.h -verify // REQUIRES: objc_interop func test(_ value: SwiftEnum) { switch value { case .one: break case .two: break case .three: break } // no error } let _: Int = forwardBarePointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} let _: Int = forwardWithUnderlyingPointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} let _: Int = forwardObjCPointer // expected-error {{cannot convert value of type '(OpaquePointer) -> Void' to specified type 'Int'}} // FIXME: It would be nice to import these as unavailable somehow instead. let _: Int = forwardWithUnderlyingValue // expected-error {{use of unresolved identifier 'forwardWithUnderlyingValue'}} let _: Int = forwardObjCValue // expected-error {{use of unresolved identifier 'forwardObjCValue'}} // Note that if /these/ start getting imported as unavailable, the error will // also mention that there's a missing argument, since the second argument isn't // actually defaultable. _ = SomeClass.tryInferDefaultArgumentUnderlyingValue(false) // expected-error {{type 'SomeClass' has no member 'tryInferDefaultArgumentUnderlyingValue'}} _ = SomeClass.tryInferDefaultArgumentObjCValue(false) // expected-error {{type 'SomeClass' has no member 'tryInferDefaultArgumentObjCValue'}}
apache-2.0
9d74ef096d91d3efd7d3790ddc94b1c6
56.8
153
0.745329
4.237537
false
false
false
false
xxhp/BrowserTabViewDemo_swift
BrowerTabView/BrowserTab.swift
1
3789
// // BrowserTab.swift // BrowserTabView_Swift // // Created by xiaohaibo on 3/14/15. // Copyright (c) 2015 xiaohaibo. All rights reserved. // // github:https://github.com/xxhp/BrowserTabViewDemo_swift // Email:[email protected] // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. import UIKit class BrowserTab: UIView { weak var browserTabView : BrowserTabView? var titleFont :UIFont? var titleField :UITextField? var imageView :UIImageView? var index :Int? fileprivate var closeButton:UIButton = UIButton(type:UIButtonType.custom) as UIButton // Default initializer override init(frame: CGRect) { super.init(frame: frame) } convenience init(browserTabView abrowserTabView:BrowserTabView) { self.init(frame: CGRect.zero) browserTabView = abrowserTabView titleFont = UIFont.systemFont(ofSize: 16) imageView = UIImageView(frame: self.bounds) addSubview(imageView!) closeButton.setImage(UIImage(named:"tab_close"), for:UIControlState()) closeButton.addTarget(self, action: #selector(BrowserTab.onCloseTap(_:)), for: UIControlEvents.touchUpInside) closeButton.isHidden = true addSubview(closeButton) titleField = UITextField(frame: self.bounds) as UITextField titleField?.textAlignment = NSTextAlignment.center titleField?.isEnabled = false addSubview(titleField!) self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BrowserTab.handleTap(_:)))) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var selected: Bool = false{ didSet { if (selected) { imageView?.image = UIImage(named:"tab_selected")?.stretchableImage(withLeftCapWidth: 30, topCapHeight:0) closeButton.isHidden = !((self.browserTabView?.tabArray.count)! > 1) }else{ imageView?.image = UIImage(named:"tab_normal")?.stretchableImage(withLeftCapWidth: 30, topCapHeight:0) closeButton.isHidden = true } } } override func layoutSubviews() { titleField?.frame = self.bounds imageView?.frame = self.bounds closeButton.frame = CGRect(x: self.bounds.maxX - 50, y: 0, width: 44, height: 44) } func handleTap(_ gestureRecognizer: UITapGestureRecognizer) { browserTabView?.selectTab(atIndex:self.index!, animated: false) } func onCloseTap(_ sender:UIButton){ browserTabView?.removeTab(atIndex: self.index!) } }
mit
a84a952407307065fdc2ef89fa1c5f2d
36.514851
120
0.667722
4.67201
false
false
false
false
macmade/AtomicKit
AtomicKit/Source/DispatchedValue.swift
1
4799
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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 /** * Thread-safe value wrapper, using dispatch queues to achieve synchronization. * Note that this class is not KVO-compliant. * If you need this, please use subclasses of `DispatchedValue`. * * - seealso: DispatchedValueWrapper */ public class DispatchedValue< T >: DispatchedValueWrapper { /** * The wrapped value type. */ public typealias ValueType = T /** * Initializes a dispatched value object. * This initializer will use the main queue for synchronization. * * - parameter value: The initial value. */ public required convenience init( value: T ) { self.init( value: value, queue: DispatchQueue.main ) } /** * Initializes a dispatched value object. * * - parameter value: The initial value. * - parameter queue: The queue to use to achieve synchronization. */ public required init( value: T, queue: DispatchQueue ) { self._queue = queue self._value = value self._queue.setSpecific( key: self._key, value: self._uuid ) } /** * Atomically gets the wrapped value. * The getter will be executed on the queue specified in the initialzer. * * - returns: The actual value. */ public func get() -> T { if( DispatchQueue.getSpecific( key: self._key ) == self._uuid ) { return self._value } else { return self._queue.sync( execute: { return self._value } ); } } /** * Atomically sets the wrapped value. * The setter will be executed on the queue specified in the initialzer. * * -parameter value: The value to set. */ public func set( _ value: T ) { if( DispatchQueue.getSpecific( key: self._key ) == self._uuid ) { self._value = value } else { self._queue.sync{ self._value = value } } } /** * Atomically executes a closure on the wrapped value. * The closure will be passed the actual value of the wrapped value, * and is guaranteed to be executed atomically, on the queue specified in * the initialzer. * * -parameter closure: The close to execute. */ public func execute( closure: ( T ) -> Swift.Void ) { if( DispatchQueue.getSpecific( key: self._key ) == self._uuid ) { closure( self._value ) } else { self._queue.sync{ closure( self._value ) } } } /** * Atomically executes a closure on the wrapped value, returning some value. * The closure will be passed the actual value of the wrapped value, * and is guaranteed to be executed atomically, on the queue specified in * the initialzer. * * -parameter closure: The close to execute, returning some value. */ public func execute< R >( closure: ( T ) -> R ) -> R { if( DispatchQueue.getSpecific( key: self._key ) == self._uuid ) { return closure( self._value ) } else { return self._queue.sync( execute: { return closure( self._value ) } ) } } private let _key = DispatchSpecificKey< String >() private let _uuid = UUID().uuidString private var _queue: DispatchQueue private var _value: T }
mit
acb26d1b37b11601b0cd7d21ed24c268
31.425676
82
0.593665
4.700294
false
false
false
false
krzysztofzablocki/Sourcery
SourcerySwift/Sources/SourceryRuntime.content.generated.swift
1
300872
let sourceryRuntimeFiles: [FolderSynchronizer.File] = [ .init(name: "AccessLevel.swift", content: """ // // Created by Krzysztof Zablocki on 13/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: public enum AccessLevel: String { case `internal` = "internal" case `private` = "private" case `fileprivate` = "fileprivate" case `public` = "public" case `open` = "open" case none = "" } """), .init(name: "Annotations.swift", content: """ import Foundation public typealias Annotations = [String: NSObject] /// Describes annotated declaration, i.e. type, method, variable, enum case public protocol Annotated { /** All annotations of declaration stored by their name. Value can be `bool`, `String`, float `NSNumber` or array of those types if you use several annotations with the same name. **Example:** ``` //sourcery: booleanAnnotation //sourcery: stringAnnotation = "value" //sourcery: numericAnnotation = 0.5 [ "booleanAnnotation": true, "stringAnnotation": "value", "numericAnnotation": 0.5 ] ``` */ var annotations: Annotations { get } } """), .init(name: "Array+Parallel.swift", content: """ // // Created by Krzysztof Zablocki on 06/01/2017. // Copyright (c) 2017 Pixle. All rights reserved. // import Foundation public extension Array { func parallelFlatMap<T>(transform: (Element) -> [T]) -> [T] { return parallelMap(transform: transform).flatMap { $0 } } func parallelCompactMap<T>(transform: (Element) -> T?) -> [T] { return parallelMap(transform: transform).compactMap { $0 } } func parallelMap<T>(transform: (Element) -> T) -> [T] { var result = ContiguousArray<T?>(repeating: nil, count: count) return result.withUnsafeMutableBufferPointer { buffer in DispatchQueue.concurrentPerform(iterations: buffer.count) { idx in buffer[idx] = transform(self[idx]) } return buffer.map { $0! } } } func parallelPerform(transform: (Element) -> Void) { DispatchQueue.concurrentPerform(iterations: count) { idx in transform(self[idx]) } } } """), .init(name: "Array.swift", content: """ import Foundation /// Describes array type @objcMembers public final class ArrayType: NSObject, SourceryModel { /// Type name used in declaration public var name: String /// Array element type name public var elementTypeName: TypeName // sourcery: skipEquality, skipDescription /// Array element type, if known public var elementType: Type? /// :nodoc: public init(name: String, elementTypeName: TypeName, elementType: Type? = nil) { self.name = name self.elementTypeName = elementTypeName self.elementType = elementType } /// Returns array as generic type public var asGeneric: GenericType { GenericType(name: "Array", typeParameters: [ .init(typeName: elementTypeName) ]) } public var asSource: String { "[\\(elementTypeName.asSource)]" } // sourcery:inline:ArrayType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let elementTypeName: TypeName = aDecoder.decode(forKey: "elementTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["elementTypeName"])); fatalError() }; self.elementTypeName = elementTypeName self.elementType = aDecoder.decode(forKey: "elementType") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.elementTypeName, forKey: "elementTypeName") aCoder.encode(self.elementType, forKey: "elementType") } // sourcery:end } """), .init(name: "AssociatedType.swift", content: """ import Foundation /// Describes Swift AssociatedType @objcMembers public final class AssociatedType: NSObject, SourceryModel { /// Associated type name public let name: String /// Associated type type constraint name, if specified public let typeName: TypeName? // sourcery: skipEquality, skipDescription /// Associated type constrained type, if known, i.e. if the type is declared in the scanned sources. public var type: Type? /// :nodoc: public init(name: String, typeName: TypeName? = nil, type: Type? = nil) { self.name = name self.typeName = typeName self.type = type } // sourcery:inline:AssociatedType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name self.typeName = aDecoder.decode(forKey: "typeName") self.type = aDecoder.decode(forKey: "type") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") } // sourcery:end } """), .init(name: "Attribute.swift", content: """ import Foundation /// Describes Swift attribute @objcMembers public class Attribute: NSObject, AutoCoding, AutoEquatable, AutoDiffable, AutoJSExport { /// Attribute name public let name: String /// Attribute arguments public let arguments: [String: NSObject] // sourcery: skipJSExport let _description: String // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(name: String, arguments: [String: NSObject] = [:], description: String? = nil) { self.name = name self.arguments = arguments self._description = description ?? "@\\(name)" } /// TODO: unify `asSource` / `description`? public var asSource: String { description } /// Attribute description that can be used in a template. public override var description: String { return _description } /// :nodoc: public enum Identifier: String { case convenience case required case available case discardableResult case GKInspectable = "gkinspectable" case objc case objcMembers case nonobjc case NSApplicationMain case NSCopying case NSManaged case UIApplicationMain case IBOutlet = "iboutlet" case IBInspectable = "ibinspectable" case IBDesignable = "ibdesignable" case autoclosure case convention case mutating case escaping case final case open case lazy case `public` = "public" case `internal` = "internal" case `private` = "private" case `fileprivate` = "fileprivate" case publicSetter = "setter_access.public" case internalSetter = "setter_access.internal" case privateSetter = "setter_access.private" case fileprivateSetter = "setter_access.fileprivate" case optional public init?(identifier: String) { let identifier = identifier.trimmingPrefix("source.decl.attribute.") if identifier == "objc.name" { self.init(rawValue: "objc") } else { self.init(rawValue: identifier) } } public static func from(string: String) -> Identifier? { switch string { case "GKInspectable": return Identifier.GKInspectable case "objc": return .objc case "IBOutlet": return .IBOutlet case "IBInspectable": return .IBInspectable case "IBDesignable": return .IBDesignable default: return Identifier(rawValue: string) } } public var name: String { switch self { case .GKInspectable: return "GKInspectable" case .objc: return "objc" case .IBOutlet: return "IBOutlet" case .IBInspectable: return "IBInspectable" case .IBDesignable: return "IBDesignable" case .fileprivateSetter: return "fileprivate" case .privateSetter: return "private" case .internalSetter: return "internal" case .publicSetter: return "public" default: return rawValue } } public var description: String { return hasAtPrefix ? "@\\(name)" : name } public var hasAtPrefix: Bool { switch self { case .available, .discardableResult, .GKInspectable, .objc, .objcMembers, .nonobjc, .NSApplicationMain, .NSCopying, .NSManaged, .UIApplicationMain, .IBOutlet, .IBInspectable, .IBDesignable, .autoclosure, .convention, .escaping: return true default: return false } } } // sourcery:inline:Attribute.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let arguments: [String: NSObject] = aDecoder.decode(forKey: "arguments") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["arguments"])); fatalError() }; self.arguments = arguments guard let _description: String = aDecoder.decode(forKey: "_description") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["_description"])); fatalError() }; self._description = _description } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.arguments, forKey: "arguments") aCoder.encode(self._description, forKey: "_description") } // sourcery:end } """), .init(name: "AutoHashable.generated.swift", content: """ // Generated using Sourcery 1.3.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable all // MARK: - AutoHashable for classes, protocols, structs // MARK: - AutoHashable for Enums """), .init(name: "BytesRange.swift", content: """ // // Created by Sébastien Duperron on 03/01/2018. // Copyright © 2018 Pixle. All rights reserved. // import Foundation /// :nodoc: @objcMembers public final class BytesRange: NSObject, SourceryModel { public let offset: Int64 public let length: Int64 public init(offset: Int64, length: Int64) { self.offset = offset self.length = length } public convenience init(range: (offset: Int64, length: Int64)) { self.init(offset: range.offset, length: range.length) } // sourcery:inline:BytesRange.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.offset = aDecoder.decodeInt64(forKey: "offset") self.length = aDecoder.decodeInt64(forKey: "length") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.offset, forKey: "offset") aCoder.encode(self.length, forKey: "length") } // sourcery:end } """), .init(name: "Class.swift", content: """ import Foundation // sourcery: skipDescription /// Descibes Swift class @objc(SwiftClass) @objcMembers public final class Class: Type { /// Returns "class" public override var kind: String { return "class" } /// Whether type is final public var isFinal: Bool { return modifiers.contains { $0.name == "final" } } /// :nodoc: public override init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], isGeneric: Bool = false) { super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, subscripts: subscripts, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, attributes: attributes, modifiers: modifiers, annotations: annotations, documentation: documentation, isGeneric: isGeneric ) } // sourcery:inline:Class.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) } // sourcery:end } """), .init(name: "Closure.swift", content: """ import Foundation /// Describes closure type @objcMembers public final class ClosureType: NSObject, SourceryModel { /// Type name used in declaration with stripped whitespaces and new lines public let name: String /// List of closure parameters public let parameters: [ClosureParameter] /// Return value type name public let returnTypeName: TypeName /// Actual return value type name if declaration uses typealias, otherwise just a `returnTypeName` public var actualReturnTypeName: TypeName { return returnTypeName.actualTypeName ?? returnTypeName } // sourcery: skipEquality, skipDescription /// Actual return value type, if known public var returnType: Type? // sourcery: skipEquality, skipDescription /// Whether return value type is optional public var isOptionalReturnType: Bool { return returnTypeName.isOptional } // sourcery: skipEquality, skipDescription /// Whether return value type is implicitly unwrapped optional public var isImplicitlyUnwrappedOptionalReturnType: Bool { return returnTypeName.isImplicitlyUnwrappedOptional } // sourcery: skipEquality, skipDescription /// Return value type name without attributes and optional type information public var unwrappedReturnTypeName: String { return returnTypeName.unwrappedTypeName } /// Whether method is async method public let isAsync: Bool /// async keyword public let asyncKeyword: String? /// Whether closure throws public let `throws`: Bool /// throws or rethrows keyword public let throwsOrRethrowsKeyword: String? /// :nodoc: public init(name: String, parameters: [ClosureParameter], returnTypeName: TypeName, returnType: Type? = nil, asyncKeyword: String? = nil, throwsOrRethrowsKeyword: String? = nil) { self.name = name self.parameters = parameters self.returnTypeName = returnTypeName self.returnType = returnType self.asyncKeyword = asyncKeyword self.isAsync = asyncKeyword != nil self.throwsOrRethrowsKeyword = throwsOrRethrowsKeyword self.`throws` = throwsOrRethrowsKeyword != nil } public var asSource: String { "\\(parameters.asSource)\\(asyncKeyword != nil ? " \\(asyncKeyword!)" : "")\\(throwsOrRethrowsKeyword != nil ? " \\(throwsOrRethrowsKeyword!)" : "") -> \\(returnTypeName.asSource)" } // sourcery:inline:ClosureType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let parameters: [ClosureParameter] = aDecoder.decode(forKey: "parameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["parameters"])); fatalError() }; self.parameters = parameters guard let returnTypeName: TypeName = aDecoder.decode(forKey: "returnTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["returnTypeName"])); fatalError() }; self.returnTypeName = returnTypeName self.returnType = aDecoder.decode(forKey: "returnType") self.isAsync = aDecoder.decode(forKey: "isAsync") self.asyncKeyword = aDecoder.decode(forKey: "asyncKeyword") self.`throws` = aDecoder.decode(forKey: "`throws`") self.throwsOrRethrowsKeyword = aDecoder.decode(forKey: "throwsOrRethrowsKeyword") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.parameters, forKey: "parameters") aCoder.encode(self.returnTypeName, forKey: "returnTypeName") aCoder.encode(self.returnType, forKey: "returnType") aCoder.encode(self.isAsync, forKey: "isAsync") aCoder.encode(self.asyncKeyword, forKey: "asyncKeyword") aCoder.encode(self.`throws`, forKey: "`throws`") aCoder.encode(self.throwsOrRethrowsKeyword, forKey: "throwsOrRethrowsKeyword") } // sourcery:end } """), .init(name: "Coding.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace trailing_newline import Foundation extension NSCoder { @nonobjc func decode(forKey: String) -> String? { return self.maybeDecode(forKey: forKey) as String? } @nonobjc func decode(forKey: String) -> TypeName? { return self.maybeDecode(forKey: forKey) as TypeName? } @nonobjc func decode(forKey: String) -> AccessLevel? { return self.maybeDecode(forKey: forKey) as AccessLevel? } @nonobjc func decode(forKey: String) -> Bool { return self.decodeBool(forKey: forKey) } @nonobjc func decode(forKey: String) -> Int { return self.decodeInteger(forKey: forKey) } func decode<E>(forKey: String) -> E? { return maybeDecode(forKey: forKey) as E? } fileprivate func maybeDecode<E>(forKey: String) -> E? { guard let object = self.decodeObject(forKey: forKey) else { return nil } return object as? E } } extension ArrayType: NSCoding {} extension AssociatedType: NSCoding {} extension AssociatedValue: NSCoding {} extension Attribute: NSCoding {} extension BytesRange: NSCoding {} extension ClosureParameter: NSCoding {} extension ClosureType: NSCoding {} extension DictionaryType: NSCoding {} extension EnumCase: NSCoding {} extension FileParserResult: NSCoding {} extension GenericRequirement: NSCoding {} extension GenericType: NSCoding {} extension GenericTypeParameter: NSCoding {} extension Import: NSCoding {} extension Method: NSCoding {} extension MethodParameter: NSCoding {} extension Modifier: NSCoding {} extension Subscript: NSCoding {} extension TupleElement: NSCoding {} extension TupleType: NSCoding {} extension Type: NSCoding {} extension TypeName: NSCoding {} extension Typealias: NSCoding {} extension Types: NSCoding {} extension Variable: NSCoding {} """), .init(name: "Composer.swift", content: """ // // Created by Krzysztof Zablocki on 31/12/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation private func currentTimestamp() -> TimeInterval { return CFAbsoluteTimeGetCurrent() } /// Responsible for composing results of `FileParser`. public enum Composer { internal final class State { private(set) var typeMap = [String: Type]() private(set) var modules = [String: [String: Type]]() let parsedTypes: [Type] let functions: [SourceryMethod] let resolvedTypealiases: [String: Typealias] let unresolvedTypealiases: [String: Typealias] init(parserResult: FileParserResult) { // TODO: This logic should really be more complicated // For any resolution we need to be looking at accessLevel and module boundaries // e.g. there might be a typealias `private typealias Something = MyType` in one module and same name in another with public modifier, one could be accessed and the other could not self.functions = parserResult.functions let aliases = Self.typealiases(parserResult) resolvedTypealiases = aliases.resolved unresolvedTypealiases = aliases.unresolved parsedTypes = parserResult.types // set definedInType for all methods and variables parsedTypes .forEach { type in type.variables.forEach { $0.definedInType = type } type.methods.forEach { $0.definedInType = type } type.subscripts.forEach { $0.definedInType = type } } // map all known types to their names parsedTypes .filter { $0.isExtension == false } .forEach { typeMap[$0.globalName] = $0 if let module = $0.module { var typesByModules = modules[module, default: [:]] typesByModules[$0.name] = $0 modules[module] = typesByModules } } } func unifyTypes() -> [Type] { /// Resolve actual names of extensions, as they could have been done on typealias and note updated child names in uniques if needed parsedTypes .filter { $0.isExtension == true } .forEach { let oldName = $0.globalName if let resolved = resolveGlobalName(for: oldName, containingType: $0.parent, unique: typeMap, modules: modules, typealiases: resolvedTypealiases)?.name { $0.localName = resolved.replacingOccurrences(of: "\\($0.module != nil ? "\\($0.module!)." : "")", with: "") } else { return } // nothing left to do guard oldName != $0.globalName else { return } // if it had contained types, they might have been fully defined and so their name has to be noted in uniques func rewriteChildren(of type: Type) { // child is never an extension so no need to check for child in type.containedTypes { typeMap[child.globalName] = child rewriteChildren(of: child) } } rewriteChildren(of: $0) } // extend all types with their extensions parsedTypes.forEach { type in type.inheritedTypes = type.inheritedTypes.map { inheritedName in resolveGlobalName(for: inheritedName, containingType: type.parent, unique: typeMap, modules: modules, typealiases: resolvedTypealiases)?.name ?? inheritedName } let uniqueType = typeMap[type.globalName] ?? // this check will only fail on an extension? typeFromComposedName(type.name, modules: modules) ?? // this can happen for an extension on unknown type, this case should probably be handled by the inferTypeNameFromModules (inferTypeNameFromModules(from: type.localName, containedInType: type.parent, uniqueTypes: typeMap, modules: modules).flatMap { typeMap[$0] }) guard let current = uniqueType else { assert(type.isExtension) // for unknown types we still store their extensions but mark them as unknown type.isUnknownExtension = true if let existingType = typeMap[type.globalName] { existingType.extend(type) typeMap[type.globalName] = existingType } else { typeMap[type.globalName] = type } let inheritanceClause = type.inheritedTypes.isEmpty ? "" : ": \\(type.inheritedTypes.joined(separator: ", "))" Log.astWarning("Found \\"extension \\(type.name)\\(inheritanceClause)\\" of type for which there is no original type declaration information.") return } if current == type { return } current.extend(type) typeMap[current.globalName] = current } let values = typeMap.values var processed = Set<String>(minimumCapacity: values.count) return typeMap.values.filter({ let name = $0.globalName let wasProcessed = processed.contains(name) processed.insert(name) return !wasProcessed }) } /// returns typealiases map to their full names, with `resolved` removing intermediate /// typealises and `unresolved` including typealiases that reference other typealiases. private static func typealiases(_ parserResult: FileParserResult) -> (resolved: [String: Typealias], unresolved: [String: Typealias]) { var typealiasesByNames = [String: Typealias]() parserResult.typealiases.forEach { typealiasesByNames[$0.name] = $0 } parserResult.types.forEach { type in type.typealiases.forEach({ (_, alias) in // TODO: should I deal with the fact that alias.name depends on type name but typenames might be updated later on // maybe just handle non extension case here and extension aliases after resolving them? typealiasesByNames[alias.name] = alias }) } let unresolved = typealiasesByNames // ! if a typealias leads to another typealias, follow through and replace with final type typealiasesByNames.forEach { _, alias in var aliasNamesToReplace = [alias.name] var finalAlias = alias while let targetAlias = typealiasesByNames[finalAlias.typeName.name] { aliasNamesToReplace.append(targetAlias.name) finalAlias = targetAlias } // ! replace all keys aliasNamesToReplace.forEach { typealiasesByNames[$0] = finalAlias } } return (resolved: typealiasesByNames, unresolved: unresolved) } /// Resolves type identifier for name func resolveGlobalName(for type: String, containingType: Type? = nil, unique: [String: Type]? = nil, modules: [String: [String: Type]], typealiases: [String: Typealias]) -> (name: String, typealias: Typealias?)? { // if the type exists for this name and isn't an extension just return it's name // if it's extension we need to check if there aren't other options TODO: verify if let realType = unique?[type], realType.isExtension == false { return (name: realType.globalName, typealias: nil) } if let alias = typealiases[type] { return (name: alias.type?.globalName ?? alias.typeName.name, typealias: alias) } if let containingType = containingType { if type == "Self" { return (name: containingType.globalName, typealias: nil) } var currentContainer: Type? = containingType while currentContainer != nil, let parentName = currentContainer?.globalName { /// TODO: no parent for sure? /// manually walk the containment tree if let name = resolveGlobalName(for: "\\(parentName).\\(type)", containingType: nil, unique: unique, modules: modules, typealiases: typealiases) { return name } currentContainer = currentContainer?.parent } // if let name = resolveGlobalName(for: "\\(containingType.globalName).\\(type)", containingType: containingType.parent, unique: unique, modules: modules, typealiases: typealiases) { // return name // } // last check it's via module // if let module = containingType.module, let name = resolveGlobalName(for: "\\(module).\\(type)", containingType: nil, unique: unique, modules: modules, typealiases: typealiases) { // return name // } } // TODO: is this needed? if let inferred = inferTypeNameFromModules(from: type, containedInType: containingType, uniqueTypes: unique ?? [:], modules: modules) { return (name: inferred, typealias: nil) } return typeFromComposedName(type, modules: modules).map { (name: $0.globalName, typealias: nil) } } private func inferTypeNameFromModules(from typeIdentifier: String, containedInType: Type?, uniqueTypes: [String: Type], modules: [String: [String: Type]]) -> String? { func fullName(for module: String) -> String { "\\(module).\\(typeIdentifier)" } func type(for module: String) -> Type? { return modules[module]?[typeIdentifier] } func ambiguousErrorMessage(from types: [Type]) -> String? { Log.astWarning("Ambiguous type \\(typeIdentifier), found \\(types.map { $0.globalName }.joined(separator: ", ")). Specify module name at declaration site to disambiguate.") return nil } let explicitModulesAtDeclarationSite: [String] = [ containedInType?.module.map { [$0] } ?? [], // main module for this typename containedInType?.imports.map { $0.moduleName } ?? [] // imported modules ] .flatMap { $0 } let remainingModules = Set(modules.keys).subtracting(explicitModulesAtDeclarationSite) /// We need to check whether we can find type in one of the modules but we need to be careful to avoid amibiguity /// First checking explicit modules available at declaration site (so source module + all imported ones) /// If there is no ambigiuity there we can assume that module will be resolved by the compiler /// If that's not the case we look after remaining modules in the application and if the typename has no ambigiuity we use that /// But if there is more than 1 typename duplication across modules we have no way to resolve what is the compiler going to use so we fail let moduleSetsToCheck: [[String]] = [ explicitModulesAtDeclarationSite, Array(remainingModules) ] for modules in moduleSetsToCheck { let possibleTypes = modules .compactMap { type(for: $0) } if possibleTypes.count > 1 { return ambiguousErrorMessage(from: possibleTypes) } if let type = possibleTypes.first { return type.globalName } } // as last result for unknown types / extensions // try extracting type from unique array if let module = containedInType?.module { return uniqueTypes[fullName(for: module)]?.globalName } return nil } func typeFromComposedName(_ name: String, modules: [String: [String: Type]]) -> Type? { guard name.contains(".") else { return nil } let nameComponents = name.components(separatedBy: ".") let moduleName = nameComponents[0] let typeName = nameComponents.suffix(from: 1).joined(separator: ".") return modules[moduleName]?[typeName] } } /// Performs final processing of discovered types: /// - extends types with their corresponding extensions; /// - replaces typealiases with actual types /// - finds actual types for variables and enums raw values /// - filters out any private types and extensions /// /// - Parameter parserResult: Result of parsing source code. /// - Returns: Final types and extensions of unknown types. public static func uniqueTypesAndFunctions(_ parserResult: FileParserResult) -> (types: [Type], functions: [SourceryMethod], typealiases: [Typealias]) { let state = State(parserResult: parserResult) let resolveType = { (typeName: TypeName, containingType: Type?) -> Type? in return self.resolveType(typeName: typeName, containingType: containingType, state: state) } /// Resolve typealiases let typealiases = Array(state.unresolvedTypealiases.values) typealiases.forEach { alias in alias.type = resolveType(alias.typeName, alias.parent) } let types = state.unifyTypes() let resolutionStart = currentTimestamp() types.parallelPerform { type in type.variables.forEach { resolveVariableTypes($0, of: type, resolve: resolveType) } type.methods.forEach { resolveMethodTypes($0, of: type, resolve: resolveType) } type.subscripts.forEach { resolveSubscriptTypes($0, of: type, resolve: resolveType) } if let enumeration = type as? Enum { resolveEnumTypes(enumeration, types: state.typeMap, resolve: resolveType) } if let composition = type as? ProtocolComposition { resolveProtocolCompositionTypes(composition, resolve: resolveType) } if let sourceryProtocol = type as? SourceryProtocol { resolveProtocolTypes(sourceryProtocol, resolve: resolveType) } } state.functions.parallelPerform { function in resolveMethodTypes(function, of: nil, resolve: resolveType) } Log.benchmark("resolution took \\(currentTimestamp() - resolutionStart)") updateTypeRelationships(types: types) return ( types: types.sorted { $0.globalName < $1.globalName }, functions: state.functions.sorted { $0.name < $1.name }, typealiases: typealiases.sorted(by: { $0.name < $1.name }) ) } private static func resolveType(typeName: TypeName, containingType: Type?, state: State) -> Type? { let resolveTypeWithName = { (typeName: TypeName) -> Type? in return self.resolveType(typeName: typeName, containingType: containingType, state: state) } let unique = state.typeMap let modules = state.modules let typealiases = state.resolvedTypealiases if let name = typeName.actualTypeName { let resolvedIdentifier = name.generic?.name ?? name.unwrappedTypeName return unique[resolvedIdentifier] } let retrievedName = self.actualTypeName(for: typeName, containingType: containingType, state: state) let lookupName = retrievedName ?? typeName if let tuple = lookupName.tuple { var needsUpdate = false tuple.elements.forEach { tupleElement in tupleElement.type = resolveTypeWithName(tupleElement.typeName) if tupleElement.typeName.actualTypeName != nil { needsUpdate = true } } if needsUpdate || retrievedName != nil { let tupleCopy = TupleType(name: tuple.name, elements: tuple.elements) tupleCopy.elements.forEach { $0.typeName = $0.actualTypeName ?? $0.typeName $0.typeName.actualTypeName = nil } tupleCopy.name = tupleCopy.elements.asTypeName typeName.tuple = tupleCopy // TODO: really don't like this old behaviour typeName.actualTypeName = TypeName(name: tupleCopy.name, isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: tupleCopy, array: lookupName.array, dictionary: lookupName.dictionary, closure: lookupName.closure, generic: lookupName.generic ) } return nil } else if let array = lookupName.array { array.elementType = resolveTypeWithName(array.elementTypeName) if array.elementTypeName.actualTypeName != nil || retrievedName != nil { let array = ArrayType(name: array.name, elementTypeName: array.elementTypeName, elementType: array.elementType) array.elementTypeName = array.elementTypeName.actualTypeName ?? array.elementTypeName array.elementTypeName.actualTypeName = nil array.name = array.asSource typeName.array = array // TODO: really don't like this old behaviour typeName.generic = array.asGeneric // TODO: really don't like this old behaviour typeName.actualTypeName = TypeName(name: array.name, isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: lookupName.tuple, array: array, dictionary: lookupName.dictionary, closure: lookupName.closure, generic: typeName.generic ) } } else if let dictionary = lookupName.dictionary { dictionary.keyType = resolveTypeWithName(dictionary.keyTypeName) dictionary.valueType = resolveTypeWithName(dictionary.valueTypeName) if dictionary.keyTypeName.actualTypeName != nil || dictionary.valueTypeName.actualTypeName != nil || retrievedName != nil { let dictionary = DictionaryType(name: dictionary.name, valueTypeName: dictionary.valueTypeName, valueType: dictionary.valueType, keyTypeName: dictionary.keyTypeName, keyType: dictionary.keyType) dictionary.keyTypeName = dictionary.keyTypeName.actualTypeName ?? dictionary.keyTypeName dictionary.keyTypeName.actualTypeName = nil // TODO: really don't like this old behaviour dictionary.valueTypeName = dictionary.valueTypeName.actualTypeName ?? dictionary.valueTypeName dictionary.valueTypeName.actualTypeName = nil // TODO: really don't like this old behaviour dictionary.name = dictionary.asSource typeName.dictionary = dictionary // TODO: really don't like this old behaviour typeName.generic = dictionary.asGeneric // TODO: really don't like this old behaviour typeName.actualTypeName = TypeName(name: dictionary.asSource, isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: lookupName.tuple, array: lookupName.array, dictionary: dictionary, closure: lookupName.closure, generic: dictionary.asGeneric ) } } else if let closure = lookupName.closure { var needsUpdate = false closure.returnType = resolveTypeWithName(closure.returnTypeName) closure.parameters.forEach { parameter in parameter.type = resolveTypeWithName(parameter.typeName) if parameter.typeName.actualTypeName != nil { needsUpdate = true } } if closure.returnTypeName.actualTypeName != nil || needsUpdate || retrievedName != nil { typeName.closure = closure // TODO: really don't like this old behaviour typeName.actualTypeName = TypeName(name: closure.asSource, isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: lookupName.tuple, array: lookupName.array, dictionary: lookupName.dictionary, closure: closure, generic: lookupName.generic ) } return nil } else if let generic = lookupName.generic { var needsUpdate = false generic.typeParameters.forEach { parameter in parameter.type = resolveTypeWithName(parameter.typeName) if parameter.typeName.actualTypeName != nil { needsUpdate = true } } if needsUpdate || retrievedName != nil { let generic = GenericType(name: generic.name, typeParameters: generic.typeParameters) generic.typeParameters.forEach { $0.typeName = $0.typeName.actualTypeName ?? $0.typeName $0.typeName.actualTypeName = nil // TODO: really don't like this old behaviour } typeName.generic = generic // TODO: really don't like this old behaviour typeName.array = lookupName.array // TODO: really don't like this old behaviour typeName.dictionary = lookupName.dictionary // TODO: really don't like this old behaviour let params = generic.typeParameters.map { $0.typeName.asSource }.joined(separator: ", ") typeName.actualTypeName = TypeName(name: "\\(generic.name)<\\(params)>", isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: lookupName.tuple, array: lookupName.array, // TODO: asArray dictionary: lookupName.dictionary, // TODO: asDictionary closure: lookupName.closure, generic: generic ) } } if let aliasedName = (typeName.actualTypeName ?? retrievedName), aliasedName.unwrappedTypeName != typeName.unwrappedTypeName { typeName.actualTypeName = aliasedName } let finalLookup = typeName.actualTypeName ?? typeName let resolvedIdentifier = finalLookup.generic?.name ?? finalLookup.unwrappedTypeName // should we cache resolved typenames? return unique[resolvedIdentifier] } typealias TypeResolver = (TypeName, Type?) -> Type? private static func resolveVariableTypes(_ variable: Variable, of type: Type, resolve: TypeResolver) { variable.type = resolve(variable.typeName, type) /// The actual `definedInType` is assigned in `uniqueTypes` but we still /// need to resolve the type to correctly parse typealiases /// @see https://github.com/krzysztofzablocki/Sourcery/pull/374 if let definedInTypeName = variable.definedInTypeName { _ = resolve(definedInTypeName, type) } } private static func resolveSubscriptTypes(_ subscript: Subscript, of type: Type, resolve: TypeResolver) { `subscript`.parameters.forEach { (parameter) in parameter.type = resolve(parameter.typeName, type) } `subscript`.returnType = resolve(`subscript`.returnTypeName, type) if let definedInTypeName = `subscript`.definedInTypeName { _ = resolve(definedInTypeName, type) } } private static func resolveMethodTypes(_ method: SourceryMethod, of type: Type?, resolve: TypeResolver) { method.parameters.forEach { parameter in parameter.type = resolve(parameter.typeName, type) } /// The actual `definedInType` is assigned in `uniqueTypes` but we still /// need to resolve the type to correctly parse typealiases /// @see https://github.com/krzysztofzablocki/Sourcery/pull/374 var definedInType: Type? if let definedInTypeName = method.definedInTypeName { definedInType = resolve(definedInTypeName, type) } guard !method.returnTypeName.isVoid else { return } if method.isInitializer || method.isFailableInitializer { method.returnType = definedInType if let type = method.actualDefinedInTypeName { if method.isFailableInitializer { method.returnTypeName = TypeName( name: type.name, isOptional: true, isImplicitlyUnwrappedOptional: false, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic, isProtocolComposition: type.isProtocolComposition ) } else if method.isInitializer { method.returnTypeName = type } } } else { method.returnType = resolve(method.returnTypeName, type) } } private static func resolveEnumTypes(_ enumeration: Enum, types: [String: Type], resolve: TypeResolver) { enumeration.cases.forEach { enumCase in enumCase.associatedValues.forEach { associatedValue in associatedValue.type = resolve(associatedValue.typeName, enumeration) } } guard enumeration.hasRawType else { return } if let rawValueVariable = enumeration.variables.first(where: { $0.name == "rawValue" && !$0.isStatic }) { enumeration.rawTypeName = rawValueVariable.actualTypeName enumeration.rawType = rawValueVariable.type } else if let rawTypeName = enumeration.inheritedTypes.first { // enums with no cases or enums with cases that contain associated values can't have raw type guard !enumeration.cases.isEmpty, !enumeration.hasAssociatedValues else { return enumeration.rawTypeName = nil } if let rawTypeCandidate = types[rawTypeName] { if !((rawTypeCandidate is SourceryProtocol) || (rawTypeCandidate is ProtocolComposition)) { enumeration.rawTypeName = TypeName(rawTypeName) enumeration.rawType = rawTypeCandidate } } else { enumeration.rawTypeName = TypeName(rawTypeName) } } } private static func resolveProtocolCompositionTypes(_ protocolComposition: ProtocolComposition, resolve: TypeResolver) { let composedTypes = protocolComposition.composedTypeNames.compactMap { typeName in resolve(typeName, protocolComposition) } protocolComposition.composedTypes = composedTypes } private static func resolveProtocolTypes(_ sourceryProtocol: SourceryProtocol, resolve: TypeResolver) { sourceryProtocol.associatedTypes.forEach { (_, value) in guard let typeName = value.typeName, let type = resolve(typeName, sourceryProtocol) else { return } value.type = type } sourceryProtocol.genericRequirements.forEach { requirment in if let knownAssociatedType = sourceryProtocol.associatedTypes[requirment.leftType.name] { requirment.leftType = knownAssociatedType } requirment.rightType.type = resolve(requirment.rightType.typeName, sourceryProtocol) } } private static func actualTypeName(for typeName: TypeName, containingType: Type? = nil, state: State) -> TypeName? { let unique = state.typeMap let modules = state.modules let typealiases = state.resolvedTypealiases var unwrapped = typeName.unwrappedTypeName if let generic = typeName.generic { unwrapped = generic.name } guard let aliased = state.resolveGlobalName(for: unwrapped, containingType: containingType, unique: unique, modules: modules, typealiases: typealiases) else { return nil } /// TODO: verify let generic = typeName.generic.map { GenericType(name: $0.name, typeParameters: $0.typeParameters) } generic?.name = aliased.name let dictionary = typeName.dictionary.map { DictionaryType(name: $0.name, valueTypeName: $0.valueTypeName, valueType: $0.valueType, keyTypeName: $0.keyTypeName, keyType: $0.keyType) } dictionary?.name = aliased.name let array = typeName.array.map { ArrayType(name: $0.name, elementTypeName: $0.elementTypeName, elementType: $0.elementType) } array?.name = aliased.name return TypeName(name: aliased.name, isOptional: typeName.isOptional, isImplicitlyUnwrappedOptional: typeName.isImplicitlyUnwrappedOptional, tuple: aliased.typealias?.typeName.tuple ?? typeName.tuple, // TODO: verify array: aliased.typealias?.typeName.array ?? array, dictionary: aliased.typealias?.typeName.dictionary ?? dictionary, closure: aliased.typealias?.typeName.closure ?? typeName.closure, generic: aliased.typealias?.typeName.generic ?? generic ) } private static func updateTypeRelationships(types: [Type]) { var typesByName = [String: Type]() types.forEach { typesByName[$0.globalName] = $0 } var processed = [String: Bool]() types.forEach { type in if let type = type as? Class, let supertype = type.inheritedTypes.first.flatMap({ typesByName[$0] }) as? Class { type.supertype = supertype } processed[type.globalName] = true updateTypeRelationship(for: type, typesByName: typesByName, processed: &processed) } } private static func findBaseType(for type: Type, name: String, typesByName: [String: Type]) -> Type? { if let baseType = typesByName[name] { return baseType } if let module = type.module, let baseType = typesByName["\\(module).\\(name)"] { return baseType } for importModule in type.imports { if let baseType = typesByName["\\(importModule).\\(name)"] { return baseType } } return nil } private static func updateTypeRelationship(for type: Type, typesByName: [String: Type], processed: inout [String: Bool]) { type.based.keys.forEach { name in guard let baseType = findBaseType(for: type, name: name, typesByName: typesByName) else { return } let globalName = baseType.globalName if processed[globalName] != true { processed[globalName] = true updateTypeRelationship(for: baseType, typesByName: typesByName, processed: &processed) } baseType.based.keys.forEach { type.based[$0] = $0 } baseType.basedTypes.forEach { type.basedTypes[$0.key] = $0.value } baseType.inherits.forEach { type.inherits[$0.key] = $0.value } baseType.implements.forEach { type.implements[$0.key] = $0.value } if baseType is Class { type.inherits[globalName] = baseType } else if let baseProtocol = baseType as? SourceryProtocol { type.implements[globalName] = baseProtocol if let extendingProtocol = type as? SourceryProtocol { baseProtocol.associatedTypes.forEach { if extendingProtocol.associatedTypes[$0.key] == nil { extendingProtocol.associatedTypes[$0.key] = $0.value } } } } else if baseType is ProtocolComposition { // TODO: associated types? type.implements[globalName] = baseType } type.basedTypes[globalName] = baseType } } } """), .init(name: "Definition.swift", content: """ import Foundation /// Describes that the object is defined in a context of some `Type` public protocol Definition: AnyObject { /// Reference to type name where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc var definedInTypeName: TypeName? { get } /// Reference to actual type where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown var definedInType: Type? { get } // sourcery: skipJSExport /// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName` var actualDefinedInTypeName: TypeName? { get } } """), .init(name: "Description.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace extension ArrayType { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "elementTypeName = \\(String(describing: self.elementTypeName)), " string += "asGeneric = \\(String(describing: self.asGeneric)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension AssociatedType { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "typeName = \\(String(describing: self.typeName))" return string } } extension AssociatedValue { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "localName = \\(String(describing: self.localName)), " string += "externalName = \\(String(describing: self.externalName)), " string += "typeName = \\(String(describing: self.typeName)), " string += "defaultValue = \\(String(describing: self.defaultValue)), " string += "annotations = \\(String(describing: self.annotations))" return string } } extension BytesRange { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "offset = \\(String(describing: self.offset)), " string += "length = \\(String(describing: self.length))" return string } } extension Class { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \\(String(describing: self.kind)), " string += "isFinal = \\(String(describing: self.isFinal))" return string } } extension ClosureParameter { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "argumentLabel = \\(String(describing: self.argumentLabel)), " string += "name = \\(String(describing: self.name)), " string += "typeName = \\(String(describing: self.typeName)), " string += "`inout` = \\(String(describing: self.`inout`)), " string += "typeAttributes = \\(String(describing: self.typeAttributes)), " string += "defaultValue = \\(String(describing: self.defaultValue)), " string += "annotations = \\(String(describing: self.annotations)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension ClosureType { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "parameters = \\(String(describing: self.parameters)), " string += "returnTypeName = \\(String(describing: self.returnTypeName)), " string += "actualReturnTypeName = \\(String(describing: self.actualReturnTypeName)), " string += "isAsync = \\(String(describing: self.isAsync)), " string += "asyncKeyword = \\(String(describing: self.asyncKeyword)), " string += "`throws` = \\(String(describing: self.`throws`)), " string += "throwsOrRethrowsKeyword = \\(String(describing: self.throwsOrRethrowsKeyword)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension DictionaryType { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "valueTypeName = \\(String(describing: self.valueTypeName)), " string += "keyTypeName = \\(String(describing: self.keyTypeName)), " string += "asGeneric = \\(String(describing: self.asGeneric)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension Enum { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "cases = \\(String(describing: self.cases)), " string += "rawTypeName = \\(String(describing: self.rawTypeName)), " string += "hasAssociatedValues = \\(String(describing: self.hasAssociatedValues))" return string } } extension EnumCase { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "rawValue = \\(String(describing: self.rawValue)), " string += "associatedValues = \\(String(describing: self.associatedValues)), " string += "annotations = \\(String(describing: self.annotations)), " string += "documentation = \\(String(describing: self.documentation)), " string += "indirect = \\(String(describing: self.indirect)), " string += "hasAssociatedValue = \\(String(describing: self.hasAssociatedValue))" return string } } extension FileParserResult { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "path = \\(String(describing: self.path)), " string += "module = \\(String(describing: self.module)), " string += "types = \\(String(describing: self.types)), " string += "functions = \\(String(describing: self.functions)), " string += "typealiases = \\(String(describing: self.typealiases)), " string += "inlineRanges = \\(String(describing: self.inlineRanges)), " string += "inlineIndentations = \\(String(describing: self.inlineIndentations)), " string += "modifiedDate = \\(String(describing: self.modifiedDate)), " string += "sourceryVersion = \\(String(describing: self.sourceryVersion)), " string += "isEmpty = \\(String(describing: self.isEmpty))" return string } } extension GenericRequirement { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "leftType = \\(String(describing: self.leftType)), " string += "rightType = \\(String(describing: self.rightType)), " string += "relationship = \\(String(describing: self.relationship)), " string += "relationshipSyntax = \\(String(describing: self.relationshipSyntax))" return string } } extension GenericTypeParameter { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "typeName = \\(String(describing: self.typeName))" return string } } extension Method { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "selectorName = \\(String(describing: self.selectorName)), " string += "parameters = \\(String(describing: self.parameters)), " string += "returnTypeName = \\(String(describing: self.returnTypeName)), " string += "isAsync = \\(String(describing: self.isAsync)), " string += "`throws` = \\(String(describing: self.`throws`)), " string += "`rethrows` = \\(String(describing: self.`rethrows`)), " string += "accessLevel = \\(String(describing: self.accessLevel)), " string += "isStatic = \\(String(describing: self.isStatic)), " string += "isClass = \\(String(describing: self.isClass)), " string += "isFailableInitializer = \\(String(describing: self.isFailableInitializer)), " string += "annotations = \\(String(describing: self.annotations)), " string += "documentation = \\(String(describing: self.documentation)), " string += "definedInTypeName = \\(String(describing: self.definedInTypeName)), " string += "attributes = \\(String(describing: self.attributes)), " string += "modifiers = \\(String(describing: self.modifiers))" return string } } extension MethodParameter { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "argumentLabel = \\(String(describing: self.argumentLabel)), " string += "name = \\(String(describing: self.name)), " string += "typeName = \\(String(describing: self.typeName)), " string += "`inout` = \\(String(describing: self.`inout`)), " string += "isVariadic = \\(String(describing: self.isVariadic)), " string += "typeAttributes = \\(String(describing: self.typeAttributes)), " string += "defaultValue = \\(String(describing: self.defaultValue)), " string += "annotations = \\(String(describing: self.annotations)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension Protocol { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \\(String(describing: self.kind)), " string += "associatedTypes = \\(String(describing: self.associatedTypes)), " string += "genericRequirements = \\(String(describing: self.genericRequirements))" return string } } extension ProtocolComposition { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \\(String(describing: self.kind)), " string += "composedTypeNames = \\(String(describing: self.composedTypeNames))" return string } } extension Struct { /// :nodoc: override public var description: String { var string = super.description string += ", " string += "kind = \\(String(describing: self.kind))" return string } } extension Subscript { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "parameters = \\(String(describing: self.parameters)), " string += "returnTypeName = \\(String(describing: self.returnTypeName)), " string += "actualReturnTypeName = \\(String(describing: self.actualReturnTypeName)), " string += "isFinal = \\(String(describing: self.isFinal)), " string += "readAccess = \\(String(describing: self.readAccess)), " string += "writeAccess = \\(String(describing: self.writeAccess)), " string += "isMutable = \\(String(describing: self.isMutable)), " string += "annotations = \\(String(describing: self.annotations)), " string += "documentation = \\(String(describing: self.documentation)), " string += "definedInTypeName = \\(String(describing: self.definedInTypeName)), " string += "actualDefinedInTypeName = \\(String(describing: self.actualDefinedInTypeName)), " string += "attributes = \\(String(describing: self.attributes)), " string += "modifiers = \\(String(describing: self.modifiers))" return string } } extension TemplateContext { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "parserResult = \\(String(describing: self.parserResult)), " string += "functions = \\(String(describing: self.functions)), " string += "types = \\(String(describing: self.types)), " string += "argument = \\(String(describing: self.argument)), " string += "stencilContext = \\(String(describing: self.stencilContext))" return string } } extension TupleElement { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "typeName = \\(String(describing: self.typeName)), " string += "asSource = \\(String(describing: self.asSource))" return string } } extension TupleType { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "elements = \\(String(describing: self.elements))" return string } } extension Type { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "module = \\(String(describing: self.module)), " string += "imports = \\(String(describing: self.imports)), " string += "allImports = \\(String(describing: self.allImports)), " string += "typealiases = \\(String(describing: self.typealiases)), " string += "isExtension = \\(String(describing: self.isExtension)), " string += "kind = \\(String(describing: self.kind)), " string += "accessLevel = \\(String(describing: self.accessLevel)), " string += "name = \\(String(describing: self.name)), " string += "isUnknownExtension = \\(String(describing: self.isUnknownExtension)), " string += "isGeneric = \\(String(describing: self.isGeneric)), " string += "localName = \\(String(describing: self.localName)), " string += "rawVariables = \\(String(describing: self.rawVariables)), " string += "rawMethods = \\(String(describing: self.rawMethods)), " string += "rawSubscripts = \\(String(describing: self.rawSubscripts)), " string += "initializers = \\(String(describing: self.initializers)), " string += "annotations = \\(String(describing: self.annotations)), " string += "documentation = \\(String(describing: self.documentation)), " string += "staticVariables = \\(String(describing: self.staticVariables)), " string += "staticMethods = \\(String(describing: self.staticMethods)), " string += "classMethods = \\(String(describing: self.classMethods)), " string += "instanceVariables = \\(String(describing: self.instanceVariables)), " string += "instanceMethods = \\(String(describing: self.instanceMethods)), " string += "computedVariables = \\(String(describing: self.computedVariables)), " string += "storedVariables = \\(String(describing: self.storedVariables)), " string += "inheritedTypes = \\(String(describing: self.inheritedTypes)), " string += "inherits = \\(String(describing: self.inherits)), " string += "containedTypes = \\(String(describing: self.containedTypes)), " string += "parentName = \\(String(describing: self.parentName)), " string += "parentTypes = \\(String(describing: self.parentTypes)), " string += "attributes = \\(String(describing: self.attributes)), " string += "modifiers = \\(String(describing: self.modifiers)), " string += "fileName = \\(String(describing: self.fileName))" return string } } extension Typealias { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "aliasName = \\(String(describing: self.aliasName)), " string += "typeName = \\(String(describing: self.typeName)), " string += "module = \\(String(describing: self.module)), " string += "accessLevel = \\(String(describing: self.accessLevel)), " string += "parentName = \\(String(describing: self.parentName)), " string += "name = \\(String(describing: self.name))" return string } } extension Types { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "types = \\(String(describing: self.types)), " string += "typealiases = \\(String(describing: self.typealiases))" return string } } extension Variable { /// :nodoc: override public var description: String { var string = "\\(Swift.type(of: self)): " string += "name = \\(String(describing: self.name)), " string += "typeName = \\(String(describing: self.typeName)), " string += "isComputed = \\(String(describing: self.isComputed)), " string += "isAsync = \\(String(describing: self.isAsync)), " string += "`throws` = \\(String(describing: self.`throws`)), " string += "isStatic = \\(String(describing: self.isStatic)), " string += "readAccess = \\(String(describing: self.readAccess)), " string += "writeAccess = \\(String(describing: self.writeAccess)), " string += "accessLevel = \\(String(describing: self.accessLevel)), " string += "isMutable = \\(String(describing: self.isMutable)), " string += "defaultValue = \\(String(describing: self.defaultValue)), " string += "annotations = \\(String(describing: self.annotations)), " string += "documentation = \\(String(describing: self.documentation)), " string += "attributes = \\(String(describing: self.attributes)), " string += "modifiers = \\(String(describing: self.modifiers)), " string += "isFinal = \\(String(describing: self.isFinal)), " string += "isLazy = \\(String(describing: self.isLazy)), " string += "definedInTypeName = \\(String(describing: self.definedInTypeName)), " string += "actualDefinedInTypeName = \\(String(describing: self.actualDefinedInTypeName))" return string } } """), .init(name: "Dictionary.swift", content: """ import Foundation /// Describes dictionary type @objcMembers public final class DictionaryType: NSObject, SourceryModel { /// Type name used in declaration public var name: String /// Dictionary value type name public var valueTypeName: TypeName // sourcery: skipEquality, skipDescription /// Dictionary value type, if known public var valueType: Type? /// Dictionary key type name public var keyTypeName: TypeName // sourcery: skipEquality, skipDescription /// Dictionary key type, if known public var keyType: Type? /// :nodoc: public init(name: String, valueTypeName: TypeName, valueType: Type? = nil, keyTypeName: TypeName, keyType: Type? = nil) { self.name = name self.valueTypeName = valueTypeName self.valueType = valueType self.keyTypeName = keyTypeName self.keyType = keyType } /// Returns dictionary as generic type public var asGeneric: GenericType { GenericType(name: "Dictionary", typeParameters: [ .init(typeName: keyTypeName), .init(typeName: valueTypeName) ]) } public var asSource: String { "[\\(keyTypeName.asSource): \\(valueTypeName.asSource)]" } // sourcery:inline:DictionaryType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let valueTypeName: TypeName = aDecoder.decode(forKey: "valueTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["valueTypeName"])); fatalError() }; self.valueTypeName = valueTypeName self.valueType = aDecoder.decode(forKey: "valueType") guard let keyTypeName: TypeName = aDecoder.decode(forKey: "keyTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["keyTypeName"])); fatalError() }; self.keyTypeName = keyTypeName self.keyType = aDecoder.decode(forKey: "keyType") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.valueTypeName, forKey: "valueTypeName") aCoder.encode(self.valueType, forKey: "valueType") aCoder.encode(self.keyTypeName, forKey: "keyTypeName") aCoder.encode(self.keyType, forKey: "keyType") } // sourcery:end } """), .init(name: "Diffable.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import Foundation extension ArrayType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? ArrayType else { results.append("Incorrect type <expected: ArrayType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "elementTypeName").trackDifference(actual: self.elementTypeName, expected: castObject.elementTypeName)) return results } } extension AssociatedType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? AssociatedType else { results.append("Incorrect type <expected: AssociatedType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) return results } } extension AssociatedValue: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? AssociatedValue else { results.append("Incorrect type <expected: AssociatedValue, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "localName").trackDifference(actual: self.localName, expected: castObject.localName)) results.append(contentsOf: DiffableResult(identifier: "externalName").trackDifference(actual: self.externalName, expected: castObject.externalName)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) results.append(contentsOf: DiffableResult(identifier: "defaultValue").trackDifference(actual: self.defaultValue, expected: castObject.defaultValue)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) return results } } extension Attribute: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Attribute else { results.append("Incorrect type <expected: Attribute, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "arguments").trackDifference(actual: self.arguments, expected: castObject.arguments)) results.append(contentsOf: DiffableResult(identifier: "_description").trackDifference(actual: self._description, expected: castObject._description)) return results } } extension BytesRange: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? BytesRange else { results.append("Incorrect type <expected: BytesRange, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "offset").trackDifference(actual: self.offset, expected: castObject.offset)) results.append(contentsOf: DiffableResult(identifier: "length").trackDifference(actual: self.length, expected: castObject.length)) return results } } extension Class { override public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Class else { results.append("Incorrect type <expected: Class, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: super.diffAgainst(castObject)) return results } } extension ClosureType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? ClosureType else { results.append("Incorrect type <expected: ClosureType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "parameters").trackDifference(actual: self.parameters, expected: castObject.parameters)) results.append(contentsOf: DiffableResult(identifier: "returnTypeName").trackDifference(actual: self.returnTypeName, expected: castObject.returnTypeName)) results.append(contentsOf: DiffableResult(identifier: "isAsync").trackDifference(actual: self.isAsync, expected: castObject.isAsync)) results.append(contentsOf: DiffableResult(identifier: "asyncKeyword").trackDifference(actual: self.asyncKeyword, expected: castObject.asyncKeyword)) results.append(contentsOf: DiffableResult(identifier: "`throws`").trackDifference(actual: self.`throws`, expected: castObject.`throws`)) results.append(contentsOf: DiffableResult(identifier: "throwsOrRethrowsKeyword").trackDifference(actual: self.throwsOrRethrowsKeyword, expected: castObject.throwsOrRethrowsKeyword)) return results } } extension DictionaryType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? DictionaryType else { results.append("Incorrect type <expected: DictionaryType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "valueTypeName").trackDifference(actual: self.valueTypeName, expected: castObject.valueTypeName)) results.append(contentsOf: DiffableResult(identifier: "keyTypeName").trackDifference(actual: self.keyTypeName, expected: castObject.keyTypeName)) return results } } extension Enum { override public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Enum else { results.append("Incorrect type <expected: Enum, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "cases").trackDifference(actual: self.cases, expected: castObject.cases)) results.append(contentsOf: DiffableResult(identifier: "rawTypeName").trackDifference(actual: self.rawTypeName, expected: castObject.rawTypeName)) results.append(contentsOf: super.diffAgainst(castObject)) return results } } extension EnumCase: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? EnumCase else { results.append("Incorrect type <expected: EnumCase, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "rawValue").trackDifference(actual: self.rawValue, expected: castObject.rawValue)) results.append(contentsOf: DiffableResult(identifier: "associatedValues").trackDifference(actual: self.associatedValues, expected: castObject.associatedValues)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) results.append(contentsOf: DiffableResult(identifier: "documentation").trackDifference(actual: self.documentation, expected: castObject.documentation)) results.append(contentsOf: DiffableResult(identifier: "indirect").trackDifference(actual: self.indirect, expected: castObject.indirect)) return results } } extension FileParserResult: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? FileParserResult else { results.append("Incorrect type <expected: FileParserResult, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "path").trackDifference(actual: self.path, expected: castObject.path)) results.append(contentsOf: DiffableResult(identifier: "module").trackDifference(actual: self.module, expected: castObject.module)) results.append(contentsOf: DiffableResult(identifier: "types").trackDifference(actual: self.types, expected: castObject.types)) results.append(contentsOf: DiffableResult(identifier: "functions").trackDifference(actual: self.functions, expected: castObject.functions)) results.append(contentsOf: DiffableResult(identifier: "typealiases").trackDifference(actual: self.typealiases, expected: castObject.typealiases)) results.append(contentsOf: DiffableResult(identifier: "inlineRanges").trackDifference(actual: self.inlineRanges, expected: castObject.inlineRanges)) results.append(contentsOf: DiffableResult(identifier: "inlineIndentations").trackDifference(actual: self.inlineIndentations, expected: castObject.inlineIndentations)) results.append(contentsOf: DiffableResult(identifier: "modifiedDate").trackDifference(actual: self.modifiedDate, expected: castObject.modifiedDate)) results.append(contentsOf: DiffableResult(identifier: "sourceryVersion").trackDifference(actual: self.sourceryVersion, expected: castObject.sourceryVersion)) return results } } extension GenericRequirement: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? GenericRequirement else { results.append("Incorrect type <expected: GenericRequirement, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "leftType").trackDifference(actual: self.leftType, expected: castObject.leftType)) results.append(contentsOf: DiffableResult(identifier: "rightType").trackDifference(actual: self.rightType, expected: castObject.rightType)) results.append(contentsOf: DiffableResult(identifier: "relationship").trackDifference(actual: self.relationship, expected: castObject.relationship)) results.append(contentsOf: DiffableResult(identifier: "relationshipSyntax").trackDifference(actual: self.relationshipSyntax, expected: castObject.relationshipSyntax)) return results } } extension GenericType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? GenericType else { results.append("Incorrect type <expected: GenericType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "typeParameters").trackDifference(actual: self.typeParameters, expected: castObject.typeParameters)) return results } } extension GenericTypeParameter: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? GenericTypeParameter else { results.append("Incorrect type <expected: GenericTypeParameter, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) return results } } extension Import: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Import else { results.append("Incorrect type <expected: Import, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "kind").trackDifference(actual: self.kind, expected: castObject.kind)) results.append(contentsOf: DiffableResult(identifier: "path").trackDifference(actual: self.path, expected: castObject.path)) return results } } extension Method: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Method else { results.append("Incorrect type <expected: Method, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "selectorName").trackDifference(actual: self.selectorName, expected: castObject.selectorName)) results.append(contentsOf: DiffableResult(identifier: "parameters").trackDifference(actual: self.parameters, expected: castObject.parameters)) results.append(contentsOf: DiffableResult(identifier: "returnTypeName").trackDifference(actual: self.returnTypeName, expected: castObject.returnTypeName)) results.append(contentsOf: DiffableResult(identifier: "isAsync").trackDifference(actual: self.isAsync, expected: castObject.isAsync)) results.append(contentsOf: DiffableResult(identifier: "`throws`").trackDifference(actual: self.`throws`, expected: castObject.`throws`)) results.append(contentsOf: DiffableResult(identifier: "`rethrows`").trackDifference(actual: self.`rethrows`, expected: castObject.`rethrows`)) results.append(contentsOf: DiffableResult(identifier: "accessLevel").trackDifference(actual: self.accessLevel, expected: castObject.accessLevel)) results.append(contentsOf: DiffableResult(identifier: "isStatic").trackDifference(actual: self.isStatic, expected: castObject.isStatic)) results.append(contentsOf: DiffableResult(identifier: "isClass").trackDifference(actual: self.isClass, expected: castObject.isClass)) results.append(contentsOf: DiffableResult(identifier: "isFailableInitializer").trackDifference(actual: self.isFailableInitializer, expected: castObject.isFailableInitializer)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) results.append(contentsOf: DiffableResult(identifier: "documentation").trackDifference(actual: self.documentation, expected: castObject.documentation)) results.append(contentsOf: DiffableResult(identifier: "definedInTypeName").trackDifference(actual: self.definedInTypeName, expected: castObject.definedInTypeName)) results.append(contentsOf: DiffableResult(identifier: "attributes").trackDifference(actual: self.attributes, expected: castObject.attributes)) results.append(contentsOf: DiffableResult(identifier: "modifiers").trackDifference(actual: self.modifiers, expected: castObject.modifiers)) return results } } extension MethodParameter: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? MethodParameter else { results.append("Incorrect type <expected: MethodParameter, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "argumentLabel").trackDifference(actual: self.argumentLabel, expected: castObject.argumentLabel)) results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) results.append(contentsOf: DiffableResult(identifier: "`inout`").trackDifference(actual: self.`inout`, expected: castObject.`inout`)) results.append(contentsOf: DiffableResult(identifier: "isVariadic").trackDifference(actual: self.isVariadic, expected: castObject.isVariadic)) results.append(contentsOf: DiffableResult(identifier: "defaultValue").trackDifference(actual: self.defaultValue, expected: castObject.defaultValue)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) return results } } extension Modifier: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Modifier else { results.append("Incorrect type <expected: Modifier, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "detail").trackDifference(actual: self.detail, expected: castObject.detail)) return results } } extension Protocol { override public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Protocol else { results.append("Incorrect type <expected: Protocol, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "associatedTypes").trackDifference(actual: self.associatedTypes, expected: castObject.associatedTypes)) results.append(contentsOf: DiffableResult(identifier: "genericRequirements").trackDifference(actual: self.genericRequirements, expected: castObject.genericRequirements)) results.append(contentsOf: super.diffAgainst(castObject)) return results } } extension ProtocolComposition { override public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? ProtocolComposition else { results.append("Incorrect type <expected: ProtocolComposition, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "composedTypeNames").trackDifference(actual: self.composedTypeNames, expected: castObject.composedTypeNames)) results.append(contentsOf: super.diffAgainst(castObject)) return results } } extension Struct { override public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Struct else { results.append("Incorrect type <expected: Struct, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: super.diffAgainst(castObject)) return results } } extension Subscript: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Subscript else { results.append("Incorrect type <expected: Subscript, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "parameters").trackDifference(actual: self.parameters, expected: castObject.parameters)) results.append(contentsOf: DiffableResult(identifier: "returnTypeName").trackDifference(actual: self.returnTypeName, expected: castObject.returnTypeName)) results.append(contentsOf: DiffableResult(identifier: "readAccess").trackDifference(actual: self.readAccess, expected: castObject.readAccess)) results.append(contentsOf: DiffableResult(identifier: "writeAccess").trackDifference(actual: self.writeAccess, expected: castObject.writeAccess)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) results.append(contentsOf: DiffableResult(identifier: "documentation").trackDifference(actual: self.documentation, expected: castObject.documentation)) results.append(contentsOf: DiffableResult(identifier: "definedInTypeName").trackDifference(actual: self.definedInTypeName, expected: castObject.definedInTypeName)) results.append(contentsOf: DiffableResult(identifier: "attributes").trackDifference(actual: self.attributes, expected: castObject.attributes)) results.append(contentsOf: DiffableResult(identifier: "modifiers").trackDifference(actual: self.modifiers, expected: castObject.modifiers)) return results } } extension TemplateContext: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? TemplateContext else { results.append("Incorrect type <expected: TemplateContext, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "parserResult").trackDifference(actual: self.parserResult, expected: castObject.parserResult)) results.append(contentsOf: DiffableResult(identifier: "functions").trackDifference(actual: self.functions, expected: castObject.functions)) results.append(contentsOf: DiffableResult(identifier: "types").trackDifference(actual: self.types, expected: castObject.types)) results.append(contentsOf: DiffableResult(identifier: "argument").trackDifference(actual: self.argument, expected: castObject.argument)) return results } } extension TupleElement: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? TupleElement else { results.append("Incorrect type <expected: TupleElement, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) return results } } extension TupleType: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? TupleType else { results.append("Incorrect type <expected: TupleType, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "elements").trackDifference(actual: self.elements, expected: castObject.elements)) return results } } extension Type: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Type else { results.append("Incorrect type <expected: Type, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "module").trackDifference(actual: self.module, expected: castObject.module)) results.append(contentsOf: DiffableResult(identifier: "imports").trackDifference(actual: self.imports, expected: castObject.imports)) results.append(contentsOf: DiffableResult(identifier: "typealiases").trackDifference(actual: self.typealiases, expected: castObject.typealiases)) results.append(contentsOf: DiffableResult(identifier: "isExtension").trackDifference(actual: self.isExtension, expected: castObject.isExtension)) results.append(contentsOf: DiffableResult(identifier: "accessLevel").trackDifference(actual: self.accessLevel, expected: castObject.accessLevel)) results.append(contentsOf: DiffableResult(identifier: "isUnknownExtension").trackDifference(actual: self.isUnknownExtension, expected: castObject.isUnknownExtension)) results.append(contentsOf: DiffableResult(identifier: "isGeneric").trackDifference(actual: self.isGeneric, expected: castObject.isGeneric)) results.append(contentsOf: DiffableResult(identifier: "localName").trackDifference(actual: self.localName, expected: castObject.localName)) results.append(contentsOf: DiffableResult(identifier: "rawVariables").trackDifference(actual: self.rawVariables, expected: castObject.rawVariables)) results.append(contentsOf: DiffableResult(identifier: "rawMethods").trackDifference(actual: self.rawMethods, expected: castObject.rawMethods)) results.append(contentsOf: DiffableResult(identifier: "rawSubscripts").trackDifference(actual: self.rawSubscripts, expected: castObject.rawSubscripts)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) results.append(contentsOf: DiffableResult(identifier: "documentation").trackDifference(actual: self.documentation, expected: castObject.documentation)) results.append(contentsOf: DiffableResult(identifier: "inheritedTypes").trackDifference(actual: self.inheritedTypes, expected: castObject.inheritedTypes)) results.append(contentsOf: DiffableResult(identifier: "inherits").trackDifference(actual: self.inherits, expected: castObject.inherits)) results.append(contentsOf: DiffableResult(identifier: "containedTypes").trackDifference(actual: self.containedTypes, expected: castObject.containedTypes)) results.append(contentsOf: DiffableResult(identifier: "parentName").trackDifference(actual: self.parentName, expected: castObject.parentName)) results.append(contentsOf: DiffableResult(identifier: "attributes").trackDifference(actual: self.attributes, expected: castObject.attributes)) results.append(contentsOf: DiffableResult(identifier: "modifiers").trackDifference(actual: self.modifiers, expected: castObject.modifiers)) results.append(contentsOf: DiffableResult(identifier: "fileName").trackDifference(actual: self.fileName, expected: castObject.fileName)) return results } } extension TypeName: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? TypeName else { results.append("Incorrect type <expected: TypeName, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "generic").trackDifference(actual: self.generic, expected: castObject.generic)) results.append(contentsOf: DiffableResult(identifier: "isProtocolComposition").trackDifference(actual: self.isProtocolComposition, expected: castObject.isProtocolComposition)) results.append(contentsOf: DiffableResult(identifier: "attributes").trackDifference(actual: self.attributes, expected: castObject.attributes)) results.append(contentsOf: DiffableResult(identifier: "modifiers").trackDifference(actual: self.modifiers, expected: castObject.modifiers)) results.append(contentsOf: DiffableResult(identifier: "tuple").trackDifference(actual: self.tuple, expected: castObject.tuple)) results.append(contentsOf: DiffableResult(identifier: "array").trackDifference(actual: self.array, expected: castObject.array)) results.append(contentsOf: DiffableResult(identifier: "dictionary").trackDifference(actual: self.dictionary, expected: castObject.dictionary)) results.append(contentsOf: DiffableResult(identifier: "closure").trackDifference(actual: self.closure, expected: castObject.closure)) return results } } extension Typealias: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Typealias else { results.append("Incorrect type <expected: Typealias, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "aliasName").trackDifference(actual: self.aliasName, expected: castObject.aliasName)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) results.append(contentsOf: DiffableResult(identifier: "module").trackDifference(actual: self.module, expected: castObject.module)) results.append(contentsOf: DiffableResult(identifier: "accessLevel").trackDifference(actual: self.accessLevel, expected: castObject.accessLevel)) results.append(contentsOf: DiffableResult(identifier: "parentName").trackDifference(actual: self.parentName, expected: castObject.parentName)) return results } } extension Types: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Types else { results.append("Incorrect type <expected: Types, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "types").trackDifference(actual: self.types, expected: castObject.types)) results.append(contentsOf: DiffableResult(identifier: "typealiases").trackDifference(actual: self.typealiases, expected: castObject.typealiases)) return results } } extension Variable: Diffable { @objc public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let castObject = object as? Variable else { results.append("Incorrect type <expected: Variable, received: \\(Swift.type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "name").trackDifference(actual: self.name, expected: castObject.name)) results.append(contentsOf: DiffableResult(identifier: "typeName").trackDifference(actual: self.typeName, expected: castObject.typeName)) results.append(contentsOf: DiffableResult(identifier: "isComputed").trackDifference(actual: self.isComputed, expected: castObject.isComputed)) results.append(contentsOf: DiffableResult(identifier: "isAsync").trackDifference(actual: self.isAsync, expected: castObject.isAsync)) results.append(contentsOf: DiffableResult(identifier: "`throws`").trackDifference(actual: self.`throws`, expected: castObject.`throws`)) results.append(contentsOf: DiffableResult(identifier: "isStatic").trackDifference(actual: self.isStatic, expected: castObject.isStatic)) results.append(contentsOf: DiffableResult(identifier: "readAccess").trackDifference(actual: self.readAccess, expected: castObject.readAccess)) results.append(contentsOf: DiffableResult(identifier: "writeAccess").trackDifference(actual: self.writeAccess, expected: castObject.writeAccess)) results.append(contentsOf: DiffableResult(identifier: "defaultValue").trackDifference(actual: self.defaultValue, expected: castObject.defaultValue)) results.append(contentsOf: DiffableResult(identifier: "annotations").trackDifference(actual: self.annotations, expected: castObject.annotations)) results.append(contentsOf: DiffableResult(identifier: "documentation").trackDifference(actual: self.documentation, expected: castObject.documentation)) results.append(contentsOf: DiffableResult(identifier: "attributes").trackDifference(actual: self.attributes, expected: castObject.attributes)) results.append(contentsOf: DiffableResult(identifier: "modifiers").trackDifference(actual: self.modifiers, expected: castObject.modifiers)) results.append(contentsOf: DiffableResult(identifier: "definedInTypeName").trackDifference(actual: self.definedInTypeName, expected: castObject.definedInTypeName)) return results } } """), .init(name: "Diffable.swift", content: """ // // Diffable.swift // Sourcery // // Created by Krzysztof Zabłocki on 22/12/2016. // Copyright © 2016 Pixle. All rights reserved. // import Foundation public protocol Diffable { /// Returns `DiffableResult` for the given objects. /// /// - Parameter object: Object to diff against. /// - Returns: Diffable results. func diffAgainst(_ object: Any?) -> DiffableResult } /// :nodoc: extension NSRange: Diffable { /// :nodoc: public static func == (lhs: NSRange, rhs: NSRange) -> Bool { return NSEqualRanges(lhs, rhs) } public func diffAgainst(_ object: Any?) -> DiffableResult { let results = DiffableResult() guard let rhs = object as? NSRange else { results.append("Incorrect type <expected: FileParserResult, received: \\(type(of: object))>") return results } results.append(contentsOf: DiffableResult(identifier: "location").trackDifference(actual: self.location, expected: rhs.location)) results.append(contentsOf: DiffableResult(identifier: "length").trackDifference(actual: self.length, expected: rhs.length)) return results } } @objcMembers public class DiffableResult: NSObject, AutoEquatable { // sourcery: skipEquality private var results: [String] internal var identifier: String? init(results: [String] = [], identifier: String? = nil) { self.results = results self.identifier = identifier } func append(_ element: String) { results.append(element) } func append(contentsOf contents: DiffableResult) { if !contents.isEmpty { results.append(contents.description) } } var isEmpty: Bool { return results.isEmpty } public override var description: String { guard !results.isEmpty else { return "" } return "\\(identifier.flatMap { "\\($0) " } ?? "")" + results.joined(separator: "\\n") } } public extension DiffableResult { #if swift(>=4.1) #else /// :nodoc: @discardableResult func trackDifference<T: Equatable>(actual: T, expected: T) -> DiffableResult { if actual != expected { let result = DiffableResult(results: ["<expected: \\(expected), received: \\(actual)>"]) append(contentsOf: result) } return self } #endif /// :nodoc: @discardableResult func trackDifference<T: Equatable>(actual: T?, expected: T?) -> DiffableResult { if actual != expected { let result = DiffableResult(results: ["<expected: \\(expected.map({ "\\($0)" }) ?? "nil"), received: \\(actual.map({ "\\($0)" }) ?? "nil")>"]) append(contentsOf: result) } return self } /// :nodoc: @discardableResult func trackDifference<T: Equatable>(actual: T, expected: T) -> DiffableResult where T: Diffable { let diffResult = actual.diffAgainst(expected) append(contentsOf: diffResult) return self } /// :nodoc: @discardableResult func trackDifference<T: Equatable>(actual: [T], expected: [T]) -> DiffableResult where T: Diffable { let diffResult = DiffableResult() defer { append(contentsOf: diffResult) } guard actual.count == expected.count else { diffResult.append("Different count, expected: \\(expected.count), received: \\(actual.count)") return self } for (idx, item) in actual.enumerated() { let diff = DiffableResult() diff.trackDifference(actual: item, expected: expected[idx]) if !diff.isEmpty { let string = "idx \\(idx): \\(diff)" diffResult.append(string) } } return self } /// :nodoc: @discardableResult func trackDifference<T: Equatable>(actual: [T], expected: [T]) -> DiffableResult { let diffResult = DiffableResult() defer { append(contentsOf: diffResult) } guard actual.count == expected.count else { diffResult.append("Different count, expected: \\(expected.count), received: \\(actual.count)") return self } for (idx, item) in actual.enumerated() where item != expected[idx] { let string = "idx \\(idx): <expected: \\(expected), received: \\(actual)>" diffResult.append(string) } return self } /// :nodoc: @discardableResult func trackDifference<K, T: Equatable>(actual: [K: T], expected: [K: T]) -> DiffableResult where T: Diffable { let diffResult = DiffableResult() defer { append(contentsOf: diffResult) } guard actual.count == expected.count else { append("Different count, expected: \\(expected.count), received: \\(actual.count)") if expected.count > actual.count { let missingKeys = Array(expected.keys.filter { actual[$0] == nil }.map { String(describing: $0) }) diffResult.append("Missing keys: \\(missingKeys.joined(separator: ", "))") } return self } for (key, actualElement) in actual { guard let expectedElement = expected[key] else { diffResult.append("Missing key \\"\\(key)\\"") continue } let diff = DiffableResult() diff.trackDifference(actual: actualElement, expected: expectedElement) if !diff.isEmpty { let string = "key \\"\\(key)\\": \\(diff)" diffResult.append(string) } } return self } // MARK: - NSObject diffing /// :nodoc: @discardableResult func trackDifference<K, T: NSObjectProtocol>(actual: [K: T], expected: [K: T]) -> DiffableResult { let diffResult = DiffableResult() defer { append(contentsOf: diffResult) } guard actual.count == expected.count else { append("Different count, expected: \\(expected.count), received: \\(actual.count)") if expected.count > actual.count { let missingKeys = Array(expected.keys.filter { actual[$0] == nil }.map { String(describing: $0) }) diffResult.append("Missing keys: \\(missingKeys.joined(separator: ", "))") } return self } for (key, actualElement) in actual { guard let expectedElement = expected[key] else { diffResult.append("Missing key \\"\\(key)\\"") continue } if !actualElement.isEqual(expectedElement) { diffResult.append("key \\"\\(key)\\": <expected: \\(expected), received: \\(actual)>") } } return self } } """), .init(name: "Documentation.swift", content: """ import Foundation public typealias Documentation = [String] /// Describes a declaration with documentation, i.e. type, method, variable, enum case public protocol Documented { var documentation: Documentation { get } } """), .init(name: "Enum.swift", content: """ // // Created by Krzysztof Zablocki on 13/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// Defines enum case associated value @objcMembers public final class AssociatedValue: NSObject, SourceryModel, AutoDescription, Typed, Annotated { /// Associated value local name. /// This is a name to be used to construct enum case value public let localName: String? /// Associated value external name. /// This is a name to be used to access value in value-bindig public let externalName: String? /// Associated value type name public let typeName: TypeName // sourcery: skipEquality, skipDescription /// Associated value type, if known public var type: Type? /// Associated value default value public let defaultValue: String? /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public var annotations: Annotations = [:] /// :nodoc: public init(localName: String?, externalName: String?, typeName: TypeName, type: Type? = nil, defaultValue: String? = nil, annotations: [String: NSObject] = [:]) { self.localName = localName self.externalName = externalName self.typeName = typeName self.type = type self.defaultValue = defaultValue self.annotations = annotations } convenience init(name: String? = nil, typeName: TypeName, type: Type? = nil, defaultValue: String? = nil, annotations: [String: NSObject] = [:]) { self.init(localName: name, externalName: name, typeName: typeName, type: type, defaultValue: defaultValue, annotations: annotations) } // sourcery:inline:AssociatedValue.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.localName = aDecoder.decode(forKey: "localName") self.externalName = aDecoder.decode(forKey: "externalName") guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") self.defaultValue = aDecoder.decode(forKey: "defaultValue") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.localName, forKey: "localName") aCoder.encode(self.externalName, forKey: "externalName") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.defaultValue, forKey: "defaultValue") aCoder.encode(self.annotations, forKey: "annotations") } // sourcery:end } /// Defines enum case @objcMembers public final class EnumCase: NSObject, SourceryModel, AutoDescription, Annotated, Documented { /// Enum case name public let name: String /// Enum case raw value, if any public let rawValue: String? /// Enum case associated values public let associatedValues: [AssociatedValue] /// Enum case annotations public var annotations: Annotations = [:] public var documentation: Documentation = [] /// Whether enum case is indirect public let indirect: Bool /// Whether enum case has associated value public var hasAssociatedValue: Bool { return !associatedValues.isEmpty } // Underlying parser data, never to be used by anything else // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(name: String, rawValue: String? = nil, associatedValues: [AssociatedValue] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], indirect: Bool = false) { self.name = name self.rawValue = rawValue self.associatedValues = associatedValues self.annotations = annotations self.documentation = documentation self.indirect = indirect } // sourcery:inline:EnumCase.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name self.rawValue = aDecoder.decode(forKey: "rawValue") guard let associatedValues: [AssociatedValue] = aDecoder.decode(forKey: "associatedValues") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["associatedValues"])); fatalError() }; self.associatedValues = associatedValues guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation self.indirect = aDecoder.decode(forKey: "indirect") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.rawValue, forKey: "rawValue") aCoder.encode(self.associatedValues, forKey: "associatedValues") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.indirect, forKey: "indirect") } // sourcery:end } /// Defines Swift enum @objcMembers public final class Enum: Type { // sourcery: skipDescription /// Returns "enum" public override var kind: String { return "enum" } /// Enum cases public var cases: [EnumCase] /** Enum raw value type name, if any. This type is removed from enum's `based` and `inherited` types collections. - important: Unless raw type is specified explicitly via type alias RawValue it will be set to the first type in the inheritance chain. So if your enum does not have raw value but implements protocols you'll have to specify conformance to these protocols via extension to get enum with nil raw value type and all based and inherited types. */ public var rawTypeName: TypeName? { didSet { if let rawTypeName = rawTypeName { hasRawType = true if let index = inheritedTypes.firstIndex(of: rawTypeName.name) { inheritedTypes.remove(at: index) } if based[rawTypeName.name] != nil { based[rawTypeName.name] = nil } } else { hasRawType = false } } } // sourcery: skipDescription, skipEquality /// :nodoc: public private(set) var hasRawType: Bool // sourcery: skipDescription, skipEquality /// Enum raw value type, if known public var rawType: Type? // sourcery: skipEquality, skipDescription, skipCoding /// Names of types or protocols this type inherits from, including unknown (not scanned) types public override var based: [String: String] { didSet { if let rawTypeName = rawTypeName, based[rawTypeName.name] != nil { based[rawTypeName.name] = nil } } } /// Whether enum contains any associated values public var hasAssociatedValues: Bool { return cases.contains(where: { $0.hasAssociatedValue }) } /// :nodoc: public init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, inheritedTypes: [String] = [], rawTypeName: TypeName? = nil, cases: [EnumCase] = [], variables: [Variable] = [], methods: [Method] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], isGeneric: Bool = false) { self.cases = cases self.rawTypeName = rawTypeName self.hasRawType = rawTypeName != nil || !inheritedTypes.isEmpty super.init(name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, attributes: attributes, modifiers: modifiers, annotations: annotations, documentation: documentation, isGeneric: isGeneric) if let rawTypeName = rawTypeName?.name, let index = self.inheritedTypes.firstIndex(of: rawTypeName) { self.inheritedTypes.remove(at: index) } } // sourcery:inline:Enum.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let cases: [EnumCase] = aDecoder.decode(forKey: "cases") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["cases"])); fatalError() }; self.cases = cases self.rawTypeName = aDecoder.decode(forKey: "rawTypeName") self.hasRawType = aDecoder.decode(forKey: "hasRawType") self.rawType = aDecoder.decode(forKey: "rawType") super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.cases, forKey: "cases") aCoder.encode(self.rawTypeName, forKey: "rawTypeName") aCoder.encode(self.hasRawType, forKey: "hasRawType") aCoder.encode(self.rawType, forKey: "rawType") } // sourcery:end } """), .init(name: "Equality.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace extension ArrayType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? ArrayType else { return false } if self.name != rhs.name { return false } if self.elementTypeName != rhs.elementTypeName { return false } return true } } extension AssociatedType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? AssociatedType else { return false } if self.name != rhs.name { return false } if self.typeName != rhs.typeName { return false } return true } } extension AssociatedValue { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? AssociatedValue else { return false } if self.localName != rhs.localName { return false } if self.externalName != rhs.externalName { return false } if self.typeName != rhs.typeName { return false } if self.defaultValue != rhs.defaultValue { return false } if self.annotations != rhs.annotations { return false } return true } } extension Attribute { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Attribute else { return false } if self.name != rhs.name { return false } if self.arguments != rhs.arguments { return false } if self._description != rhs._description { return false } return true } } extension BytesRange { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? BytesRange else { return false } if self.offset != rhs.offset { return false } if self.length != rhs.length { return false } return true } } extension Class { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Class else { return false } return super.isEqual(rhs) } } extension ClosureParameter { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? ClosureParameter else { return false } if self.argumentLabel != rhs.argumentLabel { return false } if self.name != rhs.name { return false } if self.typeName != rhs.typeName { return false } if self.`inout` != rhs.`inout` { return false } if self.defaultValue != rhs.defaultValue { return false } if self.annotations != rhs.annotations { return false } return true } } extension ClosureType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? ClosureType else { return false } if self.name != rhs.name { return false } if self.parameters != rhs.parameters { return false } if self.returnTypeName != rhs.returnTypeName { return false } if self.isAsync != rhs.isAsync { return false } if self.asyncKeyword != rhs.asyncKeyword { return false } if self.`throws` != rhs.`throws` { return false } if self.throwsOrRethrowsKeyword != rhs.throwsOrRethrowsKeyword { return false } return true } } extension DictionaryType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? DictionaryType else { return false } if self.name != rhs.name { return false } if self.valueTypeName != rhs.valueTypeName { return false } if self.keyTypeName != rhs.keyTypeName { return false } return true } } extension DiffableResult { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? DiffableResult else { return false } if self.identifier != rhs.identifier { return false } return true } } extension Enum { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Enum else { return false } if self.cases != rhs.cases { return false } if self.rawTypeName != rhs.rawTypeName { return false } return super.isEqual(rhs) } } extension EnumCase { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? EnumCase else { return false } if self.name != rhs.name { return false } if self.rawValue != rhs.rawValue { return false } if self.associatedValues != rhs.associatedValues { return false } if self.annotations != rhs.annotations { return false } if self.documentation != rhs.documentation { return false } if self.indirect != rhs.indirect { return false } return true } } extension FileParserResult { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? FileParserResult else { return false } if self.path != rhs.path { return false } if self.module != rhs.module { return false } if self.types != rhs.types { return false } if self.functions != rhs.functions { return false } if self.typealiases != rhs.typealiases { return false } if self.inlineRanges != rhs.inlineRanges { return false } if self.inlineIndentations != rhs.inlineIndentations { return false } if self.modifiedDate != rhs.modifiedDate { return false } if self.sourceryVersion != rhs.sourceryVersion { return false } return true } } extension GenericRequirement { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? GenericRequirement else { return false } if self.leftType != rhs.leftType { return false } if self.rightType != rhs.rightType { return false } if self.relationship != rhs.relationship { return false } if self.relationshipSyntax != rhs.relationshipSyntax { return false } return true } } extension GenericType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? GenericType else { return false } if self.name != rhs.name { return false } if self.typeParameters != rhs.typeParameters { return false } return true } } extension GenericTypeParameter { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? GenericTypeParameter else { return false } if self.typeName != rhs.typeName { return false } return true } } extension Import { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Import else { return false } if self.kind != rhs.kind { return false } if self.path != rhs.path { return false } return true } } extension Method { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Method else { return false } if self.name != rhs.name { return false } if self.selectorName != rhs.selectorName { return false } if self.parameters != rhs.parameters { return false } if self.returnTypeName != rhs.returnTypeName { return false } if self.isAsync != rhs.isAsync { return false } if self.`throws` != rhs.`throws` { return false } if self.`rethrows` != rhs.`rethrows` { return false } if self.accessLevel != rhs.accessLevel { return false } if self.isStatic != rhs.isStatic { return false } if self.isClass != rhs.isClass { return false } if self.isFailableInitializer != rhs.isFailableInitializer { return false } if self.annotations != rhs.annotations { return false } if self.documentation != rhs.documentation { return false } if self.definedInTypeName != rhs.definedInTypeName { return false } if self.attributes != rhs.attributes { return false } if self.modifiers != rhs.modifiers { return false } return true } } extension MethodParameter { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? MethodParameter else { return false } if self.argumentLabel != rhs.argumentLabel { return false } if self.name != rhs.name { return false } if self.typeName != rhs.typeName { return false } if self.`inout` != rhs.`inout` { return false } if self.isVariadic != rhs.isVariadic { return false } if self.defaultValue != rhs.defaultValue { return false } if self.annotations != rhs.annotations { return false } return true } } extension Modifier { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Modifier else { return false } if self.name != rhs.name { return false } if self.detail != rhs.detail { return false } return true } } extension Protocol { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Protocol else { return false } if self.associatedTypes != rhs.associatedTypes { return false } if self.genericRequirements != rhs.genericRequirements { return false } return super.isEqual(rhs) } } extension ProtocolComposition { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? ProtocolComposition else { return false } if self.composedTypeNames != rhs.composedTypeNames { return false } return super.isEqual(rhs) } } extension Struct { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Struct else { return false } return super.isEqual(rhs) } } extension Subscript { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Subscript else { return false } if self.parameters != rhs.parameters { return false } if self.returnTypeName != rhs.returnTypeName { return false } if self.readAccess != rhs.readAccess { return false } if self.writeAccess != rhs.writeAccess { return false } if self.annotations != rhs.annotations { return false } if self.documentation != rhs.documentation { return false } if self.definedInTypeName != rhs.definedInTypeName { return false } if self.attributes != rhs.attributes { return false } if self.modifiers != rhs.modifiers { return false } return true } } extension TemplateContext { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? TemplateContext else { return false } if self.parserResult != rhs.parserResult { return false } if self.functions != rhs.functions { return false } if self.types != rhs.types { return false } if self.argument != rhs.argument { return false } return true } } extension TupleElement { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? TupleElement else { return false } if self.name != rhs.name { return false } if self.typeName != rhs.typeName { return false } return true } } extension TupleType { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? TupleType else { return false } if self.name != rhs.name { return false } if self.elements != rhs.elements { return false } return true } } extension Type { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Type else { return false } if self.module != rhs.module { return false } if self.imports != rhs.imports { return false } if self.typealiases != rhs.typealiases { return false } if self.isExtension != rhs.isExtension { return false } if self.accessLevel != rhs.accessLevel { return false } if self.isUnknownExtension != rhs.isUnknownExtension { return false } if self.isGeneric != rhs.isGeneric { return false } if self.localName != rhs.localName { return false } if self.rawVariables != rhs.rawVariables { return false } if self.rawMethods != rhs.rawMethods { return false } if self.rawSubscripts != rhs.rawSubscripts { return false } if self.annotations != rhs.annotations { return false } if self.documentation != rhs.documentation { return false } if self.inheritedTypes != rhs.inheritedTypes { return false } if self.inherits != rhs.inherits { return false } if self.containedTypes != rhs.containedTypes { return false } if self.parentName != rhs.parentName { return false } if self.attributes != rhs.attributes { return false } if self.modifiers != rhs.modifiers { return false } if self.fileName != rhs.fileName { return false } if self.kind != rhs.kind { return false } return true } } extension TypeName { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? TypeName else { return false } if self.name != rhs.name { return false } if self.generic != rhs.generic { return false } if self.isProtocolComposition != rhs.isProtocolComposition { return false } if self.attributes != rhs.attributes { return false } if self.modifiers != rhs.modifiers { return false } if self.tuple != rhs.tuple { return false } if self.array != rhs.array { return false } if self.dictionary != rhs.dictionary { return false } if self.closure != rhs.closure { return false } return true } } extension Typealias { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Typealias else { return false } if self.aliasName != rhs.aliasName { return false } if self.typeName != rhs.typeName { return false } if self.module != rhs.module { return false } if self.accessLevel != rhs.accessLevel { return false } if self.parentName != rhs.parentName { return false } return true } } extension Types { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Types else { return false } if self.types != rhs.types { return false } if self.typealiases != rhs.typealiases { return false } return true } } extension Variable { /// :nodoc: public override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? Variable else { return false } if self.name != rhs.name { return false } if self.typeName != rhs.typeName { return false } if self.isComputed != rhs.isComputed { return false } if self.isAsync != rhs.isAsync { return false } if self.`throws` != rhs.`throws` { return false } if self.isStatic != rhs.isStatic { return false } if self.readAccess != rhs.readAccess { return false } if self.writeAccess != rhs.writeAccess { return false } if self.defaultValue != rhs.defaultValue { return false } if self.annotations != rhs.annotations { return false } if self.documentation != rhs.documentation { return false } if self.attributes != rhs.attributes { return false } if self.modifiers != rhs.modifiers { return false } if self.definedInTypeName != rhs.definedInTypeName { return false } return true } } // MARK: - ArrayType AutoHashable extension ArrayType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.elementTypeName) return hasher.finalize() } } // MARK: - AssociatedType AutoHashable extension AssociatedType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.typeName) return hasher.finalize() } } // MARK: - AssociatedValue AutoHashable extension AssociatedValue { public override var hash: Int { var hasher = Hasher() hasher.combine(self.localName) hasher.combine(self.externalName) hasher.combine(self.typeName) hasher.combine(self.defaultValue) hasher.combine(self.annotations) return hasher.finalize() } } // MARK: - Attribute AutoHashable extension Attribute { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.arguments) hasher.combine(self._description) return hasher.finalize() } } // MARK: - BytesRange AutoHashable extension BytesRange { public override var hash: Int { var hasher = Hasher() hasher.combine(self.offset) hasher.combine(self.length) return hasher.finalize() } } // MARK: - Class AutoHashable extension Class { public override var hash: Int { var hasher = Hasher() hasher.combine(super.hash) return hasher.finalize() } } // MARK: - ClosureParameter AutoHashable extension ClosureParameter { public override var hash: Int { var hasher = Hasher() hasher.combine(self.argumentLabel) hasher.combine(self.name) hasher.combine(self.typeName) hasher.combine(self.`inout`) hasher.combine(self.defaultValue) hasher.combine(self.annotations) return hasher.finalize() } } // MARK: - ClosureType AutoHashable extension ClosureType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.parameters) hasher.combine(self.returnTypeName) hasher.combine(self.isAsync) hasher.combine(self.asyncKeyword) hasher.combine(self.`throws`) hasher.combine(self.throwsOrRethrowsKeyword) return hasher.finalize() } } // MARK: - DictionaryType AutoHashable extension DictionaryType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.valueTypeName) hasher.combine(self.keyTypeName) return hasher.finalize() } } // MARK: - DiffableResult AutoHashable extension DiffableResult { public override var hash: Int { var hasher = Hasher() hasher.combine(self.identifier) return hasher.finalize() } } // MARK: - Enum AutoHashable extension Enum { public override var hash: Int { var hasher = Hasher() hasher.combine(self.cases) hasher.combine(self.rawTypeName) hasher.combine(super.hash) return hasher.finalize() } } // MARK: - EnumCase AutoHashable extension EnumCase { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.rawValue) hasher.combine(self.associatedValues) hasher.combine(self.annotations) hasher.combine(self.documentation) hasher.combine(self.indirect) return hasher.finalize() } } // MARK: - FileParserResult AutoHashable extension FileParserResult { public override var hash: Int { var hasher = Hasher() hasher.combine(self.path) hasher.combine(self.module) hasher.combine(self.types) hasher.combine(self.functions) hasher.combine(self.typealiases) hasher.combine(self.inlineRanges) hasher.combine(self.inlineIndentations) hasher.combine(self.modifiedDate) hasher.combine(self.sourceryVersion) return hasher.finalize() } } // MARK: - GenericRequirement AutoHashable extension GenericRequirement { public override var hash: Int { var hasher = Hasher() hasher.combine(self.leftType) hasher.combine(self.rightType) hasher.combine(self.relationship) hasher.combine(self.relationshipSyntax) return hasher.finalize() } } // MARK: - GenericType AutoHashable extension GenericType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.typeParameters) return hasher.finalize() } } // MARK: - GenericTypeParameter AutoHashable extension GenericTypeParameter { public override var hash: Int { var hasher = Hasher() hasher.combine(self.typeName) return hasher.finalize() } } // MARK: - Import AutoHashable extension Import { public override var hash: Int { var hasher = Hasher() hasher.combine(self.kind) hasher.combine(self.path) return hasher.finalize() } } // MARK: - Method AutoHashable extension Method { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.selectorName) hasher.combine(self.parameters) hasher.combine(self.returnTypeName) hasher.combine(self.isAsync) hasher.combine(self.`throws`) hasher.combine(self.`rethrows`) hasher.combine(self.accessLevel) hasher.combine(self.isStatic) hasher.combine(self.isClass) hasher.combine(self.isFailableInitializer) hasher.combine(self.annotations) hasher.combine(self.documentation) hasher.combine(self.definedInTypeName) hasher.combine(self.attributes) hasher.combine(self.modifiers) return hasher.finalize() } } // MARK: - MethodParameter AutoHashable extension MethodParameter { public override var hash: Int { var hasher = Hasher() hasher.combine(self.argumentLabel) hasher.combine(self.name) hasher.combine(self.typeName) hasher.combine(self.`inout`) hasher.combine(self.isVariadic) hasher.combine(self.defaultValue) hasher.combine(self.annotations) return hasher.finalize() } } // MARK: - Modifier AutoHashable extension Modifier { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.detail) return hasher.finalize() } } // MARK: - Protocol AutoHashable extension Protocol { public override var hash: Int { var hasher = Hasher() hasher.combine(self.associatedTypes) hasher.combine(self.genericRequirements) hasher.combine(super.hash) return hasher.finalize() } } // MARK: - ProtocolComposition AutoHashable extension ProtocolComposition { public override var hash: Int { var hasher = Hasher() hasher.combine(self.composedTypeNames) hasher.combine(super.hash) return hasher.finalize() } } // MARK: - Struct AutoHashable extension Struct { public override var hash: Int { var hasher = Hasher() hasher.combine(super.hash) return hasher.finalize() } } // MARK: - Subscript AutoHashable extension Subscript { public override var hash: Int { var hasher = Hasher() hasher.combine(self.parameters) hasher.combine(self.returnTypeName) hasher.combine(self.readAccess) hasher.combine(self.writeAccess) hasher.combine(self.annotations) hasher.combine(self.documentation) hasher.combine(self.definedInTypeName) hasher.combine(self.attributes) hasher.combine(self.modifiers) return hasher.finalize() } } // MARK: - TemplateContext AutoHashable extension TemplateContext { public override var hash: Int { var hasher = Hasher() hasher.combine(self.parserResult) hasher.combine(self.functions) hasher.combine(self.types) hasher.combine(self.argument) return hasher.finalize() } } // MARK: - TupleElement AutoHashable extension TupleElement { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.typeName) return hasher.finalize() } } // MARK: - TupleType AutoHashable extension TupleType { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.elements) return hasher.finalize() } } // MARK: - Type AutoHashable extension Type { public override var hash: Int { var hasher = Hasher() hasher.combine(self.module) hasher.combine(self.imports) hasher.combine(self.typealiases) hasher.combine(self.isExtension) hasher.combine(self.accessLevel) hasher.combine(self.isUnknownExtension) hasher.combine(self.isGeneric) hasher.combine(self.localName) hasher.combine(self.rawVariables) hasher.combine(self.rawMethods) hasher.combine(self.rawSubscripts) hasher.combine(self.annotations) hasher.combine(self.documentation) hasher.combine(self.inheritedTypes) hasher.combine(self.inherits) hasher.combine(self.containedTypes) hasher.combine(self.parentName) hasher.combine(self.attributes) hasher.combine(self.modifiers) hasher.combine(self.fileName) hasher.combine(kind) return hasher.finalize() } } // MARK: - TypeName AutoHashable extension TypeName { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.generic) hasher.combine(self.isProtocolComposition) hasher.combine(self.attributes) hasher.combine(self.modifiers) hasher.combine(self.tuple) hasher.combine(self.array) hasher.combine(self.dictionary) hasher.combine(self.closure) return hasher.finalize() } } // MARK: - Typealias AutoHashable extension Typealias { public override var hash: Int { var hasher = Hasher() hasher.combine(self.aliasName) hasher.combine(self.typeName) hasher.combine(self.module) hasher.combine(self.accessLevel) hasher.combine(self.parentName) return hasher.finalize() } } // MARK: - Types AutoHashable extension Types { public override var hash: Int { var hasher = Hasher() hasher.combine(self.types) hasher.combine(self.typealiases) return hasher.finalize() } } // MARK: - Variable AutoHashable extension Variable { public override var hash: Int { var hasher = Hasher() hasher.combine(self.name) hasher.combine(self.typeName) hasher.combine(self.isComputed) hasher.combine(self.isAsync) hasher.combine(self.`throws`) hasher.combine(self.isStatic) hasher.combine(self.readAccess) hasher.combine(self.writeAccess) hasher.combine(self.defaultValue) hasher.combine(self.annotations) hasher.combine(self.documentation) hasher.combine(self.attributes) hasher.combine(self.modifiers) hasher.combine(self.definedInTypeName) return hasher.finalize() } } """), .init(name: "Extensions.swift", content: """ import Foundation public extension StringProtocol { /// Trimms leading and trailing whitespaces and newlines var trimmed: String { self.trimmingCharacters(in: .whitespacesAndNewlines) } } public extension String { /// Returns nil if string is empty var nilIfEmpty: String? { if isEmpty { return nil } return self } /// Returns nil if string is empty or contains `_` character var nilIfNotValidParameterName: String? { if isEmpty { return nil } if self == "_" { return nil } return self } /// :nodoc: /// - Parameter substring: Instance of a substring /// - Returns: Returns number of times a substring appears in self func countInstances(of substring: String) -> Int { guard !substring.isEmpty else { return 0 } var count = 0 var searchRange: Range<String.Index>? while let foundRange = range(of: substring, options: [], range: searchRange) { count += 1 searchRange = Range(uncheckedBounds: (lower: foundRange.upperBound, upper: endIndex)) } return count } /// :nodoc: /// Removes leading and trailing whitespace from str. Returns false if str was not altered. @discardableResult mutating func strip() -> Bool { let strippedString = stripped() guard strippedString != self else { return false } self = strippedString return true } /// :nodoc: /// Returns a copy of str with leading and trailing whitespace removed. func stripped() -> String { return String(self.trimmingCharacters(in: .whitespaces)) } /// :nodoc: @discardableResult mutating func trimPrefix(_ prefix: String) -> Bool { guard hasPrefix(prefix) else { return false } self = String(self.suffix(self.count - prefix.count)) return true } /// :nodoc: func trimmingPrefix(_ prefix: String) -> String { guard hasPrefix(prefix) else { return self } return String(self.suffix(self.count - prefix.count)) } /// :nodoc: @discardableResult mutating func trimSuffix(_ suffix: String) -> Bool { guard hasSuffix(suffix) else { return false } self = String(self.prefix(self.count - suffix.count)) return true } /// :nodoc: func trimmingSuffix(_ suffix: String) -> String { guard hasSuffix(suffix) else { return self } return String(self.prefix(self.count - suffix.count)) } /// :nodoc: func dropFirstAndLast(_ n: Int = 1) -> String { return drop(first: n, last: n) } /// :nodoc: func drop(first: Int, last: Int) -> String { return String(self.dropFirst(first).dropLast(last)) } /// :nodoc: /// Wraps brackets if needed to make a valid type name func bracketsBalancing() -> String { if hasPrefix("(") && hasSuffix(")") { let unwrapped = dropFirstAndLast() return unwrapped.commaSeparated().count == 1 ? unwrapped.bracketsBalancing() : self } else { let wrapped = "(\\(self))" return wrapped.isValidTupleName() || !isBracketsBalanced() ? wrapped : self } } /// :nodoc: /// Returns true if given string can represent a valid tuple type name func isValidTupleName() -> Bool { guard hasPrefix("(") && hasSuffix(")") else { return false } let trimmedBracketsName = dropFirstAndLast() return trimmedBracketsName.isBracketsBalanced() && trimmedBracketsName.commaSeparated().count > 1 } /// :nodoc: func isValidArrayName() -> Bool { if hasPrefix("Array<") { return true } if hasPrefix("[") && hasSuffix("]") { return dropFirstAndLast().colonSeparated().count == 1 } return false } /// :nodoc: func isValidDictionaryName() -> Bool { if hasPrefix("Dictionary<") { return true } if hasPrefix("[") && contains(":") && hasSuffix("]") { return dropFirstAndLast().colonSeparated().count == 2 } return false } /// :nodoc: func isValidClosureName() -> Bool { return components(separatedBy: "->", excludingDelimiterBetween: (["(", "<"], [")", ">"])).count > 1 } /// :nodoc: /// Returns true if all opening brackets are balanced with closed brackets. func isBracketsBalanced() -> Bool { var bracketsCount: Int = 0 for char in self { if char == "(" { bracketsCount += 1 } else if char == ")" { bracketsCount -= 1 } if bracketsCount < 0 { return false } } return bracketsCount == 0 } /// :nodoc: /// Returns components separated with a comma respecting nested types func commaSeparated() -> [String] { return components(separatedBy: ",", excludingDelimiterBetween: ("<[({", "})]>")) } /// :nodoc: /// Returns components separated with colon respecting nested types func colonSeparated() -> [String] { return components(separatedBy: ":", excludingDelimiterBetween: ("<[({", "})]>")) } /// :nodoc: /// Returns components separated with semicolon respecting nested contexts func semicolonSeparated() -> [String] { return components(separatedBy: ";", excludingDelimiterBetween: ("{", "}")) } /// :nodoc: func components(separatedBy delimiter: String, excludingDelimiterBetween between: (open: String, close: String)) -> [String] { return self.components(separatedBy: delimiter, excludingDelimiterBetween: (between.open.map { String($0) }, between.close.map { String($0) })) } /// :nodoc: func components(separatedBy delimiter: String, excludingDelimiterBetween between: (open: [String], close: [String])) -> [String] { var boundingCharactersCount: Int = 0 var quotesCount: Int = 0 var item = "" var items = [String]() var i = self.startIndex while i < self.endIndex { var offset = 1 defer { i = self.index(i, offsetBy: offset) } let currentlyScanned = self[i..<(self.index(i, offsetBy: delimiter.count, limitedBy: self.endIndex) ?? self.endIndex)] if let openString = between.open.first(where: { String(self[i...]).starts(with: $0) }) { if !(boundingCharactersCount == 0 && String(self[i]) == delimiter) { boundingCharactersCount += 1 } offset = openString.count } else if let closeString = between.close.first(where: { String(self[i...]).starts(with: $0) }) { // do not count `->` if !(self[i] == ">" && item.last == "-") { boundingCharactersCount = max(0, boundingCharactersCount - 1) } offset = closeString.count } if self[i] == "\\"" { quotesCount += 1 } if currentlyScanned == delimiter && boundingCharactersCount == 0 && quotesCount % 2 == 0 { items.append(item) item = "" i = self.index(i, offsetBy: delimiter.count - 1) } else { item += self[i..<self.index(i, offsetBy: offset)] } } items.append(item) return items } } public extension NSString { /// :nodoc: var entireRange: NSRange { return NSRange(location: 0, length: self.length) } } """), .init(name: "FileParserResult.swift", content: """ // // FileParserResult.swift // Sourcery // // Created by Krzysztof Zablocki on 11/01/2017. // Copyright © 2017 Pixle. All rights reserved. // import Foundation // sourcery: skipJSExport /// :nodoc: @objcMembers public final class FileParserResult: NSObject, SourceryModel { public let path: String? public let module: String? public var types = [Type]() { didSet { types.forEach { type in guard type.module == nil, type.kind != "extensions" else { return } type.module = module } } } public var functions = [SourceryMethod]() public var typealiases = [Typealias]() public var inlineRanges = [String: NSRange]() public var inlineIndentations = [String: String]() public var modifiedDate: Date public var sourceryVersion: String var isEmpty: Bool { types.isEmpty && functions.isEmpty && typealiases.isEmpty && inlineRanges.isEmpty && inlineIndentations.isEmpty } public init(path: String?, module: String?, types: [Type], functions: [SourceryMethod], typealiases: [Typealias] = [], inlineRanges: [String: NSRange] = [:], inlineIndentations: [String: String] = [:], modifiedDate: Date = Date(), sourceryVersion: String = "") { self.path = path self.module = module self.types = types self.functions = functions self.typealiases = typealiases self.inlineRanges = inlineRanges self.inlineIndentations = inlineIndentations self.modifiedDate = modifiedDate self.sourceryVersion = sourceryVersion types.forEach { type in type.module = module } } // sourcery:inline:FileParserResult.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.path = aDecoder.decode(forKey: "path") self.module = aDecoder.decode(forKey: "module") guard let types: [Type] = aDecoder.decode(forKey: "types") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["types"])); fatalError() }; self.types = types guard let functions: [SourceryMethod] = aDecoder.decode(forKey: "functions") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["functions"])); fatalError() }; self.functions = functions guard let typealiases: [Typealias] = aDecoder.decode(forKey: "typealiases") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typealiases"])); fatalError() }; self.typealiases = typealiases guard let inlineRanges: [String: NSRange] = aDecoder.decode(forKey: "inlineRanges") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inlineRanges"])); fatalError() }; self.inlineRanges = inlineRanges guard let inlineIndentations: [String: String] = aDecoder.decode(forKey: "inlineIndentations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inlineIndentations"])); fatalError() }; self.inlineIndentations = inlineIndentations guard let modifiedDate: Date = aDecoder.decode(forKey: "modifiedDate") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiedDate"])); fatalError() }; self.modifiedDate = modifiedDate guard let sourceryVersion: String = aDecoder.decode(forKey: "sourceryVersion") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["sourceryVersion"])); fatalError() }; self.sourceryVersion = sourceryVersion } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.path, forKey: "path") aCoder.encode(self.module, forKey: "module") aCoder.encode(self.types, forKey: "types") aCoder.encode(self.functions, forKey: "functions") aCoder.encode(self.typealiases, forKey: "typealiases") aCoder.encode(self.inlineRanges, forKey: "inlineRanges") aCoder.encode(self.inlineIndentations, forKey: "inlineIndentations") aCoder.encode(self.modifiedDate, forKey: "modifiedDate") aCoder.encode(self.sourceryVersion, forKey: "sourceryVersion") } // sourcery:end } """), .init(name: "Generic.swift", content: """ import Foundation /// Descibes Swift generic type @objcMembers public final class GenericType: NSObject, SourceryModelWithoutDescription { /// The name of the base type, i.e. `Array` for `Array<Int>` public var name: String /// This generic type parameters public let typeParameters: [GenericTypeParameter] /// :nodoc: public init(name: String, typeParameters: [GenericTypeParameter] = []) { self.name = name self.typeParameters = typeParameters } public var asSource: String { let arguments = typeParameters .map({ $0.typeName.asSource }) .joined(separator: ", ") return "\\(name)<\\(arguments)>" } public override var description: String { asSource } // sourcery:inline:GenericType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let typeParameters: [GenericTypeParameter] = aDecoder.decode(forKey: "typeParameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeParameters"])); fatalError() }; self.typeParameters = typeParameters } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeParameters, forKey: "typeParameters") } // sourcery:end } /// Descibes Swift generic type parameter @objcMembers public final class GenericTypeParameter: NSObject, SourceryModel { /// Generic parameter type name public var typeName: TypeName // sourcery: skipEquality, skipDescription /// Generic parameter type, if known public var type: Type? /// :nodoc: public init(typeName: TypeName, type: Type? = nil) { self.typeName = typeName self.type = type } // sourcery:inline:GenericTypeParameter.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") } // sourcery:end } """), .init(name: "GenericRequirement.swift", content: """ import Foundation /// modifier can be thing like `private`, `class`, `nonmutating` /// if a declaration has modifier like `private(set)` it's name will be `private` and detail will be `set` @objcMembers public class GenericRequirement: NSObject, SourceryModel { public enum Relationship: String { case equals case conformsTo var syntax: String { switch self { case .equals: return "==" case .conformsTo: return ":" } } } public var leftType: AssociatedType public let rightType: GenericTypeParameter /// relationship name public let relationship: String /// Syntax e.g. `==` or `:` public let relationshipSyntax: String public init(leftType: AssociatedType, rightType: GenericTypeParameter, relationship: Relationship) { self.leftType = leftType self.rightType = rightType self.relationship = relationship.rawValue self.relationshipSyntax = relationship.syntax } // sourcery:inline:GenericRequirement.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let leftType: AssociatedType = aDecoder.decode(forKey: "leftType") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["leftType"])); fatalError() }; self.leftType = leftType guard let rightType: GenericTypeParameter = aDecoder.decode(forKey: "rightType") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["rightType"])); fatalError() }; self.rightType = rightType guard let relationship: String = aDecoder.decode(forKey: "relationship") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["relationship"])); fatalError() }; self.relationship = relationship guard let relationshipSyntax: String = aDecoder.decode(forKey: "relationshipSyntax") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["relationshipSyntax"])); fatalError() }; self.relationshipSyntax = relationshipSyntax } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.leftType, forKey: "leftType") aCoder.encode(self.rightType, forKey: "rightType") aCoder.encode(self.relationship, forKey: "relationship") aCoder.encode(self.relationshipSyntax, forKey: "relationshipSyntax") } // sourcery:end } """), .init(name: "Import.swift", content: """ import Foundation /// Defines import type @objcMembers public class Import: NSObject, SourceryModelWithoutDescription { /// Import kind, e.g. class, struct in `import class Module.ClassName` public var kind: String? /// Import path public var path: String /// :nodoc: public init(path: String, kind: String? = nil) { self.path = path self.kind = kind } /// Full import value e.g. `import struct Module.StructName` public override var description: String { if let kind = kind { return "\\(kind) \\(path)" } return path } /// Returns module name from a import, e.g. if you had `import struct Module.Submodule.Struct` it will return `Module.Submodule` public var moduleName: String { if kind != nil { if let idx = path.lastIndex(of: ".") { return String(path[..<idx]) } else { return path } } else { return path } } // sourcery:inline:Import.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.kind = aDecoder.decode(forKey: "kind") guard let path: String = aDecoder.decode(forKey: "path") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["path"])); fatalError() }; self.path = path } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.kind, forKey: "kind") aCoder.encode(self.path, forKey: "path") } // sourcery:end } """), .init(name: "JSExport.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace trailing_newline import JavaScriptCore @objc protocol ArrayTypeAutoJSExport: JSExport { var name: String { get } var elementTypeName: TypeName { get } var elementType: Type? { get } var asGeneric: GenericType { get } var asSource: String { get } } extension ArrayType: ArrayTypeAutoJSExport {} @objc protocol AssociatedTypeAutoJSExport: JSExport { var name: String { get } var typeName: TypeName? { get } var type: Type? { get } } extension AssociatedType: AssociatedTypeAutoJSExport {} @objc protocol AssociatedValueAutoJSExport: JSExport { var localName: String? { get } var externalName: String? { get } var typeName: TypeName { get } var type: Type? { get } var defaultValue: String? { get } var annotations: Annotations { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } } extension AssociatedValue: AssociatedValueAutoJSExport {} @objc protocol AttributeAutoJSExport: JSExport { var name: String { get } var arguments: [String: NSObject] { get } var asSource: String { get } var description: String { get } } extension Attribute: AttributeAutoJSExport {} @objc protocol BytesRangeAutoJSExport: JSExport { var offset: Int64 { get } var length: Int64 { get } } extension BytesRange: BytesRangeAutoJSExport {} @objc protocol ClassAutoJSExport: JSExport { var kind: String { get } var isFinal: Bool { get } var module: String? { get } var imports: [Import] { get } var allImports: [Import] { get } var accessLevel: String { get } var name: String { get } var isUnknownExtension: Bool { get } var globalName: String { get } var isGeneric: Bool { get } var localName: String { get } var variables: [Variable] { get } var rawVariables: [Variable] { get } var allVariables: [Variable] { get } var methods: [Method] { get } var rawMethods: [Method] { get } var allMethods: [Method] { get } var subscripts: [Subscript] { get } var rawSubscripts: [Subscript] { get } var allSubscripts: [Subscript] { get } var initializers: [Method] { get } var annotations: Annotations { get } var documentation: Documentation { get } var staticVariables: [Variable] { get } var staticMethods: [Method] { get } var classMethods: [Method] { get } var instanceVariables: [Variable] { get } var instanceMethods: [Method] { get } var computedVariables: [Variable] { get } var storedVariables: [Variable] { get } var inheritedTypes: [String] { get } var based: [String: String] { get } var basedTypes: [String: Type] { get } var inherits: [String: Type] { get } var implements: [String: Type] { get } var containedTypes: [Type] { get } var containedType: [String: Type] { get } var parentName: String? { get } var parent: Type? { get } var supertype: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var fileName: String? { get } } extension Class: ClassAutoJSExport {} @objc protocol ClosureParameterAutoJSExport: JSExport { var argumentLabel: String? { get } var name: String? { get } var typeName: TypeName { get } var `inout`: Bool { get } var type: Type? { get } var typeAttributes: AttributeList { get } var defaultValue: String? { get } var annotations: Annotations { get } var asSource: String { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } } extension ClosureParameter: ClosureParameterAutoJSExport {} @objc protocol ClosureTypeAutoJSExport: JSExport { var name: String { get } var parameters: [ClosureParameter] { get } var returnTypeName: TypeName { get } var actualReturnTypeName: TypeName { get } var returnType: Type? { get } var isOptionalReturnType: Bool { get } var isImplicitlyUnwrappedOptionalReturnType: Bool { get } var unwrappedReturnTypeName: String { get } var isAsync: Bool { get } var asyncKeyword: String? { get } var `throws`: Bool { get } var throwsOrRethrowsKeyword: String? { get } var asSource: String { get } } extension ClosureType: ClosureTypeAutoJSExport {} @objc protocol DictionaryTypeAutoJSExport: JSExport { var name: String { get } var valueTypeName: TypeName { get } var valueType: Type? { get } var keyTypeName: TypeName { get } var keyType: Type? { get } var asGeneric: GenericType { get } var asSource: String { get } } extension DictionaryType: DictionaryTypeAutoJSExport {} @objc protocol EnumAutoJSExport: JSExport { var kind: String { get } var cases: [EnumCase] { get } var rawTypeName: TypeName? { get } var hasRawType: Bool { get } var rawType: Type? { get } var based: [String: String] { get } var hasAssociatedValues: Bool { get } var module: String? { get } var imports: [Import] { get } var allImports: [Import] { get } var accessLevel: String { get } var name: String { get } var isUnknownExtension: Bool { get } var globalName: String { get } var isGeneric: Bool { get } var localName: String { get } var variables: [Variable] { get } var rawVariables: [Variable] { get } var allVariables: [Variable] { get } var methods: [Method] { get } var rawMethods: [Method] { get } var allMethods: [Method] { get } var subscripts: [Subscript] { get } var rawSubscripts: [Subscript] { get } var allSubscripts: [Subscript] { get } var initializers: [Method] { get } var annotations: Annotations { get } var documentation: Documentation { get } var staticVariables: [Variable] { get } var staticMethods: [Method] { get } var classMethods: [Method] { get } var instanceVariables: [Variable] { get } var instanceMethods: [Method] { get } var computedVariables: [Variable] { get } var storedVariables: [Variable] { get } var inheritedTypes: [String] { get } var basedTypes: [String: Type] { get } var inherits: [String: Type] { get } var implements: [String: Type] { get } var containedTypes: [Type] { get } var containedType: [String: Type] { get } var parentName: String? { get } var parent: Type? { get } var supertype: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var fileName: String? { get } } extension Enum: EnumAutoJSExport {} @objc protocol EnumCaseAutoJSExport: JSExport { var name: String { get } var rawValue: String? { get } var associatedValues: [AssociatedValue] { get } var annotations: Annotations { get } var documentation: Documentation { get } var indirect: Bool { get } var hasAssociatedValue: Bool { get } } extension EnumCase: EnumCaseAutoJSExport {} @objc protocol GenericRequirementAutoJSExport: JSExport { var leftType: AssociatedType { get } var rightType: GenericTypeParameter { get } var relationship: String { get } var relationshipSyntax: String { get } } extension GenericRequirement: GenericRequirementAutoJSExport {} @objc protocol GenericTypeAutoJSExport: JSExport { var name: String { get } var typeParameters: [GenericTypeParameter] { get } var asSource: String { get } var description: String { get } } extension GenericType: GenericTypeAutoJSExport {} @objc protocol GenericTypeParameterAutoJSExport: JSExport { var typeName: TypeName { get } var type: Type? { get } } extension GenericTypeParameter: GenericTypeParameterAutoJSExport {} @objc protocol ImportAutoJSExport: JSExport { var kind: String? { get } var path: String { get } var description: String { get } var moduleName: String { get } } extension Import: ImportAutoJSExport {} @objc protocol MethodAutoJSExport: JSExport { var name: String { get } var selectorName: String { get } var shortName: String { get } var callName: String { get } var parameters: [MethodParameter] { get } var returnTypeName: TypeName { get } var actualReturnTypeName: TypeName { get } var returnType: Type? { get } var isOptionalReturnType: Bool { get } var isImplicitlyUnwrappedOptionalReturnType: Bool { get } var unwrappedReturnTypeName: String { get } var isAsync: Bool { get } var `throws`: Bool { get } var `rethrows`: Bool { get } var accessLevel: String { get } var isStatic: Bool { get } var isClass: Bool { get } var isInitializer: Bool { get } var isDeinitializer: Bool { get } var isFailableInitializer: Bool { get } var isConvenienceInitializer: Bool { get } var isRequired: Bool { get } var isFinal: Bool { get } var isMutating: Bool { get } var isGeneric: Bool { get } var isOptional: Bool { get } var annotations: Annotations { get } var documentation: Documentation { get } var definedInTypeName: TypeName? { get } var actualDefinedInTypeName: TypeName? { get } var definedInType: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } } extension Method: MethodAutoJSExport {} @objc protocol MethodParameterAutoJSExport: JSExport { var argumentLabel: String? { get } var name: String { get } var typeName: TypeName { get } var `inout`: Bool { get } var isVariadic: Bool { get } var type: Type? { get } var typeAttributes: AttributeList { get } var defaultValue: String? { get } var annotations: Annotations { get } var asSource: String { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } } extension MethodParameter: MethodParameterAutoJSExport {} @objc protocol ModifierAutoJSExport: JSExport { var name: String { get } var detail: String? { get } var asSource: String { get } } extension Modifier: ModifierAutoJSExport {} @objc protocol ProtocolAutoJSExport: JSExport { var kind: String { get } var associatedTypes: [String: AssociatedType] { get } var genericRequirements: [GenericRequirement] { get } var module: String? { get } var imports: [Import] { get } var allImports: [Import] { get } var accessLevel: String { get } var name: String { get } var isUnknownExtension: Bool { get } var globalName: String { get } var isGeneric: Bool { get } var localName: String { get } var variables: [Variable] { get } var rawVariables: [Variable] { get } var allVariables: [Variable] { get } var methods: [Method] { get } var rawMethods: [Method] { get } var allMethods: [Method] { get } var subscripts: [Subscript] { get } var rawSubscripts: [Subscript] { get } var allSubscripts: [Subscript] { get } var initializers: [Method] { get } var annotations: Annotations { get } var documentation: Documentation { get } var staticVariables: [Variable] { get } var staticMethods: [Method] { get } var classMethods: [Method] { get } var instanceVariables: [Variable] { get } var instanceMethods: [Method] { get } var computedVariables: [Variable] { get } var storedVariables: [Variable] { get } var inheritedTypes: [String] { get } var based: [String: String] { get } var basedTypes: [String: Type] { get } var inherits: [String: Type] { get } var implements: [String: Type] { get } var containedTypes: [Type] { get } var containedType: [String: Type] { get } var parentName: String? { get } var parent: Type? { get } var supertype: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var fileName: String? { get } } extension Protocol: ProtocolAutoJSExport {} @objc protocol StructAutoJSExport: JSExport { var kind: String { get } var module: String? { get } var imports: [Import] { get } var allImports: [Import] { get } var accessLevel: String { get } var name: String { get } var isUnknownExtension: Bool { get } var globalName: String { get } var isGeneric: Bool { get } var localName: String { get } var variables: [Variable] { get } var rawVariables: [Variable] { get } var allVariables: [Variable] { get } var methods: [Method] { get } var rawMethods: [Method] { get } var allMethods: [Method] { get } var subscripts: [Subscript] { get } var rawSubscripts: [Subscript] { get } var allSubscripts: [Subscript] { get } var initializers: [Method] { get } var annotations: Annotations { get } var documentation: Documentation { get } var staticVariables: [Variable] { get } var staticMethods: [Method] { get } var classMethods: [Method] { get } var instanceVariables: [Variable] { get } var instanceMethods: [Method] { get } var computedVariables: [Variable] { get } var storedVariables: [Variable] { get } var inheritedTypes: [String] { get } var based: [String: String] { get } var basedTypes: [String: Type] { get } var inherits: [String: Type] { get } var implements: [String: Type] { get } var containedTypes: [Type] { get } var containedType: [String: Type] { get } var parentName: String? { get } var parent: Type? { get } var supertype: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var fileName: String? { get } } extension Struct: StructAutoJSExport {} @objc protocol SubscriptAutoJSExport: JSExport { var parameters: [MethodParameter] { get } var returnTypeName: TypeName { get } var actualReturnTypeName: TypeName { get } var returnType: Type? { get } var isOptionalReturnType: Bool { get } var isImplicitlyUnwrappedOptionalReturnType: Bool { get } var unwrappedReturnTypeName: String { get } var isFinal: Bool { get } var readAccess: String { get } var writeAccess: String { get } var isMutable: Bool { get } var annotations: Annotations { get } var documentation: Documentation { get } var definedInTypeName: TypeName? { get } var actualDefinedInTypeName: TypeName? { get } var definedInType: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } } extension Subscript: SubscriptAutoJSExport {} @objc protocol TemplateContextAutoJSExport: JSExport { var functions: [SourceryMethod] { get } var types: Types { get } var argument: [String: NSObject] { get } var type: [String: Type] { get } var stencilContext: [String: Any] { get } var jsContext: [String: Any] { get } } extension TemplateContext: TemplateContextAutoJSExport {} @objc protocol TupleElementAutoJSExport: JSExport { var name: String? { get } var typeName: TypeName { get } var type: Type? { get } var asSource: String { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } } extension TupleElement: TupleElementAutoJSExport {} @objc protocol TupleTypeAutoJSExport: JSExport { var name: String { get } var elements: [TupleElement] { get } } extension TupleType: TupleTypeAutoJSExport {} @objc protocol TypeAutoJSExport: JSExport { var module: String? { get } var imports: [Import] { get } var allImports: [Import] { get } var kind: String { get } var accessLevel: String { get } var name: String { get } var isUnknownExtension: Bool { get } var globalName: String { get } var isGeneric: Bool { get } var localName: String { get } var variables: [Variable] { get } var rawVariables: [Variable] { get } var allVariables: [Variable] { get } var methods: [Method] { get } var rawMethods: [Method] { get } var allMethods: [Method] { get } var subscripts: [Subscript] { get } var rawSubscripts: [Subscript] { get } var allSubscripts: [Subscript] { get } var initializers: [Method] { get } var annotations: Annotations { get } var documentation: Documentation { get } var staticVariables: [Variable] { get } var staticMethods: [Method] { get } var classMethods: [Method] { get } var instanceVariables: [Variable] { get } var instanceMethods: [Method] { get } var computedVariables: [Variable] { get } var storedVariables: [Variable] { get } var inheritedTypes: [String] { get } var based: [String: String] { get } var basedTypes: [String: Type] { get } var inherits: [String: Type] { get } var implements: [String: Type] { get } var containedTypes: [Type] { get } var containedType: [String: Type] { get } var parentName: String? { get } var parent: Type? { get } var supertype: Type? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var fileName: String? { get } } extension Type: TypeAutoJSExport {} @objc protocol TypeNameAutoJSExport: JSExport { var name: String { get } var generic: GenericType? { get } var isGeneric: Bool { get } var isProtocolComposition: Bool { get } var actualTypeName: TypeName? { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } var isVoid: Bool { get } var isTuple: Bool { get } var tuple: TupleType? { get } var isArray: Bool { get } var array: ArrayType? { get } var isDictionary: Bool { get } var dictionary: DictionaryType? { get } var isClosure: Bool { get } var closure: ClosureType? { get } var asSource: String { get } var description: String { get } var debugDescription: String { get } } extension TypeName: TypeNameAutoJSExport {} @objc protocol TypesCollectionAutoJSExport: JSExport { } extension TypesCollection: TypesCollectionAutoJSExport {} @objc protocol VariableAutoJSExport: JSExport { var name: String { get } var typeName: TypeName { get } var type: Type? { get } var isComputed: Bool { get } var isAsync: Bool { get } var `throws`: Bool { get } var isStatic: Bool { get } var readAccess: String { get } var writeAccess: String { get } var isMutable: Bool { get } var defaultValue: String? { get } var annotations: Annotations { get } var documentation: Documentation { get } var attributes: AttributeList { get } var modifiers: [SourceryModifier] { get } var isFinal: Bool { get } var isLazy: Bool { get } var definedInTypeName: TypeName? { get } var actualDefinedInTypeName: TypeName? { get } var definedInType: Type? { get } var isOptional: Bool { get } var isImplicitlyUnwrappedOptional: Bool { get } var unwrappedTypeName: String { get } } extension Variable: VariableAutoJSExport {} """), .init(name: "Log.swift", content: """ import Darwin import Foundation /// :nodoc: public enum Log { public enum Level: Int { case errors case warnings case info case verbose } public static var level: Level = .warnings public static var logBenchmarks: Bool = false public static var logAST: Bool = false public static var stackMessages: Bool = false public private(set) static var messagesStack = [String]() public static func error(_ message: Any) { log(level: .errors, "error: \\(message)") // to return error when running swift templates which is done in a different process if ProcessInfo().processName != "Sourcery" { fputs("\\(message)", stderr) } } public static func warning(_ message: Any) { log(level: .warnings, "warning: \\(message)") } public static func astWarning(_ message: Any) { guard logAST else { return } log(level: .warnings, "ast warning: \\(message)") } public static func astError(_ message: Any) { guard logAST else { return } log(level: .errors, "ast error: \\(message)") } public static func verbose(_ message: Any) { log(level: .verbose, message) } public static func info(_ message: Any) { log(level: .info, message) } public static func benchmark(_ message: Any) { guard logBenchmarks else { return } if stackMessages { messagesStack.append("\\(message)") } else { print(message) } } private static func log(level logLevel: Level, _ message: Any) { guard logLevel.rawValue <= Log.level.rawValue else { return } if stackMessages { messagesStack.append("\\(message)") } else { print(message) } } public static func output(_ message: String) { print(message) } } extension String: Error {} """), .init(name: "Method.swift", content: """ import Foundation /// :nodoc: public typealias SourceryMethod = Method /// Describes method parameter @objcMembers public class MethodParameter: NSObject, SourceryModel, Typed, Annotated { /// Parameter external name public var argumentLabel: String? // Note: although method parameter can have no name, this property is not optional, // this is so to maintain compatibility with existing templates. /// Parameter internal name public let name: String /// Parameter type name public let typeName: TypeName /// Parameter flag whether it's inout or not public let `inout`: Bool /// Is this variadic parameter? public let isVariadic: Bool // sourcery: skipEquality, skipDescription /// Parameter type, if known public var type: Type? /// Parameter type attributes, i.e. `@escaping` public var typeAttributes: AttributeList { return typeName.attributes } /// Method parameter default value expression public var defaultValue: String? /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public var annotations: Annotations = [:] /// :nodoc: public init(argumentLabel: String?, name: String = "", typeName: TypeName, type: Type? = nil, defaultValue: String? = nil, annotations: [String: NSObject] = [:], isInout: Bool = false, isVariadic: Bool = false) { self.typeName = typeName self.argumentLabel = argumentLabel self.name = name self.type = type self.defaultValue = defaultValue self.annotations = annotations self.`inout` = isInout self.isVariadic = isVariadic } /// :nodoc: public init(name: String = "", typeName: TypeName, type: Type? = nil, defaultValue: String? = nil, annotations: [String: NSObject] = [:], isInout: Bool = false, isVariadic: Bool = false) { self.typeName = typeName self.argumentLabel = name self.name = name self.type = type self.defaultValue = defaultValue self.annotations = annotations self.`inout` = isInout self.isVariadic = isVariadic } public var asSource: String { let typeSuffix = ": \\(`inout` ? "inout " : "")\\(typeName.asSource)\\(defaultValue.map { " = \\($0)" } ?? "")" + (isVariadic ? "..." : "") guard argumentLabel != name else { return name + typeSuffix } let labels = [argumentLabel ?? "_", name.nilIfEmpty] .compactMap { $0 } .joined(separator: " ") return (labels.nilIfEmpty ?? "_") + typeSuffix } // sourcery:inline:MethodParameter.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.argumentLabel = aDecoder.decode(forKey: "argumentLabel") guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.`inout` = aDecoder.decode(forKey: "`inout`") self.isVariadic = aDecoder.decode(forKey: "isVariadic") self.type = aDecoder.decode(forKey: "type") self.defaultValue = aDecoder.decode(forKey: "defaultValue") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.argumentLabel, forKey: "argumentLabel") aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.`inout`, forKey: "`inout`") aCoder.encode(self.isVariadic, forKey: "isVariadic") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.defaultValue, forKey: "defaultValue") aCoder.encode(self.annotations, forKey: "annotations") } // sourcery:end } extension Array where Element == MethodParameter { public var asSource: String { "(\\(map { $0.asSource }.joined(separator: ", ")))" } } // sourcery: skipDiffing @objcMembers public final class ClosureParameter: NSObject, SourceryModel, Typed, Annotated { /// Parameter external name public var argumentLabel: String? /// Parameter internal name public let name: String? /// Parameter type name public let typeName: TypeName /// Parameter flag whether it's inout or not public let `inout`: Bool // sourcery: skipEquality, skipDescription /// Parameter type, if known public var type: Type? /// Parameter type attributes, i.e. `@escaping` public var typeAttributes: AttributeList { return typeName.attributes } /// Method parameter default value expression public var defaultValue: String? /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public var annotations: Annotations = [:] /// :nodoc: public init(argumentLabel: String? = nil, name: String? = nil, typeName: TypeName, type: Type? = nil, defaultValue: String? = nil, annotations: [String: NSObject] = [:], isInout: Bool = false) { self.typeName = typeName self.argumentLabel = argumentLabel self.name = name self.type = type self.defaultValue = defaultValue self.annotations = annotations self.`inout` = isInout } public var asSource: String { let typeInfo = "\\(`inout` ? "inout " : "")\\(typeName.asSource)" if argumentLabel?.nilIfNotValidParameterName == nil, name?.nilIfNotValidParameterName == nil { return typeInfo } let typeSuffix = ": \\(typeInfo)" guard argumentLabel != name else { return name ?? "" + typeSuffix } let labels = [argumentLabel ?? "_", name?.nilIfEmpty] .compactMap { $0 } .joined(separator: " ") return (labels.nilIfEmpty ?? "_") + typeSuffix } // sourcery:inline:ClosureParameter.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.argumentLabel = aDecoder.decode(forKey: "argumentLabel") self.name = aDecoder.decode(forKey: "name") guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.`inout` = aDecoder.decode(forKey: "`inout`") self.type = aDecoder.decode(forKey: "type") self.defaultValue = aDecoder.decode(forKey: "defaultValue") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.argumentLabel, forKey: "argumentLabel") aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.`inout`, forKey: "`inout`") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.defaultValue, forKey: "defaultValue") aCoder.encode(self.annotations, forKey: "annotations") } // sourcery:end } extension Array where Element == ClosureParameter { public var asSource: String { "(\\(map { $0.asSource }.joined(separator: ", ")))" } } /// Describes method @objc(SwiftMethod) @objcMembers public final class Method: NSObject, SourceryModel, Annotated, Documented, Definition { /// Full method name, including generic constraints, i.e. `foo<T>(bar: T)` public let name: String /// Method name including arguments names, i.e. `foo(bar:)` public var selectorName: String // sourcery: skipEquality, skipDescription /// Method name without arguments names and parenthesis, i.e. `foo<T>` public var shortName: String { return name.range(of: "(").map({ String(name[..<$0.lowerBound]) }) ?? name } // sourcery: skipEquality, skipDescription /// Method name without arguments names, parenthesis and generic types, i.e. `foo` (can be used to generate code for method call) public var callName: String { return shortName.range(of: "<").map({ String(shortName[..<$0.lowerBound]) }) ?? shortName } /// Method parameters public var parameters: [MethodParameter] /// Return value type name used in declaration, including generic constraints, i.e. `where T: Equatable` public var returnTypeName: TypeName // sourcery: skipEquality, skipDescription /// Actual return value type name if declaration uses typealias, otherwise just a `returnTypeName` public var actualReturnTypeName: TypeName { return returnTypeName.actualTypeName ?? returnTypeName } // sourcery: skipEquality, skipDescription /// Actual return value type, if known public var returnType: Type? // sourcery: skipEquality, skipDescription /// Whether return value type is optional public var isOptionalReturnType: Bool { return returnTypeName.isOptional || isFailableInitializer } // sourcery: skipEquality, skipDescription /// Whether return value type is implicitly unwrapped optional public var isImplicitlyUnwrappedOptionalReturnType: Bool { return returnTypeName.isImplicitlyUnwrappedOptional } // sourcery: skipEquality, skipDescription /// Return value type name without attributes and optional type information public var unwrappedReturnTypeName: String { return returnTypeName.unwrappedTypeName } /// Whether method is async method public let isAsync: Bool /// Whether method throws public let `throws`: Bool /// Whether method rethrows public let `rethrows`: Bool /// Method access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let accessLevel: String /// Whether method is a static method public let isStatic: Bool /// Whether method is a class method public let isClass: Bool // sourcery: skipEquality, skipDescription /// Whether method is an initializer public var isInitializer: Bool { return selectorName.hasPrefix("init(") || selectorName == "init" } // sourcery: skipEquality, skipDescription /// Whether method is an deinitializer public var isDeinitializer: Bool { return selectorName == "deinit" } /// Whether method is a failable initializer public let isFailableInitializer: Bool // sourcery: skipEquality, skipDescription /// Whether method is a convenience initializer public var isConvenienceInitializer: Bool { modifiers.contains { $0.name == "convenience" } } // sourcery: skipEquality, skipDescription /// Whether method is required public var isRequired: Bool { modifiers.contains { $0.name == "required" } } // sourcery: skipEquality, skipDescription /// Whether method is final public var isFinal: Bool { modifiers.contains { $0.name == "final" } } // sourcery: skipEquality, skipDescription /// Whether method is mutating public var isMutating: Bool { modifiers.contains { $0.name == "mutating" } } // sourcery: skipEquality, skipDescription /// Whether method is generic public var isGeneric: Bool { shortName.hasSuffix(">") } // sourcery: skipEquality, skipDescription /// Whether method is optional (in an Objective-C protocol) public var isOptional: Bool { modifiers.contains { $0.name == "optional" } } /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public let annotations: Annotations public let documentation: Documentation /// Reference to type name where the method is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc public let definedInTypeName: TypeName? // sourcery: skipEquality, skipDescription /// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName` public var actualDefinedInTypeName: TypeName? { return definedInTypeName?.actualTypeName ?? definedInTypeName } // sourcery: skipEquality, skipDescription /// Reference to actual type where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown public var definedInType: Type? /// Method attributes, i.e. `@discardableResult` public let attributes: AttributeList /// Method modifiers, i.e. `private` public let modifiers: [SourceryModifier] // Underlying parser data, never to be used by anything else // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(name: String, selectorName: String? = nil, parameters: [MethodParameter] = [], returnTypeName: TypeName = TypeName(name: "Void"), isAsync: Bool = false, throws: Bool = false, rethrows: Bool = false, accessLevel: AccessLevel = .internal, isStatic: Bool = false, isClass: Bool = false, isFailableInitializer: Bool = false, attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], definedInTypeName: TypeName? = nil) { self.name = name self.selectorName = selectorName ?? name self.parameters = parameters self.returnTypeName = returnTypeName self.isAsync = isAsync self.throws = `throws` self.rethrows = `rethrows` self.accessLevel = accessLevel.rawValue self.isStatic = isStatic self.isClass = isClass self.isFailableInitializer = isFailableInitializer self.attributes = attributes self.modifiers = modifiers self.annotations = annotations self.documentation = documentation self.definedInTypeName = definedInTypeName } // sourcery:inline:Method.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let selectorName: String = aDecoder.decode(forKey: "selectorName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["selectorName"])); fatalError() }; self.selectorName = selectorName guard let parameters: [MethodParameter] = aDecoder.decode(forKey: "parameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["parameters"])); fatalError() }; self.parameters = parameters guard let returnTypeName: TypeName = aDecoder.decode(forKey: "returnTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["returnTypeName"])); fatalError() }; self.returnTypeName = returnTypeName self.returnType = aDecoder.decode(forKey: "returnType") self.isAsync = aDecoder.decode(forKey: "isAsync") self.`throws` = aDecoder.decode(forKey: "`throws`") self.`rethrows` = aDecoder.decode(forKey: "`rethrows`") guard let accessLevel: String = aDecoder.decode(forKey: "accessLevel") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["accessLevel"])); fatalError() }; self.accessLevel = accessLevel self.isStatic = aDecoder.decode(forKey: "isStatic") self.isClass = aDecoder.decode(forKey: "isClass") self.isFailableInitializer = aDecoder.decode(forKey: "isFailableInitializer") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation self.definedInTypeName = aDecoder.decode(forKey: "definedInTypeName") self.definedInType = aDecoder.decode(forKey: "definedInType") guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.selectorName, forKey: "selectorName") aCoder.encode(self.parameters, forKey: "parameters") aCoder.encode(self.returnTypeName, forKey: "returnTypeName") aCoder.encode(self.returnType, forKey: "returnType") aCoder.encode(self.isAsync, forKey: "isAsync") aCoder.encode(self.`throws`, forKey: "`throws`") aCoder.encode(self.`rethrows`, forKey: "`rethrows`") aCoder.encode(self.accessLevel, forKey: "accessLevel") aCoder.encode(self.isStatic, forKey: "isStatic") aCoder.encode(self.isClass, forKey: "isClass") aCoder.encode(self.isFailableInitializer, forKey: "isFailableInitializer") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.definedInTypeName, forKey: "definedInTypeName") aCoder.encode(self.definedInType, forKey: "definedInType") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") } // sourcery:end } """), .init(name: "Modifier.swift", content: """ import Foundation public typealias SourceryModifier = Modifier /// modifier can be thing like `private`, `class`, `nonmutating` /// if a declaration has modifier like `private(set)` it's name will be `private` and detail will be `set` @objcMembers public class Modifier: NSObject, AutoCoding, AutoEquatable, AutoDiffable, AutoJSExport { /// The declaration modifier name. public let name: String /// The modifier detail, if any. public let detail: String? public init(name: String, detail: String? = nil) { self.name = name self.detail = detail } public var asSource: String { if let detail = detail { return "\\(name)(\\(detail))" } else { return name } } // sourcery:inline:Modifier.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name self.detail = aDecoder.decode(forKey: "detail") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.detail, forKey: "detail") } // sourcery:end } """), .init(name: "PhantomProtocols.swift", content: """ // // Created by Krzysztof Zablocki on 23/01/2017. // Copyright (c) 2017 Pixle. All rights reserved. // import Foundation /// Phantom protocol for diffing protocol AutoDiffable {} /// Phantom protocol for equality protocol AutoEquatable {} /// Phantom protocol for equality protocol AutoDescription {} /// Phantom protocol for NSCoding protocol AutoCoding {} protocol AutoJSExport {} /// Phantom protocol for NSCoding, Equatable and Diffable protocol SourceryModelWithoutDescription: AutoDiffable, AutoEquatable, AutoCoding, AutoJSExport {} protocol SourceryModel: SourceryModelWithoutDescription, AutoDescription {} """), .init(name: "Protocol.swift", content: """ // // Protocol.swift // Sourcery // // Created by Krzysztof Zablocki on 09/12/2016. // Copyright © 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: public typealias SourceryProtocol = Protocol /// Describes Swift protocol @objcMembers public final class Protocol: Type { /// Returns "protocol" public override var kind: String { return "protocol" } /// list of all declared associated types with their names as keys public var associatedTypes: [String: AssociatedType] { didSet { isGeneric = !associatedTypes.isEmpty || !genericRequirements.isEmpty } } /// list of generic requirements public var genericRequirements: [GenericRequirement] { didSet { isGeneric = !associatedTypes.isEmpty || !genericRequirements.isEmpty } } /// :nodoc: public init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], associatedTypes: [String: AssociatedType] = [:], genericRequirements: [GenericRequirement] = [], attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = []) { self.genericRequirements = genericRequirements self.associatedTypes = associatedTypes super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, subscripts: subscripts, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, attributes: attributes, modifiers: modifiers, annotations: annotations, documentation: documentation, isGeneric: !associatedTypes.isEmpty || !genericRequirements.isEmpty ) } // sourcery:inline:Protocol.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let associatedTypes: [String: AssociatedType] = aDecoder.decode(forKey: "associatedTypes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["associatedTypes"])); fatalError() }; self.associatedTypes = associatedTypes guard let genericRequirements: [GenericRequirement] = aDecoder.decode(forKey: "genericRequirements") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["genericRequirements"])); fatalError() }; self.genericRequirements = genericRequirements super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.associatedTypes, forKey: "associatedTypes") aCoder.encode(self.genericRequirements, forKey: "genericRequirements") } // sourcery:end } """), .init(name: "ProtocolComposition.swift", content: """ // Created by eric_horacek on 2/12/20. // Copyright © 2020 Airbnb Inc. All rights reserved. import Foundation // sourcery: skipJSExport /// Describes a Swift [protocol composition](https://docs.swift.org/swift-book/ReferenceManual/Types.html#ID454). @objcMembers public final class ProtocolComposition: Type { /// Returns "protocolComposition" public override var kind: String { return "protocolComposition" } /// The names of the types composed to form this composition public let composedTypeNames: [TypeName] // sourcery: skipEquality, skipDescription /// The types composed to form this composition, if known public var composedTypes: [Type]? /// :nodoc: public init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: AttributeList = [:], annotations: [String: NSObject] = [:], isGeneric: Bool = false, composedTypeNames: [TypeName] = [], composedTypes: [Type]? = nil) { self.composedTypeNames = composedTypeNames self.composedTypes = composedTypes super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, subscripts: subscripts, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, annotations: annotations, isGeneric: isGeneric ) } // sourcery:inline:ProtocolComposition.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let composedTypeNames: [TypeName] = aDecoder.decode(forKey: "composedTypeNames") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["composedTypeNames"])); fatalError() }; self.composedTypeNames = composedTypeNames self.composedTypes = aDecoder.decode(forKey: "composedTypes") super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.composedTypeNames, forKey: "composedTypeNames") aCoder.encode(self.composedTypes, forKey: "composedTypes") } // sourcery:end } """), .init(name: "Struct.swift", content: """ // // Struct.swift // Sourcery // // Created by Krzysztof Zablocki on 13/09/2016. // Copyright © 2016 Pixle. All rights reserved. // import Foundation // sourcery: skipDescription /// Describes Swift struct @objcMembers public final class Struct: Type { /// Returns "struct" public override var kind: String { return "struct" } /// :nodoc: public override init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], isGeneric: Bool = false) { super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, subscripts: subscripts, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, attributes: attributes, modifiers: modifiers, annotations: annotations, documentation: documentation, isGeneric: isGeneric ) } // sourcery:inline:Struct.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) } // sourcery:end } """), .init(name: "Subscript.swift", content: """ import Foundation /// Describes subscript @objcMembers public final class Subscript: NSObject, SourceryModel, Annotated, Documented, Definition { /// Method parameters public var parameters: [MethodParameter] /// Return value type name used in declaration, including generic constraints, i.e. `where T: Equatable` public var returnTypeName: TypeName /// Actual return value type name if declaration uses typealias, otherwise just a `returnTypeName` public var actualReturnTypeName: TypeName { return returnTypeName.actualTypeName ?? returnTypeName } // sourcery: skipEquality, skipDescription /// Actual return value type, if known public var returnType: Type? // sourcery: skipEquality, skipDescription /// Whether return value type is optional public var isOptionalReturnType: Bool { return returnTypeName.isOptional } // sourcery: skipEquality, skipDescription /// Whether return value type is implicitly unwrapped optional public var isImplicitlyUnwrappedOptionalReturnType: Bool { return returnTypeName.isImplicitlyUnwrappedOptional } // sourcery: skipEquality, skipDescription /// Return value type name without attributes and optional type information public var unwrappedReturnTypeName: String { return returnTypeName.unwrappedTypeName } /// Whether method is final public var isFinal: Bool { modifiers.contains { $0.name == "final" } } /// Variable read access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let readAccess: String /// Variable write access, i.e. `internal`, `private`, `fileprivate`, `public`, `open`. /// For immutable variables this value is empty string public var writeAccess: String /// Whether variable is mutable or not public var isMutable: Bool { return writeAccess != AccessLevel.none.rawValue } /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public let annotations: Annotations public let documentation: Documentation /// Reference to type name where the method is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc public let definedInTypeName: TypeName? /// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName` public var actualDefinedInTypeName: TypeName? { return definedInTypeName?.actualTypeName ?? definedInTypeName } // sourcery: skipEquality, skipDescription /// Reference to actual type where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown public var definedInType: Type? /// Method attributes, i.e. `@discardableResult` public let attributes: AttributeList /// Method modifiers, i.e. `private` public let modifiers: [SourceryModifier] // Underlying parser data, never to be used by anything else // sourcery: skipEquality, skipDescription, skipCoding, skipJSExport /// :nodoc: public var __parserData: Any? /// :nodoc: public init(parameters: [MethodParameter] = [], returnTypeName: TypeName, accessLevel: (read: AccessLevel, write: AccessLevel) = (.internal, .internal), attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], definedInTypeName: TypeName? = nil) { self.parameters = parameters self.returnTypeName = returnTypeName self.readAccess = accessLevel.read.rawValue self.writeAccess = accessLevel.write.rawValue self.attributes = attributes self.modifiers = modifiers self.annotations = annotations self.documentation = documentation self.definedInTypeName = definedInTypeName } // sourcery:inline:Subscript.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let parameters: [MethodParameter] = aDecoder.decode(forKey: "parameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["parameters"])); fatalError() }; self.parameters = parameters guard let returnTypeName: TypeName = aDecoder.decode(forKey: "returnTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["returnTypeName"])); fatalError() }; self.returnTypeName = returnTypeName self.returnType = aDecoder.decode(forKey: "returnType") guard let readAccess: String = aDecoder.decode(forKey: "readAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["readAccess"])); fatalError() }; self.readAccess = readAccess guard let writeAccess: String = aDecoder.decode(forKey: "writeAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["writeAccess"])); fatalError() }; self.writeAccess = writeAccess guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation self.definedInTypeName = aDecoder.decode(forKey: "definedInTypeName") self.definedInType = aDecoder.decode(forKey: "definedInType") guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.parameters, forKey: "parameters") aCoder.encode(self.returnTypeName, forKey: "returnTypeName") aCoder.encode(self.returnType, forKey: "returnType") aCoder.encode(self.readAccess, forKey: "readAccess") aCoder.encode(self.writeAccess, forKey: "writeAccess") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.definedInTypeName, forKey: "definedInTypeName") aCoder.encode(self.definedInType, forKey: "definedInType") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") } // sourcery:end } """), .init(name: "TemplateContext.swift", content: """ // // Created by Krzysztof Zablocki on 31/12/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: // sourcery: skipCoding @objcMembers public final class TemplateContext: NSObject, SourceryModel, NSCoding { // sourcery: skipJSExport public let parserResult: FileParserResult? public let functions: [SourceryMethod] public let types: Types public let argument: [String: NSObject] // sourcery: skipDescription public var type: [String: Type] { return types.typesByName } public init(parserResult: FileParserResult?, types: Types, functions: [SourceryMethod], arguments: [String: NSObject]) { self.parserResult = parserResult self.types = types self.functions = functions self.argument = arguments } /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let parserResult: FileParserResult = aDecoder.decode(forKey: "parserResult") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found. FileParserResults are required for template context that needs persisting.", arguments: getVaList(["parserResult"])); fatalError() } guard let argument: [String: NSObject] = aDecoder.decode(forKey: "argument") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["argument"])); fatalError() } // if we want to support multiple cycles of encode / decode we need deep copy because composer changes reference types let fileParserResultCopy: FileParserResult? = nil // fileParserResultCopy = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(NSKeyedArchiver.archivedData(withRootObject: parserResult)) as? FileParserResult let composed = Composer.uniqueTypesAndFunctions(parserResult) self.types = .init(types: composed.types, typealiases: composed.typealiases) self.functions = composed.functions self.parserResult = fileParserResultCopy self.argument = argument } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.parserResult, forKey: "parserResult") aCoder.encode(self.argument, forKey: "argument") } public var stencilContext: [String: Any] { return [ "types": types, "functions": functions, "type": types.typesByName, "argument": argument ] } // sourcery: skipDescription, skipEquality public var jsContext: [String: Any] { return [ "types": [ "all": types.all, "protocols": types.protocols, "classes": types.classes, "structs": types.structs, "enums": types.enums, "extensions": types.extensions, "based": types.based, "inheriting": types.inheriting, "implementing": types.implementing ], "functions": functions, "type": types.typesByName, "argument": argument ] } } extension ProcessInfo { /// :nodoc: public var context: TemplateContext! { return NSKeyedUnarchiver.unarchiveObject(withFile: arguments[1]) as? TemplateContext } } // sourcery: skipJSExport /// Collection of scanned types for accessing in templates @objcMembers public final class Types: NSObject, SourceryModel { /// :nodoc: public let types: [Type] /// All known typealiases public let typealiases: [Typealias] /// :nodoc: public init(types: [Type], typealiases: [Typealias] = []) { self.types = types self.typealiases = typealiases } // sourcery:inline:Types.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let types: [Type] = aDecoder.decode(forKey: "types") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["types"])); fatalError() }; self.types = types guard let typealiases: [Typealias] = aDecoder.decode(forKey: "typealiases") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typealiases"])); fatalError() }; self.typealiases = typealiases } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.types, forKey: "types") aCoder.encode(self.typealiases, forKey: "typealiases") } // sourcery:end // sourcery: skipDescription, skipEquality, skipCoding /// :nodoc: public lazy internal(set) var typesByName: [String: Type] = { var typesByName = [String: Type]() self.types.forEach { typesByName[$0.globalName] = $0 } return typesByName }() // sourcery: skipDescription, skipEquality, skipCoding /// :nodoc: public lazy internal(set) var typesaliasesByName: [String: Typealias] = { var typesaliasesByName = [String: Typealias]() self.typealiases.forEach { typesaliasesByName[$0.name] = $0 } return typesaliasesByName }() // sourcery: skipDescription, skipEquality, skipCoding /// All known types, excluding protocols or protocol compositions. public lazy internal(set) var all: [Type] = { return self.types.filter { !($0 is Protocol || $0 is ProtocolComposition) } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known protocols public lazy internal(set) var protocols: [Protocol] = { return self.types.compactMap { $0 as? Protocol } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known protocol compositions public lazy internal(set) var protocolCompositions: [ProtocolComposition] = { return self.types.compactMap { $0 as? ProtocolComposition } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known classes public lazy internal(set) var classes: [Class] = { return self.all.compactMap { $0 as? Class } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known structs public lazy internal(set) var structs: [Struct] = { return self.all.compactMap { $0 as? Struct } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known enums public lazy internal(set) var enums: [Enum] = { return self.all.compactMap { $0 as? Enum } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known extensions public lazy internal(set) var extensions: [Type] = { return self.all.compactMap { $0.isExtension ? $0 : nil } }() // sourcery: skipDescription, skipEquality, skipCoding /// Types based on any other type, grouped by its name, even if they are not known. /// `types.based.MyType` returns list of types based on `MyType` public lazy internal(set) var based: TypesCollection = { TypesCollection( types: self.types, collection: { Array($0.based.keys) } ) }() // sourcery: skipDescription, skipEquality, skipCoding /// Classes inheriting from any known class, grouped by its name. /// `types.inheriting.MyClass` returns list of types inheriting from `MyClass` public lazy internal(set) var inheriting: TypesCollection = { TypesCollection( types: self.types, collection: { Array($0.inherits.keys) }, validate: { type in guard type is Class else { throw "\\(type.name) is not a class and should be used with `implementing` or `based`" } }) }() // sourcery: skipDescription, skipEquality, skipCoding /// Types implementing known protocol, grouped by its name. /// `types.implementing.MyProtocol` returns list of types implementing `MyProtocol` public lazy internal(set) var implementing: TypesCollection = { TypesCollection( types: self.types, collection: { Array($0.implements.keys) }, validate: { type in guard type is Protocol else { throw "\\(type.name) is a class and should be used with `inheriting` or `based`" } }) }() } /// :nodoc: @objcMembers public class TypesCollection: NSObject, AutoJSExport { // sourcery:begin: skipJSExport let all: [Type] let types: [String: [Type]] let validate: ((Type) throws -> Void)? // sourcery:end init(types: [Type], collection: (Type) -> [String], validate: ((Type) throws -> Void)? = nil) { self.all = types var content = [String: [Type]]() self.all.forEach { type in collection(type).forEach { name in var list = content[name] ?? [Type]() list.append(type) content[name] = list } } self.types = content self.validate = validate } public func types(forKey key: String) throws -> [Type] { // In some configurations, the types are keyed by "ModuleName.TypeName" var longKey: String? if let validate = validate { guard let type = all.first(where: { $0.name == key }) else { throw "Unknown type \\(key), should be used with `based`" } try validate(type) if let module = type.module { longKey = [module, type.name].joined(separator: ".") } } // If we find the types directly, return them if let types = types[key] { return types } // if we find a types for the longKey, return them if let longKey = longKey, let types = types[longKey] { return types } return [] } /// :nodoc: public override func value(forKey key: String) -> Any? { do { return try types(forKey: key) } catch { Log.error(error) return nil } } /// :nodoc: public subscript(_ key: String) -> [Type] { do { return try types(forKey: key) } catch { Log.error(error) return [] } } public override func responds(to aSelector: Selector!) -> Bool { return true } } """), .init(name: "Tuple.swift", content: """ import Foundation /// Describes tuple type @objcMembers public final class TupleType: NSObject, SourceryModel { /// Type name used in declaration public var name: String /// Tuple elements public var elements: [TupleElement] /// :nodoc: public init(name: String, elements: [TupleElement]) { self.name = name self.elements = elements } /// :nodoc: public init(elements: [TupleElement]) { self.name = elements.asSource self.elements = elements } // sourcery:inline:TupleType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let elements: [TupleElement] = aDecoder.decode(forKey: "elements") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["elements"])); fatalError() }; self.elements = elements } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.elements, forKey: "elements") } // sourcery:end } /// Describes tuple type element @objcMembers public final class TupleElement: NSObject, SourceryModel, Typed { /// Tuple element name public let name: String? /// Tuple element type name public var typeName: TypeName // sourcery: skipEquality, skipDescription /// Tuple element type, if known public var type: Type? /// :nodoc: public init(name: String? = nil, typeName: TypeName, type: Type? = nil) { self.name = name self.typeName = typeName self.type = type } public var asSource: String { // swiftlint:disable:next force_unwrapping "\\(name != nil ? "\\(name!): " : "")\\(typeName.asSource)" } // sourcery:inline:TupleElement.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.name = aDecoder.decode(forKey: "name") guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") } // sourcery:end } extension Array where Element == TupleElement { public var asSource: String { "(\\(map { $0.asSource }.joined(separator: ", ")))" } public var asTypeName: String { "(\\(map { $0.typeName.asSource }.joined(separator: ", ")))" } } """), .init(name: "Type.swift", content: """ // // Created by Krzysztof Zablocki on 11/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: public typealias AttributeList = [String: [Attribute]] /// Defines Swift type @objcMembers public class Type: NSObject, SourceryModel, Annotated, Documented { /// :nodoc: public var module: String? /// Imports that existed in the file that contained this type declaration public var imports: [Import] = [] // sourcery: skipEquality /// Imports existed in all files containing this type and all its super classes/protocols public var allImports: [Import] { return self.unique({ $0.gatherAllImports() }, filter: { $0 == $1 }) } private func gatherAllImports() -> [Import] { var allImports: [Import] = Array(self.imports) self.basedTypes.values.forEach { (basedType) in allImports.append(contentsOf: basedType.imports) } return allImports } // All local typealiases // sourcery: skipJSExport /// :nodoc: public var typealiases: [String: Typealias] { didSet { typealiases.values.forEach { $0.parent = self } } } // sourcery: skipJSExport /// Whether declaration is an extension of some type public var isExtension: Bool // sourcery: forceEquality /// Kind of type declaration, i.e. `enum`, `struct`, `class`, `protocol` or `extension` public var kind: String { return isExtension ? "extension" : "unknown" } /// Type access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let accessLevel: String /// Type name in global scope. For inner types includes the name of its containing type, i.e. `Type.Inner` public var name: String { guard let parentName = parent?.name else { return localName } return "\\(parentName).\\(localName)" } // sourcery: skipCoding /// Whether the type has been resolved as unknown extension public var isUnknownExtension: Bool = false // sourcery: skipDescription /// Global type name including module name, unless it's an extension of unknown type public var globalName: String { guard let module = module, !isUnknownExtension else { return name } return "\\(module).\\(name)" } /// Whether type is generic public var isGeneric: Bool /// Type name in its own scope. public var localName: String // sourcery: skipEquality, skipDescription /// Variables defined in this type only, inluding variables defined in its extensions, /// but not including variables inherited from superclasses (for classes only) and protocols public var variables: [Variable] { unique({ $0.rawVariables }, filter: Self.uniqueVariableFilter) } /// Unfiltered (can contain duplications from extensions) variables defined in this type only, inluding variables defined in its extensions, /// but not including variables inherited from superclasses (for classes only) and protocols public var rawVariables: [Variable] // sourcery: skipEquality, skipDescription /// All variables defined for this type, including variables defined in extensions, /// in superclasses (for classes only) and protocols public var allVariables: [Variable] { return flattenAll({ return $0.variables }, isExtension: { $0.definedInType?.isExtension == true }, filter: { all, extracted in !all.contains(where: { Self.uniqueVariableFilter($0, rhs: extracted) }) }) } private static func uniqueVariableFilter(_ lhs: Variable, rhs: Variable) -> Bool { return lhs.name == rhs.name && lhs.isStatic == rhs.isStatic && lhs.typeName == rhs.typeName } // sourcery: skipEquality, skipDescription /// Methods defined in this type only, inluding methods defined in its extensions, /// but not including methods inherited from superclasses (for classes only) and protocols public var methods: [Method] { unique({ $0.rawMethods }, filter: Self.uniqueMethodFilter) } /// Unfiltered (can contain duplications from extensions) methods defined in this type only, inluding methods defined in its extensions, /// but not including methods inherited from superclasses (for classes only) and protocols public var rawMethods: [Method] // sourcery: skipEquality, skipDescription /// All methods defined for this type, including methods defined in extensions, /// in superclasses (for classes only) and protocols public var allMethods: [Method] { return flattenAll({ $0.methods }, isExtension: { $0.definedInType?.isExtension == true }, filter: { all, extracted in !all.contains(where: { Self.uniqueMethodFilter($0, rhs: extracted) }) }) } private static func uniqueMethodFilter(_ lhs: Method, rhs: Method) -> Bool { return lhs.name == rhs.name && lhs.isStatic == rhs.isStatic && lhs.isClass == rhs.isClass && lhs.actualReturnTypeName == rhs.actualReturnTypeName } // sourcery: skipEquality, skipDescription /// Subscripts defined in this type only, inluding subscripts defined in its extensions, /// but not including subscripts inherited from superclasses (for classes only) and protocols public var subscripts: [Subscript] { unique({ $0.rawSubscripts }, filter: Self.uniqueSubscriptFilter) } /// Unfiltered (can contain duplications from extensions) Subscripts defined in this type only, inluding subscripts defined in its extensions, /// but not including subscripts inherited from superclasses (for classes only) and protocols public var rawSubscripts: [Subscript] // sourcery: skipEquality, skipDescription /// All subscripts defined for this type, including subscripts defined in extensions, /// in superclasses (for classes only) and protocols public var allSubscripts: [Subscript] { return flattenAll({ $0.subscripts }, isExtension: { $0.definedInType?.isExtension == true }, filter: { all, extracted in !all.contains(where: { Self.uniqueSubscriptFilter($0, rhs: extracted) }) }) } private static func uniqueSubscriptFilter(_ lhs: Subscript, rhs: Subscript) -> Bool { return lhs.parameters == rhs.parameters && lhs.returnTypeName == rhs.returnTypeName && lhs.readAccess == rhs.readAccess && lhs.writeAccess == rhs.writeAccess } // sourcery: skipEquality, skipDescription, skipJSExport /// Bytes position of the body of this type in its declaration file if available. public var bodyBytesRange: BytesRange? // sourcery: skipEquality, skipDescription, skipJSExport /// Bytes position of the whole declaration of this type in its declaration file if available. public var completeDeclarationRange: BytesRange? private func flattenAll<T>(_ extraction: @escaping (Type) -> [T], isExtension: (T) -> Bool, filter: ([T], T) -> Bool) -> [T] { let all = NSMutableOrderedSet() let allObjects = extraction(self) /// The order of importance for properties is: /// Base class /// Inheritance /// Protocol conformance /// Extension var extensions = [T]() var baseObjects = [T]() allObjects.forEach { if isExtension($0) { extensions.append($0) } else { baseObjects.append($0) } } all.addObjects(from: baseObjects) func filteredExtraction(_ target: Type) -> [T] { // swiftlint:disable:next force_cast let all = all.array as! [T] let extracted = extraction(target).filter({ filter(all, $0) }) return extracted } inherits.values.sorted(by: { $0.name < $1.name }).forEach { all.addObjects(from: filteredExtraction($0)) } implements.values.sorted(by: { $0.name < $1.name }).forEach { all.addObjects(from: filteredExtraction($0)) } // swiftlint:disable:next force_cast let array = all.array as! [T] all.addObjects(from: extensions.filter({ filter(array, $0) })) return all.array.compactMap { $0 as? T } } private func unique<T>(_ extraction: @escaping (Type) -> [T], filter: (T, T) -> Bool) -> [T] { let all = NSMutableOrderedSet() for nextItem in extraction(self) { // swiftlint:disable:next force_cast if !all.contains(where: { filter($0 as! T, nextItem) }) { all.add(nextItem) } } return all.array.compactMap { $0 as? T } } /// All initializers defined in this type public var initializers: [Method] { return methods.filter { $0.isInitializer } } /// All annotations for this type public var annotations: Annotations = [:] public var documentation: Documentation = [] /// Static variables defined in this type public var staticVariables: [Variable] { return variables.filter { $0.isStatic } } /// Static methods defined in this type public var staticMethods: [Method] { return methods.filter { $0.isStatic } } /// Class methods defined in this type public var classMethods: [Method] { return methods.filter { $0.isClass } } /// Instance variables defined in this type public var instanceVariables: [Variable] { return variables.filter { !$0.isStatic } } /// Instance methods defined in this type public var instanceMethods: [Method] { return methods.filter { !$0.isStatic && !$0.isClass } } /// Computed instance variables defined in this type public var computedVariables: [Variable] { return variables.filter { $0.isComputed && !$0.isStatic } } /// Stored instance variables defined in this type public var storedVariables: [Variable] { return variables.filter { !$0.isComputed && !$0.isStatic } } /// Names of types this type inherits from (for classes only) and protocols it implements, in order of definition public var inheritedTypes: [String] { didSet { based.removeAll() inheritedTypes.forEach { name in self.based[name] = name } } } // sourcery: skipEquality, skipDescription /// Names of types or protocols this type inherits from, including unknown (not scanned) types public var based = [String: String]() // sourcery: skipEquality, skipDescription /// Types this type inherits from or implements, including unknown (not scanned) types with extensions defined public var basedTypes = [String: Type]() /// Types this type inherits from public var inherits = [String: Type]() // sourcery: skipEquality, skipDescription /// Protocols this type implements public var implements = [String: Type]() /// Contained types public var containedTypes: [Type] { didSet { containedTypes.forEach { containedType[$0.localName] = $0 $0.parent = self } } } // sourcery: skipEquality, skipDescription /// Contained types groupd by their names public private(set) var containedType: [String: Type] = [:] /// Name of parent type (for contained types only) public private(set) var parentName: String? // sourcery: skipEquality, skipDescription /// Parent type, if known (for contained types only) public var parent: Type? { didSet { parentName = parent?.name } } // sourcery: skipJSExport /// :nodoc: public var parentTypes: AnyIterator<Type> { var next: Type? = self return AnyIterator { next = next?.parent return next } } // sourcery: skipEquality, skipDescription /// Superclass type, if known (only for classes) public var supertype: Type? /// Type attributes, i.e. `@objc` public var attributes: AttributeList /// Type modifiers, i.e. `private`, `final` public var modifiers: [SourceryModifier] /// Path to file where the type is defined // sourcery: skipDescription, skipEquality, skipJSExport public var path: String? { didSet { if let path = path { fileName = (path as NSString).lastPathComponent } } } /// Directory to file where the type is defined // sourcery: skipDescription, skipEquality, skipJSExport public var directory: String? { get { return (path as? NSString)?.deletingLastPathComponent } } /// File name where the type was defined public var fileName: String? /// :nodoc: public init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], isGeneric: Bool = false) { self.localName = name self.accessLevel = accessLevel.rawValue self.isExtension = isExtension self.rawVariables = variables self.rawMethods = methods self.rawSubscripts = subscripts self.inheritedTypes = inheritedTypes self.containedTypes = containedTypes self.typealiases = [:] self.parent = parent self.parentName = parent?.name self.attributes = attributes self.modifiers = modifiers self.annotations = annotations self.documentation = documentation self.isGeneric = isGeneric super.init() containedTypes.forEach { containedType[$0.localName] = $0 $0.parent = self } inheritedTypes.forEach { name in self.based[name] = name } typealiases.forEach({ $0.parent = self self.typealiases[$0.aliasName] = $0 }) } /// :nodoc: public func extend(_ type: Type) { type.annotations.forEach { self.annotations[$0.key] = $0.value } type.inherits.forEach { self.inherits[$0.key] = $0.value } type.implements.forEach { self.implements[$0.key] = $0.value } self.inheritedTypes += type.inheritedTypes self.containedTypes += type.containedTypes self.rawVariables += type.rawVariables self.rawMethods += type.rawMethods self.rawSubscripts += type.rawSubscripts } // sourcery:inline:Type.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.module = aDecoder.decode(forKey: "module") guard let imports: [Import] = aDecoder.decode(forKey: "imports") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["imports"])); fatalError() }; self.imports = imports guard let typealiases: [String: Typealias] = aDecoder.decode(forKey: "typealiases") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typealiases"])); fatalError() }; self.typealiases = typealiases self.isExtension = aDecoder.decode(forKey: "isExtension") guard let accessLevel: String = aDecoder.decode(forKey: "accessLevel") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["accessLevel"])); fatalError() }; self.accessLevel = accessLevel self.isGeneric = aDecoder.decode(forKey: "isGeneric") guard let localName: String = aDecoder.decode(forKey: "localName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["localName"])); fatalError() }; self.localName = localName guard let rawVariables: [Variable] = aDecoder.decode(forKey: "rawVariables") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["rawVariables"])); fatalError() }; self.rawVariables = rawVariables guard let rawMethods: [Method] = aDecoder.decode(forKey: "rawMethods") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["rawMethods"])); fatalError() }; self.rawMethods = rawMethods guard let rawSubscripts: [Subscript] = aDecoder.decode(forKey: "rawSubscripts") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["rawSubscripts"])); fatalError() }; self.rawSubscripts = rawSubscripts self.bodyBytesRange = aDecoder.decode(forKey: "bodyBytesRange") self.completeDeclarationRange = aDecoder.decode(forKey: "completeDeclarationRange") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation guard let inheritedTypes: [String] = aDecoder.decode(forKey: "inheritedTypes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inheritedTypes"])); fatalError() }; self.inheritedTypes = inheritedTypes guard let based: [String: String] = aDecoder.decode(forKey: "based") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["based"])); fatalError() }; self.based = based guard let basedTypes: [String: Type] = aDecoder.decode(forKey: "basedTypes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["basedTypes"])); fatalError() }; self.basedTypes = basedTypes guard let inherits: [String: Type] = aDecoder.decode(forKey: "inherits") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inherits"])); fatalError() }; self.inherits = inherits guard let implements: [String: Type] = aDecoder.decode(forKey: "implements") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["implements"])); fatalError() }; self.implements = implements guard let containedTypes: [Type] = aDecoder.decode(forKey: "containedTypes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["containedTypes"])); fatalError() }; self.containedTypes = containedTypes guard let containedType: [String: Type] = aDecoder.decode(forKey: "containedType") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["containedType"])); fatalError() }; self.containedType = containedType self.parentName = aDecoder.decode(forKey: "parentName") self.parent = aDecoder.decode(forKey: "parent") self.supertype = aDecoder.decode(forKey: "supertype") guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers self.path = aDecoder.decode(forKey: "path") self.fileName = aDecoder.decode(forKey: "fileName") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.module, forKey: "module") aCoder.encode(self.imports, forKey: "imports") aCoder.encode(self.typealiases, forKey: "typealiases") aCoder.encode(self.isExtension, forKey: "isExtension") aCoder.encode(self.accessLevel, forKey: "accessLevel") aCoder.encode(self.isGeneric, forKey: "isGeneric") aCoder.encode(self.localName, forKey: "localName") aCoder.encode(self.rawVariables, forKey: "rawVariables") aCoder.encode(self.rawMethods, forKey: "rawMethods") aCoder.encode(self.rawSubscripts, forKey: "rawSubscripts") aCoder.encode(self.bodyBytesRange, forKey: "bodyBytesRange") aCoder.encode(self.completeDeclarationRange, forKey: "completeDeclarationRange") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.inheritedTypes, forKey: "inheritedTypes") aCoder.encode(self.based, forKey: "based") aCoder.encode(self.basedTypes, forKey: "basedTypes") aCoder.encode(self.inherits, forKey: "inherits") aCoder.encode(self.implements, forKey: "implements") aCoder.encode(self.containedTypes, forKey: "containedTypes") aCoder.encode(self.containedType, forKey: "containedType") aCoder.encode(self.parentName, forKey: "parentName") aCoder.encode(self.parent, forKey: "parent") aCoder.encode(self.supertype, forKey: "supertype") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") aCoder.encode(self.path, forKey: "path") aCoder.encode(self.fileName, forKey: "fileName") } // sourcery:end } extension Type { // sourcery: skipDescription, skipJSExport /// :nodoc: var isClass: Bool { let isNotClass = self is Struct || self is Enum || self is Protocol return !isNotClass && !isExtension } } /// Extends type so that inner types can be accessed via KVC e.g. Parent.Inner.Children extension Type { /// :nodoc: override public func value(forUndefinedKey key: String) -> Any? { if let innerType = containedTypes.lazy.filter({ $0.localName == key }).first { return innerType } return super.value(forUndefinedKey: key) } } """), .init(name: "TypeName.swift", content: """ // // Created by Krzysztof Zabłocki on 25/12/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// Describes name of the type used in typed declaration (variable, method parameter or return value etc.) @objcMembers public final class TypeName: NSObject, SourceryModelWithoutDescription, LosslessStringConvertible { /// :nodoc: public init(name: String, actualTypeName: TypeName? = nil, unwrappedTypeName: String? = nil, attributes: AttributeList = [:], isOptional: Bool = false, isImplicitlyUnwrappedOptional: Bool = false, tuple: TupleType? = nil, array: ArrayType? = nil, dictionary: DictionaryType? = nil, closure: ClosureType? = nil, generic: GenericType? = nil, isProtocolComposition: Bool = false) { let optionalSuffix: String // TODO: TBR if !name.hasPrefix("Optional<") && !name.contains(" where ") { if isOptional { optionalSuffix = "?" } else if isImplicitlyUnwrappedOptional { optionalSuffix = "!" } else { optionalSuffix = "" } } else { optionalSuffix = "" } self.name = name + optionalSuffix self.actualTypeName = actualTypeName self.unwrappedTypeName = unwrappedTypeName ?? name self.tuple = tuple self.array = array self.dictionary = dictionary self.closure = closure self.generic = generic self.isOptional = isOptional || isImplicitlyUnwrappedOptional self.isImplicitlyUnwrappedOptional = isImplicitlyUnwrappedOptional self.isProtocolComposition = isProtocolComposition self.attributes = attributes self.modifiers = [] super.init() } /// Type name used in declaration public var name: String /// The generics of this TypeName public var generic: GenericType? /// Whether this TypeName is generic public var isGeneric: Bool { actualTypeName?.generic != nil || generic != nil } /// Whether this TypeName is protocol composition public var isProtocolComposition: Bool // sourcery: skipEquality /// Actual type name if given type name is a typealias public var actualTypeName: TypeName? /// Type name attributes, i.e. `@escaping` public var attributes: AttributeList /// Modifiers, i.e. `escaping` public var modifiers: [SourceryModifier] // sourcery: skipEquality /// Whether type is optional public let isOptional: Bool // sourcery: skipEquality /// Whether type is implicitly unwrapped optional public let isImplicitlyUnwrappedOptional: Bool // sourcery: skipEquality /// Type name without attributes and optional type information public var unwrappedTypeName: String // sourcery: skipEquality /// Whether type is void (`Void` or `()`) public var isVoid: Bool { return name == "Void" || name == "()" || unwrappedTypeName == "Void" } /// Whether type is a tuple public var isTuple: Bool { actualTypeName?.tuple != nil || tuple != nil } /// Tuple type data public var tuple: TupleType? /// Whether type is an array public var isArray: Bool { actualTypeName?.array != nil || array != nil } /// Array type data public var array: ArrayType? /// Whether type is a dictionary public var isDictionary: Bool { actualTypeName?.dictionary != nil || dictionary != nil } /// Dictionary type data public var dictionary: DictionaryType? /// Whether type is a closure public var isClosure: Bool { actualTypeName?.closure != nil || closure != nil } /// Closure type data public var closure: ClosureType? /// Prints typename as it would appear on definition public var asSource: String { // TODO: TBR special treatment let specialTreatment = isOptional && name.hasPrefix("Optional<") var description = ( attributes.flatMap({ $0.value }).map({ $0.asSource }).sorted() + modifiers.map({ $0.asSource }) + [specialTreatment ? name : unwrappedTypeName] ).joined(separator: " ") if let _ = self.dictionary { // array and dictionary cases are covered by the unwrapped type name // description.append(dictionary.asSource) } else if let _ = self.array { // description.append(array.asSource) } else if let _ = self.generic { // let arguments = generic.typeParameters // .map({ $0.typeName.asSource }) // .joined(separator: ", ") // description.append("<\\(arguments)>") } if !specialTreatment { if isImplicitlyUnwrappedOptional { description.append("!") } else if isOptional { description.append("?") } } return description } public override var description: String { ( attributes.flatMap({ $0.value }).map({ $0.asSource }).sorted() + modifiers.map({ $0.asSource }) + [name] ).joined(separator: " ") } // sourcery:inline:TypeName.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name self.generic = aDecoder.decode(forKey: "generic") self.isProtocolComposition = aDecoder.decode(forKey: "isProtocolComposition") self.actualTypeName = aDecoder.decode(forKey: "actualTypeName") guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers self.isOptional = aDecoder.decode(forKey: "isOptional") self.isImplicitlyUnwrappedOptional = aDecoder.decode(forKey: "isImplicitlyUnwrappedOptional") guard let unwrappedTypeName: String = aDecoder.decode(forKey: "unwrappedTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["unwrappedTypeName"])); fatalError() }; self.unwrappedTypeName = unwrappedTypeName self.tuple = aDecoder.decode(forKey: "tuple") self.array = aDecoder.decode(forKey: "array") self.dictionary = aDecoder.decode(forKey: "dictionary") self.closure = aDecoder.decode(forKey: "closure") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.generic, forKey: "generic") aCoder.encode(self.isProtocolComposition, forKey: "isProtocolComposition") aCoder.encode(self.actualTypeName, forKey: "actualTypeName") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") aCoder.encode(self.isOptional, forKey: "isOptional") aCoder.encode(self.isImplicitlyUnwrappedOptional, forKey: "isImplicitlyUnwrappedOptional") aCoder.encode(self.unwrappedTypeName, forKey: "unwrappedTypeName") aCoder.encode(self.tuple, forKey: "tuple") aCoder.encode(self.array, forKey: "array") aCoder.encode(self.dictionary, forKey: "dictionary") aCoder.encode(self.closure, forKey: "closure") } // sourcery:end // sourcery: skipEquality, skipDescription /// :nodoc: public override var debugDescription: String { return name } public convenience init(_ description: String) { self.init(name: description, actualTypeName: nil) } } extension TypeName { public static func unknown(description: String?, attributes: AttributeList = [:]) -> TypeName { if let description = description { Log.astWarning("Unknown type, please add type attribution to \\(description)") } else { Log.astWarning("Unknown type, please add type attribution") } return TypeName(name: "UnknownTypeSoAddTypeAttributionToVariable", attributes: attributes) } } """), .init(name: "Typealias.swift", content: """ import Foundation // sourcery: skipJSExport /// :nodoc: @objcMembers public final class Typealias: NSObject, Typed, SourceryModel { // New typealias name public let aliasName: String // Target name public let typeName: TypeName // sourcery: skipEquality, skipDescription public var type: Type? /// module in which this typealias was declared public var module: String? // sourcery: skipEquality, skipDescription public var parent: Type? { didSet { parentName = parent?.name } } /// Type access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let accessLevel: String var parentName: String? public var name: String { if let parentName = parent?.name { return "\\(module != nil ? "\\(module!)." : "")\\(parentName).\\(aliasName)" } else { return "\\(module != nil ? "\\(module!)." : "")\\(aliasName)" } } public init(aliasName: String = "", typeName: TypeName, accessLevel: AccessLevel = .internal, parent: Type? = nil, module: String? = nil) { self.aliasName = aliasName self.typeName = typeName self.accessLevel = accessLevel.rawValue self.parent = parent self.parentName = parent?.name self.module = module } // sourcery:inline:Typealias.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let aliasName: String = aDecoder.decode(forKey: "aliasName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["aliasName"])); fatalError() }; self.aliasName = aliasName guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") self.module = aDecoder.decode(forKey: "module") self.parent = aDecoder.decode(forKey: "parent") guard let accessLevel: String = aDecoder.decode(forKey: "accessLevel") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["accessLevel"])); fatalError() }; self.accessLevel = accessLevel self.parentName = aDecoder.decode(forKey: "parentName") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.aliasName, forKey: "aliasName") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.module, forKey: "module") aCoder.encode(self.parent, forKey: "parent") aCoder.encode(self.accessLevel, forKey: "accessLevel") aCoder.encode(self.parentName, forKey: "parentName") } // sourcery:end } """), .init(name: "Typed.generated.swift", content: """ // Generated using Sourcery 1.9.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable vertical_whitespace extension AssociatedValue { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } extension ClosureParameter { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } extension MethodParameter { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } extension TupleElement { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } extension Typealias { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } extension Variable { /// Whether type is optional. Shorthand for `typeName.isOptional` public var isOptional: Bool { return typeName.isOptional } /// Whether type is implicitly unwrapped optional. Shorthand for `typeName.isImplicitlyUnwrappedOptional` public var isImplicitlyUnwrappedOptional: Bool { return typeName.isImplicitlyUnwrappedOptional } /// Type name without attributes and optional type information. Shorthand for `typeName.unwrappedTypeName` public var unwrappedTypeName: String { return typeName.unwrappedTypeName } /// Actual type name if declaration uses typealias, otherwise just a `typeName`. Shorthand for `typeName.actualTypeName` public var actualTypeName: TypeName? { return typeName.actualTypeName ?? typeName } /// Whether type is a tuple. Shorthand for `typeName.isTuple` public var isTuple: Bool { return typeName.isTuple } /// Whether type is a closure. Shorthand for `typeName.isClosure` public var isClosure: Bool { return typeName.isClosure } /// Whether type is an array. Shorthand for `typeName.isArray` public var isArray: Bool { return typeName.isArray } /// Whether type is a dictionary. Shorthand for `typeName.isDictionary` public var isDictionary: Bool { return typeName.isDictionary } } """), .init(name: "Typed.swift", content: """ import Foundation /// Descibes typed declaration, i.e. variable, method parameter, tuple element, enum case associated value public protocol Typed { // sourcery: skipEquality, skipDescription /// Type, if known var type: Type? { get } // sourcery: skipEquality, skipDescription /// Type name var typeName: TypeName { get } // sourcery: skipEquality, skipDescription /// Whether type is optional var isOptional: Bool { get } // sourcery: skipEquality, skipDescription /// Whether type is implicitly unwrapped optional var isImplicitlyUnwrappedOptional: Bool { get } // sourcery: skipEquality, skipDescription /// Type name without attributes and optional type information var unwrappedTypeName: String { get } } """), .init(name: "Variable.swift", content: """ // // Created by Krzysztof Zablocki on 13/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation /// :nodoc: public typealias SourceryVariable = Variable /// Defines variable @objcMembers public final class Variable: NSObject, SourceryModel, Typed, Annotated, Documented, Definition { /// Variable name public let name: String /// Variable type name public let typeName: TypeName // sourcery: skipEquality, skipDescription /// Variable type, if known, i.e. if the type is declared in the scanned sources. /// For explanation, see <https://cdn.rawgit.com/krzysztofzablocki/Sourcery/master/docs/writing-templates.html#what-are-em-known-em-and-em-unknown-em-types> public var type: Type? /// Whether variable is computed and not stored public let isComputed: Bool /// Whether variable is async public let isAsync: Bool /// Whether variable throws public let `throws`: Bool /// Whether variable is static public let isStatic: Bool /// Variable read access level, i.e. `internal`, `private`, `fileprivate`, `public`, `open` public let readAccess: String /// Variable write access, i.e. `internal`, `private`, `fileprivate`, `public`, `open`. /// For immutable variables this value is empty string public let writeAccess: String /// composed access level /// sourcery: skipJSExport public var accessLevel: (read: AccessLevel, write: AccessLevel) { (read: AccessLevel(rawValue: readAccess) ?? .none, AccessLevel(rawValue: writeAccess) ?? .none) } /// Whether variable is mutable or not public var isMutable: Bool { return writeAccess != AccessLevel.none.rawValue } /// Variable default value expression public var defaultValue: String? /// Annotations, that were created with // sourcery: annotation1, other = "annotation value", alterantive = 2 public var annotations: Annotations = [:] public var documentation: Documentation = [] /// Variable attributes, i.e. `@IBOutlet`, `@IBInspectable` public var attributes: AttributeList /// Modifiers, i.e. `private` public var modifiers: [SourceryModifier] /// Whether variable is final or not public var isFinal: Bool { return modifiers.contains { $0.name == "final" } } /// Whether variable is lazy or not public var isLazy: Bool { return modifiers.contains { $0.name == "lazy" } } /// Reference to type name where the variable is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc public internal(set) var definedInTypeName: TypeName? /// Reference to actual type name where the method is defined if declaration uses typealias, otherwise just a `definedInTypeName` public var actualDefinedInTypeName: TypeName? { return definedInTypeName?.actualTypeName ?? definedInTypeName } // sourcery: skipEquality, skipDescription /// Reference to actual type where the object is defined, /// nil if defined outside of any `enum`, `struct`, `class` etc or type is unknown public var definedInType: Type? /// :nodoc: public init(name: String = "", typeName: TypeName, type: Type? = nil, accessLevel: (read: AccessLevel, write: AccessLevel) = (.internal, .internal), isComputed: Bool = false, isAsync: Bool = false, `throws`: Bool = false, isStatic: Bool = false, defaultValue: String? = nil, attributes: AttributeList = [:], modifiers: [SourceryModifier] = [], annotations: [String: NSObject] = [:], documentation: [String] = [], definedInTypeName: TypeName? = nil) { self.name = name self.typeName = typeName self.type = type self.isComputed = isComputed self.isAsync = isAsync self.`throws` = `throws` self.isStatic = isStatic self.defaultValue = defaultValue self.readAccess = accessLevel.read.rawValue self.writeAccess = accessLevel.write.rawValue self.attributes = attributes self.modifiers = modifiers self.annotations = annotations self.documentation = documentation self.definedInTypeName = definedInTypeName } // sourcery:inline:Variable.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") self.isComputed = aDecoder.decode(forKey: "isComputed") self.isAsync = aDecoder.decode(forKey: "isAsync") self.`throws` = aDecoder.decode(forKey: "`throws`") self.isStatic = aDecoder.decode(forKey: "isStatic") guard let readAccess: String = aDecoder.decode(forKey: "readAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["readAccess"])); fatalError() }; self.readAccess = readAccess guard let writeAccess: String = aDecoder.decode(forKey: "writeAccess") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["writeAccess"])); fatalError() }; self.writeAccess = writeAccess self.defaultValue = aDecoder.decode(forKey: "defaultValue") guard let annotations: Annotations = aDecoder.decode(forKey: "annotations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["annotations"])); fatalError() }; self.annotations = annotations guard let documentation: Documentation = aDecoder.decode(forKey: "documentation") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["documentation"])); fatalError() }; self.documentation = documentation guard let attributes: AttributeList = aDecoder.decode(forKey: "attributes") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["attributes"])); fatalError() }; self.attributes = attributes guard let modifiers: [SourceryModifier] = aDecoder.decode(forKey: "modifiers") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiers"])); fatalError() }; self.modifiers = modifiers self.definedInTypeName = aDecoder.decode(forKey: "definedInTypeName") self.definedInType = aDecoder.decode(forKey: "definedInType") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.isComputed, forKey: "isComputed") aCoder.encode(self.isAsync, forKey: "isAsync") aCoder.encode(self.`throws`, forKey: "`throws`") aCoder.encode(self.isStatic, forKey: "isStatic") aCoder.encode(self.readAccess, forKey: "readAccess") aCoder.encode(self.writeAccess, forKey: "writeAccess") aCoder.encode(self.defaultValue, forKey: "defaultValue") aCoder.encode(self.annotations, forKey: "annotations") aCoder.encode(self.documentation, forKey: "documentation") aCoder.encode(self.attributes, forKey: "attributes") aCoder.encode(self.modifiers, forKey: "modifiers") aCoder.encode(self.definedInTypeName, forKey: "definedInTypeName") aCoder.encode(self.definedInType, forKey: "definedInType") } // sourcery:end } """), ]
mit
f782ee9270e8c4773d1f2df40dfaa5ea
41.165242
352
0.641066
4.752073
false
false
false
false
eastbanctech/demo-atm-ios
AppiumATM/ViewController.swift
1
2761
// // ViewController.swift // AppiumATM // // Created by Kirill Butin on 2/3/15. // Copyright (c) 2015 EastBanc Technologies. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var balanceLabel: UILabel! @IBOutlet weak var accountTypePicker: UIPickerView! @IBOutlet weak var amount: UITextField! var balance: [Int]! var accounts: [String]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. accountTypePicker.delegate = self accountTypePicker.dataSource = self accounts = ["Checking account", "Savings account"] balance = [5000, 100] balanceLabel.text = String(balance[0]) } @IBAction func getCashPressed(sender: AnyObject) { if (amount.text.toInt() == nil) { return } // just ignore if nothing in the amount field let currentBallance = balance[accountTypePicker.selectedRowInComponent(0)] - amount.text.toInt()! if (currentBallance >= 0){ balance[accountTypePicker.selectedRowInComponent(0)] = currentBallance balanceLabel.text = String(currentBallance) var alert = UIAlertController(title: nil, message: "Please take your money from the dispenser", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }else{ var alert = UIAlertController(title: "Error", message: "Insufficient funds", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Destructive, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } amount.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 2 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return accounts[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { balanceLabel.text = String(balance[row]) } }
gpl-3.0
dd03683d0777cc41ca74bdf14db835ea
34.857143
153
0.664252
5.066055
false
false
false
false
JNU-Include/Swift-Study
Learning Swift.playground/Pages/Operators.xcplaygroundpage/Contents.swift
1
490
//Binary Operators (+ - / * %) let height = 12.0 let width = 15.0 let area = height * width let areaInSquareMeters = area / 10.764 //a = b //Comparison Operator let string1 = "Hello" let string2 = "Hello" let string3 = "hello" string1 == string2 string1 == string3 string1 != string3 string1 != string2 200 > 150 "a" > "z" "다" > "파" "A" > "a" 2500 < 1600 2 <= 2 //Unary Operator var playerLevel = 0 playerLevel = playerLevel + 1 playerLevel += 1 let on = true let off = !on
apache-2.0
34076597fcfbbe851c836068ca1e2353
11.789474
38
0.635802
2.655738
false
false
false
false
pawel-sp/AppFlowController
iOS-Example/AlphaTransition.swift
1
3057
// // AlphaTransition.swift // iOS-Example // // Created by Paweł Sporysz on 02.10.2016. // Copyright © 2016 Paweł Sporysz. All rights reserved. // import UIKit import AppFlowController class AlphaTransition: NSObject, UIViewControllerAnimatedTransitioning, FlowTransition, UINavigationControllerDelegate { // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } guard let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } let containerView = transitionContext.containerView guard let toView = toVC.view else { return } guard let fromView = fromVC.view else { return } let animationDuration = transitionDuration(using: transitionContext) toView.alpha = 0 containerView.addSubview(toView) UIView.animate(withDuration: animationDuration, animations: { toView.alpha = 1 }) { finished in if (transitionContext.transitionWasCancelled) { toView.removeFromSuperview() } else { fromView.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } // MARK: - FlowTransition func performForwardTransition(animated: Bool, completion: @escaping () -> ()) -> ForwardTransition.ForwardTransitionAction { return { navigationController, viewController in let previousDelegate = navigationController.delegate navigationController.delegate = self navigationController.pushViewController(viewController, animated: animated){ navigationController.delegate = previousDelegate completion() } } } func performBackwardTransition(animated: Bool, completion: @escaping () -> ()) -> BackwardTransition.BackwardTransitionAction { return { viewController in let navigationController = viewController.navigationController let previousDelegate = navigationController?.delegate navigationController?.delegate = self let _ = navigationController?.popViewController(animated: animated) { navigationController?.delegate = previousDelegate completion() } } } // MARK: - UINavigationControllerDelegate func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } }
mit
31eb536579b48ff6a8b17b3d0c8853f8
40.835616
246
0.69057
6.697368
false
false
false
false
RamonGilabert/Walker
Source/Constructors/Spring.swift
1
4242
import UIKit /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ view: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient) -> Void) -> Distillery { let builder = constructor([view], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0]) validate(builder.distillery) return builder.distillery } /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ firstView: UIView, _ secondView: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient, Ingredient) -> Void) -> Distillery { let builder = constructor([firstView, secondView], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0], builder.ingredients[1]) validate(builder.distillery) return builder.distillery } /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ firstView: UIView, _ secondView: UIView, _ thirdView: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring , animations: (Ingredient, Ingredient, Ingredient) -> Void) -> Distillery { let builder = constructor([firstView, secondView, thirdView], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0], builder.ingredients[1], builder.ingredients[2]) validate(builder.distillery) return builder.distillery } @discardableResult private func constructor(_ views: [UIView], _ delay: TimeInterval, _ spring: CGFloat, _ friction: CGFloat, _ mass: CGFloat, _ tolerance: CGFloat, _ calculation: Animation.Spring) -> (ingredients: [Ingredient], distillery: Distillery) { let distillery = Distillery() var ingredients: [Ingredient] = [] views.forEach { ingredients.append(Ingredient(distillery: distillery, view: $0, spring: spring, friction: friction, mass: mass, tolerance: tolerance, calculation: calculation)) } distillery.delays.append(delay) distillery.ingredients = [ingredients] return (ingredients: ingredients, distillery: distillery) } private func validate(_ distillery: Distillery) { var shouldProceed = true distilleries.forEach { if let ingredients = $0.ingredients.first, let ingredient = ingredients.first , ingredient.finalValues.isEmpty { shouldProceed = false return } } distillery.shouldProceed = shouldProceed if shouldProceed { distilleries.append(distillery) distillery.animate() } }
mit
18da306fe854f264c7ef8a5d1a5dde6f
40.588235
155
0.740217
4.293522
false
false
false
false
garvankeeley/firefox-ios
Client/UserResearch/OnboardingUserResearch.swift
1
4537
/* 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 Leanplum import Shared struct LPVariables { // Variable Used for AA test static var showOnboardingScreenAA = LPVar.define("showOnboardingScreen", with: true) // Variable Used for AB test static var showOnboardingScreenAB = LPVar.define("showOnboardingScreen_2", with: true) } // For LP variable below is the convention we follow // True = Current Onboarding Screen // False = New Onboarding Screen enum OnboardingScreenType: String { case versionV1 case versionV2 static func from(boolValue: Bool) -> OnboardingScreenType { return boolValue ? .versionV1 : .versionV2 } } class OnboardingUserResearch { // Closure delegate var updatedLPVariable: (() -> Void)? // variable var lpVariable: LPVar? // Constants private let onboardingScreenTypeKey = "onboardingScreenTypeKey" // Saving user defaults private let defaults = UserDefaults.standard // Publicly accessible onboarding screen type var onboardingScreenType: OnboardingScreenType? { set(value) { if value == nil { defaults.removeObject(forKey: onboardingScreenTypeKey) } else { defaults.set(value?.rawValue, forKey: onboardingScreenTypeKey) } } get { guard let value = defaults.value(forKey: onboardingScreenTypeKey) as? String else { return nil } return OnboardingScreenType(rawValue: value) } } // MARK: Initializer init(lpVariable: LPVar? = LPVariables.showOnboardingScreenAB) { self.lpVariable = lpVariable } // MARK: public func lpVariableObserver() { // Condition: Leanplum is disabled; use default intro view guard LeanPlumClient.shared.getSettings() != nil else { self.onboardingScreenType = .versionV1 self.updatedLPVariable?() return } // Condition: A/B test variables from leanplum server LeanPlumClient.shared.finishedStartingLeanplum = { let showScreenA = LPVariables.showOnboardingScreenAB?.boolValue() LeanPlumClient.shared.finishedStartingLeanplum = nil self.updateTelemetry() let screenType = OnboardingScreenType.from(boolValue: (showScreenA ?? true)) self.onboardingScreenType = screenType self.updatedLPVariable?() } // Condition: Leanplum server too slow; Show default onboarding. DispatchQueue.main.asyncAfter(deadline: .now() + 2) { guard LeanPlumClient.shared.finishedStartingLeanplum != nil else { return } let lpStartStatus = LeanPlumClient.shared.lpState var lpVariableValue: OnboardingScreenType = .versionV1 // Condition: LP has already started but we missed onStartLPVariable callback if case .started(startedState: _) = lpStartStatus , let boolValue = LPVariables.showOnboardingScreenAB?.boolValue() { lpVariableValue = boolValue ? .versionV1 : .versionV2 self.updateTelemetry() } self.updatedLPVariable = nil self.onboardingScreenType = lpVariableValue self.updatedLPVariable?() } } func updateTelemetry() { // Printing variant is good to know all details of A/B test fields print("lp variant \(String(describing: Leanplum.variants()))") guard let variants = Leanplum.variants(), let lpData = variants.first as? Dictionary<String, AnyObject> else { return } var abTestId = "" if let value = lpData["abTestId"] as? Int64 { abTestId = "\(value)" } let abTestName = lpData["abTestName"] as? String ?? "" let abTestVariant = lpData["name"] as? String ?? "" let attributesExtras = [LPAttributeKey.experimentId: abTestId, LPAttributeKey.experimentName: abTestName, LPAttributeKey.experimentVariant: abTestVariant] // Leanplum telemetry LeanPlumClient.shared.set(attributes: attributesExtras) // Legacy telemetry UnifiedTelemetry.recordEvent(category: .enrollment, method: .add, object: .experimentEnrollment, extras: attributesExtras) } }
mpl-2.0
a7902d28547818acee14f715e8614179
39.508929
162
0.648226
5.057971
false
true
false
false
mluedke2/ResearchKit
samples/ORKSample/ORKSample/WithdrawViewController.swift
11
2726
/* Copyright (c) 2015, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import ResearchKit class WithdrawViewController: ORKTaskViewController { // MARK: Initialization init() { let instructionStep = ORKInstructionStep(identifier: "WithdrawlInstruction") instructionStep.title = NSLocalizedString("Are you sure you want to withdraw?", comment: "") instructionStep.text = NSLocalizedString("Withdrawing from the study will reset the app to the state it was in prior to you originally joining the study.", comment: "") let completionStep = ORKCompletionStep(identifier: "Withdraw") completionStep.title = NSLocalizedString("We appreciate your time.", comment: "") completionStep.text = NSLocalizedString("Thank you for your contribution to this study. We are sorry that you could not continue.", comment: "") let withdrawTask = ORKOrderedTask(identifier: "Withdraw", steps: [instructionStep, completionStep]) super.init(task: withdrawTask, taskRun: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-3-clause
f24acfea72067bc059885bcda5cb1e5a
49.481481
176
0.765591
4.992674
false
false
false
false
DanielAsher/SwiftParse
SwiftParse/Playgrounds/Isomorphic Syntax Descriptions.playground/Pages/With Phantom Type.xcplaygroundpage/Contents.swift
1
3591
//: Invertible Syntax Descriptions //: http://www.informatik.uni-marburg.de/~rendel/unparse/rendel10invertible.pdf import Swiftz class Iso<T,U,V> { let to : T -> Optional<U> let from : U -> Optional<T> init(to: T -> Optional<U>, from: U -> Optional<T>) { self.to = to self.from = from } } func • <T,U,V>(c: Iso<U,V,V>, c2: Iso<T,U,V>) -> Iso<T,V,V> { return Iso<T,V,V>( to: { t in c2.to(t).bind(c.to) }, from: { v in c.from(v).bind(c2.from) } ) } func >>> <T,U,V>(c: Iso<T,U,V>, c2:Iso<U,V,V>) -> Iso<T,V,V> { return Iso<T,V,V>( to: { t in c.to(t).bind(c2.to) }, from: { v in c2.from(v).bind(c.from) } ) } func <<< <T,U,V>(c: Iso<U,V,V>, c2:Iso<T,U,V>) -> Iso<T,V,V> { return Iso<T,V,V>( to: { t in c2.to(t).bind(c.to) }, from: { v in c.from(v).bind(c2.from) } ) } extension Iso : Category { typealias A = T typealias B = U typealias C = V typealias CAA = Iso<A,A,C> typealias CBC = Iso<B,C,C> typealias CAC = Iso<A,C,C> static func id() -> Iso<T,T,V> { return Iso<T,T,V>(to: { t in .Some(t) }, from: { t in .Some(t) } ) } } protocol IsoFunctor { typealias A typealias B typealias C typealias FA = K1<A> typealias FB = K1<B> func <^> (iso: Iso<A,B,C>, a: FA) -> FB } func <^> <T,U,V>(iso: Iso<T,U,V>, a: Optional<T>) -> Optional<U> { return a.bind { a in iso.to(a) } } infix operator >^< { associativity left } func >^< <T,U,V>(a: Optional<T>, iso: Iso<T,U,V>) -> Optional<U> { return .None } protocol ProductFunctor { typealias A typealias B typealias FA = K1<A> typealias FB = K1<B> typealias FAB = K1<(A, B)> func <*> (a: FA, b: FB) -> FAB } infix operator <|> { associativity left} protocol Alternative { typealias A typealias FA = K1<A> func <|> (a: FA, b: FA) -> FA static var empty : FA { get } } protocol Syntax : IsoFunctor, ProductFunctor, Alternative { typealias DA = K1<A> typealias DB = K1<B> typealias DLA = K1<[A]> typealias DChar = K1<Character> static func pure(a: A) -> DA static func pureB(a: B) -> DB static var token : DChar {get} func many(p: DA) -> DLA func bind(k: A -> DB) -> DB func map(iso: Iso<A, B, B>, da: DA) -> DB static func aToB(a: A) -> B } //func cons<T,U,V>() -> Iso<T,U,V> { // //} extension Syntax where DA : Syntax, DB : Syntax { var nill : Iso<A,[A],A> { return Iso<A,[A],A> (to: { t in Optional<[A]>.None}, from: { u in Optional<A>.None }) } var cons : Iso<(A,[A]),[A],A> { return Iso<(A,[A]),[A],A>( to: { (x, xs) in [x] + xs }, from: { switch $0.match { case .Nil: return .None case let .Cons(x, xs): return .Some((x, xs)) } } ) } // func bind(da: DA, k: A -> DB) -> DB { // return da // } // func map(iso: Iso<A, B, B>, da: DA) -> DB { // let f : DB = da.bind { a in DB.pureB(DA.aToB(a)) } // return f //// return bind(da) { a in Self.pureB(iso.to(a)) } // } func many(p: DA) -> DLA { let _ = nill <^> .None let _ = { x in Self.pure(x) } // let b = p <*> many(p) return many(p) } } //extension Iso { // func map<T,U,V>(a: Optional<T>) -> Optional<U> { // let t : T = a! // let u : Optional<U> = self.to(t) // return u // } //} print("Finished :)")
mit
ef11d3514320957f3ff78f0a0d9defc1
23.25
94
0.484815
2.672375
false
false
false
false
tsuchikazu/iTunesSwift
ITunesSwift/Entity.swift
1
1035
// // Entity.swift // ITunesSwift // // Created by Kazuyoshi Tsuchiya on 2014/09/21. // Copyright (c) 2014 tsuchikazu. All rights reserved. // public enum Entity: String { case MovieArtist = "movieArtist" case Movie = "movie" case PodcastAuthor = "podcastAuthor" case Podcast = "podcast" case MusicArtist = "musicArtist" case MusicTrack = "musicTrack" case Album = "album" case MusicVideo = "musicVideo" case Mix = "mix" case Song = "song" case AudiobookAuthor = "audiobookAuthor" case Audiobook = "audiobook" case ShortFilmArtist = "shortFilmArtist" case ShortFilm = "shortFilm" case TvEpisode = "tvEpisode" case TvSeason = "tvSeason" case Software = "software" case IPadSoftware = "iPadSoftware" case MacSoftware = "macSoftware" case Ebook = "ebook" case AllArtist = "allArtist" case AllTrack = "allTrack" }
mit
48ee1b61e709f36f8254c84a3780332e
31.375
55
0.582609
3.819188
false
false
false
false
moltin/ios-swift-example
MoltinSwiftExample/MoltinSwiftExample/SwiftSpinner.swift
1
15842
// // Copyright (c) 2015-present Marin Todorov, Underplot ltd. // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit open class SwiftSpinner: UIView { // MARK: - Singleton // // Access the singleton instance // open class var sharedInstance: SwiftSpinner { struct Singleton { static let instance = SwiftSpinner(frame: CGRect.zero) } return Singleton.instance } // MARK: - Init // // Custom init to build the spinner UI // public override init(frame: CGRect) { super.init(frame: frame) blurEffect = UIBlurEffect(style: blurEffectStyle) blurView = UIVisualEffectView(effect: blurEffect) addSubview(blurView) vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) addSubview(vibrancyView) let titleScale: CGFloat = 0.85 titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale) titleLabel.font = defaultTitleFont titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.lineBreakMode = .byWordWrapping titleLabel.adjustsFontSizeToFitWidth = true titleLabel.textColor = UIColor.white blurView.contentView.addSubview(titleLabel) blurView.contentView.addSubview(vibrancyView) outerCircleView.frame.size = frameSize outerCircle.path = UIBezierPath(ovalIn: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).cgPath outerCircle.lineWidth = 8.0 outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 0.45 outerCircle.lineCap = kCALineCapRound outerCircle.fillColor = UIColor.clear.cgColor outerCircle.strokeColor = UIColor.white.cgColor outerCircleView.layer.addSublayer(outerCircle) outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 1.0 blurView.contentView.addSubview(outerCircleView) innerCircleView.frame.size = frameSize let innerCirclePadding: CGFloat = 12 innerCircle.path = UIBezierPath(ovalIn: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).cgPath innerCircle.lineWidth = 4.0 innerCircle.strokeStart = 0.5 innerCircle.strokeEnd = 0.9 innerCircle.lineCap = kCALineCapRound innerCircle.fillColor = UIColor.clear.cgColor innerCircle.strokeColor = UIColor.gray.cgColor innerCircleView.layer.addSublayer(innerCircle) innerCircle.strokeStart = 0.0 innerCircle.strokeEnd = 1.0 blurView.contentView.addSubview(innerCircleView) isUserInteractionEnabled = true } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { return self } // MARK: - Public interface open lazy var titleLabel = UILabel() open var subtitleLabel: UILabel? // // Custom superview for the spinner // fileprivate static weak var customSuperview: UIView? = nil fileprivate static func containerView() -> UIView? { return customSuperview ?? UIApplication.shared.keyWindow } open class func useContainerView(_ sv: UIView?) { customSuperview = sv } // // Show the spinner activity on screen, if visible only update the title // @discardableResult open class func show(_ title: String, animated: Bool = true) -> SwiftSpinner { let spinner = SwiftSpinner.sharedInstance spinner.clearTapHandler() spinner.updateFrame() if spinner.superview == nil { //show the spinner spinner.alpha = 0.0 guard let containerView = containerView() else { fatalError("\n`UIApplication.keyWindow` is `nil`. If you're trying to show a spinner from your view controller's `viewDidLoad` method, do that from `viewWillAppear` instead. Alternatively use `useContainerView` to set a view where the spinner should show") } containerView.addSubview(spinner) UIView.animate(withDuration: 0.33, delay: 0.0, options: .curveEaseOut, animations: { spinner.alpha = 1.0 }, completion: nil) #if os(iOS) // Orientation change observer NotificationCenter.default.addObserver( spinner, selector: #selector(SwiftSpinner.updateFrame), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) #endif } spinner.title = title spinner.animating = animated return spinner } // // Show the spinner activity on screen with duration, if visible only update the title // @discardableResult open class func show(_ duration: Double, title: String, animated: Bool = true) -> SwiftSpinner { let spinner = SwiftSpinner.show(title, animated: animated) spinner.delay(duration) { SwiftSpinner.hide() } return spinner } fileprivate static var delayedTokens = [String]() /// /// Show the spinner with the outer circle representing progress (0 to 1) /// @discardableResult open class func show(_ progress: Double, title: String) -> SwiftSpinner { let spinner = SwiftSpinner.show(title, animated: false) spinner.outerCircle.strokeEnd = CGFloat(progress) return spinner } // // Hide the spinner // open static var hideCancelsScheduledSpinners = true open class func hide(_ completion: (() -> Void)? = nil) { let spinner = SwiftSpinner.sharedInstance NotificationCenter.default.removeObserver(spinner) if hideCancelsScheduledSpinners { delayedTokens.removeAll() } DispatchQueue.main.async(execute: { spinner.clearTapHandler() if spinner.superview == nil { return } UIView.animate(withDuration: 0.33, delay: 0.0, options: .curveEaseOut, animations: { spinner.alpha = 0.0 }, completion: {_ in spinner.alpha = 1.0 spinner.removeFromSuperview() spinner.titleLabel.font = spinner.defaultTitleFont spinner.titleLabel.text = nil completion?() }) spinner.animating = false }) } // // Set the default title font // public class func setTitleFont(_ font: UIFont?) { let spinner = SwiftSpinner.sharedInstance if let font = font { spinner.titleLabel.font = font } else { spinner.titleLabel.font = spinner.defaultTitleFont } } // // The spinner title // public var title: String = "" { didSet { let spinner = SwiftSpinner.sharedInstance guard spinner.animating else { spinner.titleLabel.transform = CGAffineTransform.identity spinner.titleLabel.alpha = 1.0 spinner.titleLabel.text = self.title return } UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut, animations: { spinner.titleLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) spinner.titleLabel.alpha = 0.2 }, completion: {_ in spinner.titleLabel.text = self.title UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: [], animations: { spinner.titleLabel.transform = CGAffineTransform.identity spinner.titleLabel.alpha = 1.0 }, completion: nil) }) } } // // observe the view frame and update the subviews layout // open override var frame: CGRect { didSet { if frame == CGRect.zero { return } blurView.frame = bounds vibrancyView.frame = blurView.bounds titleLabel.center = vibrancyView.center outerCircleView.center = vibrancyView.center innerCircleView.center = vibrancyView.center if let subtitle = subtitleLabel { subtitle.bounds.size = subtitle.sizeThatFits(bounds.insetBy(dx: 20.0, dy: 0.0).size) subtitle.center = CGPoint(x: bounds.midX, y: bounds.maxY - subtitle.bounds.midY - subtitle.font.pointSize) } } } // // Start the spinning animation // public var animating: Bool = false { willSet (shouldAnimate) { if shouldAnimate && !animating { spinInner() spinOuter() } } didSet { // update UI if animating { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 0.45 self.innerCircle.strokeStart = 0.5 self.innerCircle.strokeEnd = 0.9 } else { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 1.0 self.innerCircle.strokeStart = 0.0 self.innerCircle.strokeEnd = 1.0 } } } // // Tap handler // public func addTapHandler(_ tap: @escaping (()->()), subtitle subtitleText: String? = nil) { clearTapHandler() //vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner"))) tapHandler = tap if subtitleText != nil { subtitleLabel = UILabel() if let subtitle = subtitleLabel { subtitle.text = subtitleText subtitle.font = UIFont(name: defaultTitleFont.familyName, size: defaultTitleFont.pointSize * 0.8) subtitle.textColor = UIColor.white subtitle.numberOfLines = 0 subtitle.textAlignment = .center subtitle.lineBreakMode = .byWordWrapping subtitle.bounds.size = subtitle.sizeThatFits(bounds.insetBy(dx: 20.0, dy: 0.0).size) subtitle.center = CGPoint(x: bounds.midX, y: bounds.maxY - subtitle.bounds.midY - subtitle.font.pointSize) vibrancyView.contentView.addSubview(subtitle) } } } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if tapHandler != nil { tapHandler?() tapHandler = nil } } public func clearTapHandler() { isUserInteractionEnabled = false subtitleLabel?.removeFromSuperview() tapHandler = nil } // MARK: - Private interface // // layout elements // fileprivate var blurEffectStyle: UIBlurEffectStyle = .dark fileprivate var blurEffect: UIBlurEffect! fileprivate var blurView: UIVisualEffectView! fileprivate var vibrancyView: UIVisualEffectView! var defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)! let frameSize = CGSize(width: 200.0, height: 200.0) fileprivate lazy var outerCircleView = UIView() fileprivate lazy var innerCircleView = UIView() fileprivate let outerCircle = CAShapeLayer() fileprivate let innerCircle = CAShapeLayer() required public init?(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } fileprivate var currentOuterRotation: CGFloat = 0.0 fileprivate var currentInnerRotation: CGFloat = 0.1 fileprivate func spinOuter() { if superview == nil { return } let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5 let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4 //outer circle UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: { self.currentOuterRotation -= CGFloat(randomRotation) self.outerCircleView.transform = CGAffineTransform(rotationAngle: self.currentOuterRotation) }, completion: {_ in let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0 self.delay(waitDuration, completion: { if self.animating { self.spinOuter() } }) }) } fileprivate func spinInner() { if superview == nil { return } //inner circle UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: { self.currentInnerRotation += CGFloat(M_PI_4) self.innerCircleView.transform = CGAffineTransform(rotationAngle: self.currentInnerRotation) }, completion: {_ in self.delay(0.5, completion: { if self.animating { self.spinInner() } }) }) } public func updateFrame() { if let containerView = SwiftSpinner.containerView() { SwiftSpinner.sharedInstance.frame = containerView.bounds } } // MARK: - Util methods func delay(_ seconds: Double, completion:@escaping ()->()) { let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * seconds )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { completion() } } override open func layoutSubviews() { super.layoutSubviews() updateFrame() } // MARK: - Tap handler fileprivate var tapHandler: (()->())? func didTapSpinner() { tapHandler?() } }
mit
2b8d8d3cea80f27662e0debd8d63a92f
35.334862
463
0.592918
5.35022
false
false
false
false
dklinzh/NodeExtension
NodeExtension/Classes/UIKit/Image.swift
1
5800
// // Image.swift // NodeExtension // // Created by Linzh on 8/20/17. // Copyright (c) 2017 Daniel Lin. All rights reserved. // // MARK: - Line Image extension UIImage { public static func dl_dashedLineImage(size: CGSize, color: UIColor) -> UIImage { let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: size.height / 2)) path.addLine(to: CGPoint(x: size.width, y: size.height / 2)) path.lineWidth = size.height let dashes: [CGFloat] = [4, 4] path.setLineDash(dashes, count: dashes.count, phase: 0) path.lineCapStyle = .butt UIGraphicsBeginImageContextWithOptions(size, false, 0) color.set() path.stroke() let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } public static func dl_dottedLineImage(size: CGSize, color: UIColor) -> UIImage { let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: size.height / 2)) path.addLine(to: CGPoint(x: size.width, y: size.height / 2)) path.lineWidth = size.height let dashes: [CGFloat] = [0, 2] path.setLineDash(dashes, count: dashes.count, phase: 0) path.lineCapStyle = .round UIGraphicsBeginImageContextWithOptions(size, false, 0) color.set() path.stroke() let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } // MARK: - Image Size extension UIImage { /// Make the image circular by 'Precomoposed Alpha Corners' /// /// - Parameters: /// - size: The size of image /// - width: The with of border /// - Returns: An UIImage object public func dl_makeCircularImage(size: CGSize, borderWidth width: CGFloat = 0, borderColor color: UIColor = .white) -> UIImage { // make a CGRect with the image's size let circleRect = CGRect(origin: .zero, size: size) // begin the image context since we're not in a drawRect: UIGraphicsBeginImageContextWithOptions(circleRect.size, false, 0) // create a UIBezierPath circle let circle = UIBezierPath(roundedRect: circleRect, cornerRadius: circleRect.size.width * 0.5) // clip to the circle circle.addClip() UIColor.white.set() circle.fill() // draw the image in the circleRect *AFTER* the context is clipped self.draw(in: circleRect) // create a border (for white background pictures) if width > 0 { circle.lineWidth = width color.set() circle.stroke() } // get an image from the image context let roundedImage = UIGraphicsGetImageFromCurrentImageContext() // end the image context since we're not in a drawRect: UIGraphicsEndImageContext() return roundedImage ?? self } /// Compress the data of image /// /// - Parameters: /// - maxSize: The maximum size(bytes) of image /// - minRatio: The minimum ratio for image compression. (minRatio >= maxRatio) /// - maxRatio: The maximum ratio for image compression. (maxRatio <= minRatio) /// - Returns: The data of image @objc public func dl_jpegCompression(maxSize: Int, minRatio: CGFloat, maxRatio: CGFloat) -> Data { let r = (minRatio - maxRatio) / 10 var ratio = minRatio var imageData = self.jpegData(compressionQuality: 1.0)! while imageData.count > maxSize && ratio > maxRatio { imageData = self.jpegData(compressionQuality: ratio)! ratio -= r } return imageData } public func dl_scale(size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage ?? self } } // MARK: - Image Color extension UIImage { public func dl_gradientTintedImage(tintColor: UIColor) -> UIImage { return self.dl_tintedImage(tintColor: tintColor, blendMode: .overlay) } public func dl_tintedImage(tintColor: UIColor, blendMode: CGBlendMode = .destinationIn) -> UIImage { //Set opaque to false for keepping alpha; Use 0.0 on scale to use the scale factor of the device’s main screen UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) tintColor.setFill() let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) UIRectFill(bounds) // Draw the tinted image in context self.draw(in: bounds, blendMode: blendMode, alpha: 1.0) if blendMode != .destinationIn { self.draw(in: bounds, blendMode: .destinationIn, alpha: 1.0) } let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage ?? self } public func dl_highlightedImage(alpha: CGFloat = 0.7) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) self.draw(in: bounds, blendMode: .normal, alpha: alpha) self.draw(in: bounds, blendMode: .colorBurn, alpha: alpha) let highlightedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return highlightedImage ?? self } }
mit
cc6b286124cd429b7971beee48aa1e21
35.012422
132
0.616592
4.709992
false
false
false
false
GeekerHua/GHSwiftTest
GHPlayground.playground/Pages/06.字符串.xcplaygroundpage/Contents.swift
1
3687
//: [Previous](@previous) import UIKit let d = Double("55") // String 是结构体,效率更高,推荐使用String,支持遍历 var str: String = "\"你好世界\"" for c in str.characters { print(c) } // 字符串拼接 let name: String? = "老王\u{1F425}" let age = 20 let title = "小菜" let rect = CGRect(x: 0, y: 0, width: 100, height: 100) print((name ?? "") + String(age) + title) print("\(name ?? "") \(age) \(title) \(rect)") print("\(name) \(age) \(title) \(rect)") // 字符串字符数量 let testWord = "test 测试" name?.characters.count title.characters.count testWord.characters.count // 添加可扩展字符集 var word = "cafe" print("the number of characters in \(word) is \(word.characters.count)") // 打印输出 "the number of characters in cafe is 4" //word += "\u{301}" // COMBINING ACUTE ACCENT, U+0301 print("the number of characters in \(word) is \(word.characters.count)") // 打印输出 "the number of characters in café is 4” // 真的需要格式转换 let h = 129.000023 let m: Double = 5800 let s = 8 let st = "3.600" let timeSt = String(format: "h = %.01f: m = %.0f st = %.01f", arguments: [h,m/100,NSString(string:st).doubleValue]) let p = NSNumber(double: 148) //let d = String(format: "¥ %.02f", p.doubleValue) print(d) let timeStr = "\(h):\(m):\(s)" let timeStr1 = String(format: "%02d:%02d:%02d", arguments: [h,m,s]) String(format: "%f", arguments: [23.432]) let price: Double = 2.9 String(format:"\(price)") var p3: String? p3 = "33d" Int(p3!) let possibleString: String? = "An optional string." let forcedString: String = possibleString! // 需要惊叹号来获取值 possibleString word.stringByReplacingOccurrencesOfString("fde", withString: "") // 获取字符 word.startIndex word.endIndex word.characters.count //word.removeAtIndex(word.endIndex - Index(1)) // 获取字符串最后一个字符 word[word.startIndex] word[word.endIndex.predecessor()] // 获取字符串指定位置的字符 word[word.startIndex.advancedBy(2)] for index in word.characters.indices { print("\(word[index])") } NSString(string:"532.").doubleValue // Range 变化非常大,碰到Range,最好把String转成NSString // Range 截取字符串目前还不知道谁会写 //str.substringWithRange(3..<4) str str = (str as NSString).substringWithRange(NSMakeRange(1, str.characters.count-2)) str str.substringFromIndex("你好".endIndex) var url = "http://blog.csdn.net/hello_hwc?view?mode=list" var filtered = url.stringByReplacingOccurrencesOfString("?", withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil) let text = "珍贵的“北美红宝石”<br /> <br />蔓越莓也称小红莓,因果实小且生长在低矮密实的枝蔓上而难以手工采摘,通常要靠引水灌田,再用机械打落使其漂浮,方可收集。每到蔓越莓成熟的10月,各产区的“蔓越莓节”陆续登场,不仅展示了蔓越莓独具特色的采收方式,还提供了各种蔓越莓制作的食物,吸引着天南地北的游客。<br /><br />食用方法<br />1.直接食用<br />2.制作蔓越莓干面包,糕点,饼干,果汁等" text.stringByReplacingOccurrencesOfString("<br />", withString: "\n", options: NSStringCompareOptions.LiteralSearch, range: nil) //: [Next](@next) // 去掉url中的没用字符 let u = "\t\nhttp://static.tongshijia.com/images/index/2016/06/03/4bb0ac2e-293b-11e6-b8d8-00163e1600b6.jpg\r\n" let t = "sdfsdf:" t.rangeOfString("\n") //let u: String? = nil let set = NSCharacterSet.whitespaceAndNewlineCharacterSet() let result = u.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) print(result)
mit
9d1267b3672b329e4cb2f7f570d922a7
24.733333
219
0.706282
2.678231
false
false
false
false
ReactorKit/ReactorKit
Sources/ReactorKit/StoryboardView.swift
1
1626
import RxSwift #if !os(Linux) #if os(iOS) || os(tvOS) import UIKit private typealias OSViewController = UIViewController #elseif os(macOS) import AppKit private typealias OSViewController = NSViewController #endif import WeakMapTable private typealias AnyView = AnyObject private enum MapTables { static let reactor = WeakMapTable<AnyView, Any>() static let isReactorBinded = WeakMapTable<AnyView, Bool>() } public protocol _ObjCStoryboardView { func performBinding() } public protocol StoryboardView: View, _ObjCStoryboardView {} extension StoryboardView { public var reactor: Reactor? { get { MapTables.reactor.value(forKey: self) as? Reactor } set { MapTables.reactor.setValue(newValue, forKey: self) isReactorBinded = false disposeBag = DisposeBag() performBinding() } } fileprivate var isReactorBinded: Bool { get { MapTables.isReactorBinded.value(forKey: self, default: false) } set { MapTables.isReactorBinded.setValue(newValue, forKey: self) } } public func performBinding() { guard let reactor = reactor else { return } guard !isReactorBinded else { return } guard !shouldDeferBinding(reactor: reactor) else { return } bind(reactor: reactor) isReactorBinded = true } fileprivate func shouldDeferBinding(reactor: Reactor) -> Bool { #if !os(watchOS) return (self as? OSViewController)?.isViewLoaded == false #else return false #endif } } #if !os(watchOS) extension OSViewController { @objc func _reactorkit_performBinding() { (self as? _ObjCStoryboardView)?.performBinding() } } #endif #endif
mit
08c248a9c5435592e96b88828706203d
23.268657
73
0.718327
3.889952
false
false
false
false
gabek/GitYourFeedback
Example/Pods/GRMustache.swift/Sources/Tag.swift
3
5545
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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: - TagType /// The type of a tag, variable or section. See the documentation of `Tag` for /// more information. public enum TagType { /// The type of tags such as `{{name}}` and `{{{body}}}`. case variable /// The type of section tags such as `{{#user}}...{{/user}}`. case section } // ============================================================================= // MARK: - Tag /// Tag instances represent Mustache tags that render values: /// /// - variable tags: `{{name}}` and `{{{body}}}` /// - section tags: `{{#user}}...{{/user}}` /// /// You may meet the Tag class when you implement your own `RenderFunction`, /// `WillRenderFunction` or `DidRenderFunction`, or filters that perform custom /// rendering (see `FilterFunction`). /// /// - seealso: RenderFunction /// - seealso: WillRenderFunction /// - seealso: DidRenderFunction public protocol Tag: class, CustomStringConvertible { // IMPLEMENTATION NOTE // // Tag is a class-only protocol so that the Swift compiler does not crash // when compiling the `tag` property of RenderingInfo. /// The type of the tag: variable or section: /// /// let render: RenderFunction = { (info: RenderingInfo) in /// switch info.tag.type { /// case .variable: /// return Rendering("variable") /// case .section: /// return Rendering("section") /// } /// } /// /// let template = try! Template(string: "{{object}}, {{#object}}...{{/object}}") /// /// // Renders "variable, section" /// try! template.render(["object": Box(render)]) var type: TagType { get } /// The literal and unprocessed inner content of the tag. /// /// A section tag such as `{{# person }}Hello {{ name }}!{{/ person }}` /// returns "Hello {{ name }}!". /// /// Variable tags such as `{{ name }}` have no inner content: their inner /// template string is the empty string. /// /// // {{# pluralize(count) }}...{{/ }} renders the plural form of the section /// // content if the `count` argument is greater than 1. /// let pluralize = Filter { (count: Int?, info: RenderingInfo) in /// /// // Pluralize the inner content of the section tag: /// var string = info.tag.innerTemplateString /// if let count = count, count > 1 { /// string += "s" // naive /// } /// /// return Rendering(string) /// } /// /// let template = try! Template(string: "I have {{ cats.count }} {{# pluralize(cats.count) }}cat{{/ }}.") /// template.register(pluralize, forKey: "pluralize") /// /// // Renders "I have 3 cats." /// let data = ["cats": ["Kitty", "Pussy", "Melba"]] /// try! template.render(data) var innerTemplateString: String { get } /// The delimiters of the tag. var tagDelimiterPair: TagDelimiterPair { get } /// Returns the rendering of the tag's inner content. All inner tags are /// evaluated with the provided context. /// /// This method does not return a String, but a Rendering value that wraps /// both the rendered string and its content type (HTML or Text). /// /// The contentType is HTML, unless specified otherwise by `Configuration`, /// or a `{{% CONTENT_TYPE:TEXT }}` pragma tag. /// /// // The strong RenderFunction below wraps a section in a <strong> HTML tag. /// let strong: RenderFunction = { (info: RenderingInfo) -> Rendering in /// let rendering = try info.tag.render(info.context) /// return Rendering("<strong>\(rendering.string)</strong>", .html) /// } /// /// let template = try! Template(string: "{{#strong}}Hello {{name}}{{/strong}}") /// template.register(strong, forKey: "strong") /// /// // Renders "<strong>Hello Arthur</strong>" /// try! template.render(["name": Box("Arthur")]) /// /// - parameter context: The context stack for evaluating mustache tags. /// - throws: An eventual rendering error. /// - returns: The rendering of the tag. func render(_ context: Context) throws -> Rendering }
mit
cde32db99f1e395ed7541e72ba112604
39.173913
114
0.59127
4.492707
false
false
false
false
Josscii/iOS-Demos
DynamicLabelsDemo/DynamicLabelsDemo/ViewController.swift
1
1233
// // ViewController.swift // DynamicLabelsDemo // // Created by Josscii on 2017/8/7. // Copyright © 2017年 Josscii. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let v = DynamicLabelsView() v.translatesAutoresizingMaskIntoConstraints = false view.addSubview(v) v.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true v.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true v.widthAnchor.constraint(equalToConstant: 200).isActive = true var strings: [String] = [] strings.append("哈哈,我觉得你说得太对了!") strings.append("当前版本暂不支持查看此消息,请在手机上查看。") strings.append("厉害") strings.append("不行吧") strings.append("得了吧你") v.setup(with: strings) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3aeb4f5d86bf5afd30307fff93fc51c3
26.190476
80
0.642732
4.342205
false
false
false
false