repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jlandon/Alexandria
Sources/Alexandria/UIGestureRecognizer+Extensions.swift
1
2876
// // UIGestureRecognizer+Extensions.swift // // Created by hsoi on 4/13/15. // // Extending UIGestureRecognizer -- at first, to add support for a block-based action instead of traditional target/action. // // Created by Hsoi, Swift-ized by JLandon. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension UIGestureRecognizer { private class GestureAction { var action: (UIGestureRecognizer) -> Void init(action: @escaping (UIGestureRecognizer) -> Void) { self.action = action } } private struct AssociatedKeys { static var ActionName = "action" } private var gestureAction: GestureAction? { set { objc_setAssociatedObject(self, &AssociatedKeys.ActionName, newValue, .OBJC_ASSOCIATION_RETAIN) } get { return objc_getAssociatedObject(self, &AssociatedKeys.ActionName) as? GestureAction } } /** Convenience initializer, associating an action closure with the gesture recognizer (instead of the more traditional target/action). - parameter action: The closure for the recognizer to execute. There is no pre-logic to conditionally invoke the closure or not (e.g. only invoke the closure if the gesture recognizer is in a particular state). The closure is merely invoked directly; all handler logic is up to the closure. - returns: The UIGestureRecognizer. */ public convenience init(action: @escaping (UIGestureRecognizer) -> Void) { self.init() gestureAction = GestureAction(action: action) addTarget(self, action: #selector(handleAction(_:))) } @objc dynamic private func handleAction(_ recognizer: UIGestureRecognizer) { gestureAction?.action(recognizer) } }
mit
lennet/tiny-planet
TinyPlanetUITests/TinyPlanetMacUITests.swift
1
1265
// // TinyPlanetMacUITests.swift // TinyPlanetMacUITests // // Created by Leo Thomas on 17.05.17. // Copyright © 2017 Leonard Thomas. All rights reserved. // import XCTest class TinyPlanetMacUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
GhostSK/SpriteKitPractice
FightSceneDemo/FightSceneDemo/MagicBaseModel.swift
1
1129
// // MagicBaseModel.swift // FightSceneDemo // // Created by 胡杨林 on 17/3/7. // Copyright © 2017年 胡杨林. All rights reserved. // import Foundation class MagicBaseModel: NSObject { public var MagicName:String? = nil public var MagicCategory:String? = nil //单体/群体/辅助/dot/虚弱/加速等分类 public var MagicTargets:[UnitNode]? = nil //作用对象,可能为群体 public var Buff1:String? = nil //持续效果1 public var Buff1KeepTime:NSInteger = 0 //buff1持续时间 public var buff2:String? = nil public var buff2KeepTime:NSInteger = 0 public var buff3:String? = nil public var buff3KeepTime:NSInteger = 0 public var directEffectValue:NSInteger = 0 //翔舞首跳/直接效果 public var indirectEffectValue:NSInteger = 0 //翔舞每一跳 public var endEffectValue:NSInteger = 0 //上元结束跳 init(Name:String, MagicCategory:String, directEffect:NSInteger) { super.init() self.MagicName = Name self.MagicCategory = MagicCategory self.directEffectValue = directEffect } }
apache-2.0
calebkleveter/UIWebKit
Sources/UIWebKit/Components/UIParagraph.swift
1
1931
// The MIT License (MIT) // // Copyright (c) 2017 Caleb Kleveter // // 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. /// `UIParagraph` is a wrapper class around a `p` HTML tag which is represented by a `UIElement`. open class UIParagraph { /// The `p` element that is represented by the object. public let p = UIElement(element: .p) /// The text held in the `p` element. public var text: String { didSet { self.p.add(self.text) } } /// Creates a `UIParagraph` with the desired text. /// /// - Parameter text: The text used in the objects `p` element. public init(text: String) { self.text = text self.p.add(text) } } extension UIParagraph: ElementRenderable { /// The top level `p` element of the `UIParagraph`. public var topLevelElement: UIElement { return p } }
mit
wenghengcong/Coderpursue
BeeFun/BeeFun/Model/Network/ObjError.swift
1
559
// // ObjErrorMessage.swift // BeeFun // // Created by WengHengcong on 3/8/16. // Copyright © 2016 JungleSong. All rights reserved. // import UIKit import ObjectMapper /* { "resource": "Search", "field": "q", "code": "missing" } */ class ObjError: NSObject, Mappable { var resource: String? var field: String? var code: String? required init?(map: Map) { } func mapping(map: Map) { // super.mapping(map) resource <- map["resource"] field <- map["field"] code <- map["code"] } }
mit
shohei/firefox-ios
UITests/ReaderViewUITests.swift
2
4594
/* 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 WebKit class ReaderViewUITests: KIFTestCase, UITextFieldDelegate { private var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } /** * Tests reader view UI with reader optimized content */ func testReaderViewUI() { loadReaderContent() addToReadingList() markAsReadFromReaderView() markAsUnreadFromReaderView() markAsReadFromReadingList() markAsUnreadFromReadingList() removeFromReadingList() addToReadingList() removeFromReadingListInView() } func loadReaderContent() { tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/readerContent.html" tester().clearTextFromAndThenEnterText("\(url)\n", intoViewWithAccessibilityLabel: "Address and Search") tester().tapViewWithAccessibilityLabel("Reader Mode") } func addToReadingList() { tester().tapViewWithAccessibilityLabel("Add to Reading List") tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().waitForViewWithAccessibilityLabel("Reader View Test") // TODO: Check for rows in this table tester().tapViewWithAccessibilityLabel("Cancel") } func markAsReadFromReaderView() { tester().tapViewWithAccessibilityLabel("Mark as Read") tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().swipeViewWithAccessibilityLabel("Reader View Test", inDirection: KIFSwipeDirection.Right) tester().waitForViewWithAccessibilityLabel("Mark as Unread") tester().tapViewWithAccessibilityLabel("Cancel") } func markAsUnreadFromReaderView() { tester().tapViewWithAccessibilityLabel("Mark as Unread") tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().swipeViewWithAccessibilityLabel("Reader View Test", inDirection: KIFSwipeDirection.Right) tester().waitForViewWithAccessibilityLabel("Mark as Read") tester().tapViewWithAccessibilityLabel("Cancel") } func markAsReadFromReadingList() { tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().swipeViewWithAccessibilityLabel("Reader View Test", inDirection: KIFSwipeDirection.Right) tester().tapViewWithAccessibilityLabel("Mark as Read") tester().tapViewWithAccessibilityLabel("Cancel") tester().waitForViewWithAccessibilityLabel("Mark as Unread") } func markAsUnreadFromReadingList() { tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().swipeViewWithAccessibilityLabel("Reader View Test", inDirection: KIFSwipeDirection.Right) tester().tapViewWithAccessibilityLabel("Mark as Unread") tester().tapViewWithAccessibilityLabel("Cancel") tester().waitForViewWithAccessibilityLabel("Mark as Read") } func removeFromReadingList() { tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().swipeViewWithAccessibilityLabel("Reader View Test", inDirection: KIFSwipeDirection.Left) tester().tapViewWithAccessibilityLabel("Remove") tester().waitForAbsenceOfViewWithAccessibilityLabel("Reader View Test") tester().tapViewWithAccessibilityLabel("Cancel") tester().waitForViewWithAccessibilityLabel("Add to Reading List") } func removeFromReadingListInView() { tester().tapViewWithAccessibilityLabel("Remove from Reading List") tester().waitForViewWithAccessibilityLabel("Add to Reading List") tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") // TODO: Check for rows in this table tester().tapViewWithAccessibilityLabel("Cancel") tester().waitForViewWithAccessibilityLabel("Add to Reading List") } // TODO: Add a reader view display settings test override func tearDown() { BrowserUtils.resetToAboutHome(tester()) } }
mpl-2.0
akaralar/siesta
Source/Siesta/Support/Regex+Siesta.swift
3
1136
// // Regex.swift // Siesta // // Created by Paul on 2015/7/8. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation internal extension String { func contains(regex: String) -> Bool { return range(of: regex, options: .regularExpression) != nil } func replacing(regex: String, with replacement: String) -> String { return replacingOccurrences( of: regex, with: replacement, options: .regularExpression, range: nil) } func replacing(regex: NSRegularExpression, with template: String) -> String { return regex.stringByReplacingMatches(in: self, options: [], range: fullRange, withTemplate: template) } fileprivate var fullRange: NSRange { return NSRange(location: 0, length: (self as NSString).length) } } internal extension NSRegularExpression { func matches(_ string: String) -> Bool { let match = firstMatch(in: string, options: [], range: string.fullRange) return match != nil && match?.range.location != NSNotFound } }
mit
mvader/advent-of-code
2021/08/02.swift
1
1766
import Foundation extension StringProtocol { subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] } } struct Entry { let patterns: [String] let output: [String] init(_ raw: String) { let parts = raw.components(separatedBy: " | ") patterns = parts.first!.split(separator: " ").map { String($0) } output = parts.last!.split(separator: " ").map { String($0) } } func guessDigits() throws -> [String: Int] { let one = patterns.filter { $0.count == 2 }.first! let four = patterns.filter { $0.count == 4 }.first! let patterns = [String: Int](uniqueKeysWithValues: try patterns.map { p in let pattern = String(p.sorted()) switch p.count { case 2: return (pattern, 1) case 3: return (pattern, 7) case 4: return (pattern, 4) case 7: return (pattern, 8) case 5: if one.allSatisfy({ pattern.contains($0) }) { return (pattern, 3) } if four.filter({ pattern.contains($0) }).count == 3 { return (pattern, 5) } return (pattern, 2) case 6: if four.allSatisfy({ pattern.contains($0) }) { return (pattern, 9) } if one.allSatisfy({ pattern.contains($0) }) { return (pattern, 0) } return (pattern, 6) default: throw GuessError.invalidPattern } }) return patterns } func decode() throws -> Int { let digits = try guessDigits() return Int(output.reduce("") { acc, e in acc + String(digits[String(e.sorted())]!) })! } } enum GuessError: Error { case invalidPattern } let entries = try String(contentsOfFile: "./input.txt", encoding: .utf8) .split(separator: "\n") .map { line in Entry(String(line)) } let targetDigits = [2, 3, 4, 7] let result = try entries.reduce(0) { acc, e in acc + (try e.decode()) } print(result)
mit
jacobwhite/firefox-ios
Storage/SQL/SQLiteFavicons.swift
1
3063
/* 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 Deferred import Shared open class SQLiteFavicons { let db: BrowserDB required public init(db: BrowserDB) { self.db = db } public func getFaviconIDQuery(url: String) -> (sql: String, args: Args?) { var args: Args = [] args.append(url) return (sql: "SELECT id FROM favicons WHERE url = ? LIMIT 1", args: args) } public func getInsertFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args: Args = [] args.append(favicon.url) args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) return (sql: "INSERT INTO favicons (url, width, height, type, date) VALUES (?,?,?,0,?)", args: args) } public func getUpdateFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) { var args = Args() args.append(favicon.width) args.append(favicon.height) args.append(favicon.date) args.append(favicon.url) return (sql: "UPDATE favicons SET width = ?, height = ?, date = ? WHERE url = ?", args: args) } public func getCleanupFaviconsQuery() -> (sql: String, args: Args?) { let sql = """ DELETE FROM favicons WHERE favicons.id NOT IN ( SELECT faviconID FROM favicon_sites UNION ALL SELECT faviconID FROM bookmarksLocal WHERE faviconID IS NOT NULL UNION ALL SELECT faviconID FROM bookmarksMirror WHERE faviconID IS NOT NULL ) """ return (sql: sql, args: nil) } public func insertOrUpdateFavicon(_ favicon: Favicon) -> Deferred<Maybe<Int>> { return db.withConnection { conn -> Int in self.insertOrUpdateFaviconInTransaction(favicon, conn: conn) ?? 0 } } func insertOrUpdateFaviconInTransaction(_ favicon: Favicon, conn: SQLiteDBConnection) -> Int? { let query = self.getFaviconIDQuery(url: favicon.url) let cursor = conn.executeQuery(query.sql, factory: IntFactory, withArgs: query.args) if let id = cursor[0] { let updateQuery = self.getUpdateFaviconQuery(favicon: favicon) do { try conn.executeChange(updateQuery.sql, withArgs: updateQuery.args) } catch { return nil } return id } let insertQuery = self.getInsertFaviconQuery(favicon: favicon) do { try conn.executeChange(insertQuery.sql, withArgs: insertQuery.args) } catch { return nil } return conn.lastInsertedRowID } public func cleanupFavicons() -> Success { return self.db.run([getCleanupFaviconsQuery()]) } }
mpl-2.0
ewanmellor/KZLinkedConsole
KZLinkedConsole/Extensions/NSTextView+Extensions.swift
1
4566
// // Created by Krzysztof Zabłocki on 05/12/15. // Copyright (c) 2015 pixle. All rights reserved. // import Foundation import AppKit extension NSTextView { func kz_mouseDown(event: NSEvent) { let pos = convertPoint(event.locationInWindow, fromView:nil) let idx = characterIndexForInsertionAtPoint(pos) guard let expectedClass = NSClassFromString("IDEConsoleTextView") where isKindOfClass(expectedClass) && attributedString().length > 1 && idx < attributedString().length else { kz_mouseDown(event) return } let attr = attributedString().attributesAtIndex(idx, effectiveRange: nil) guard let fileName = attr[KZLinkedConsole.Strings.linkedFileName] as? String, let lineNumber = attr[KZLinkedConsole.Strings.linkedLine] as? String, let appDelegate = NSApplication.sharedApplication().delegate else { kz_mouseDown(event) return } guard let workspacePath = KZPluginHelper.workspacePath() else { return } guard let filePath = kz_findFile(workspacePath, fileName) else { return } if appDelegate.application!(NSApplication.sharedApplication(), openFile: filePath) { dispatch_async(dispatch_get_main_queue()) { if let textView = KZPluginHelper.editorTextView(inWindow: self.window), let line = Int(lineNumber) where line >= 1 { self.scrollTextView(textView, toLine:line) } } } } private func scrollTextView(textView: NSTextView, toLine line: Int) { guard let text = (textView.string as NSString?) else { return } var currentLine = 1 var index = 0 for (; index < text.length; currentLine++) { let lineRange = text.lineRangeForRange(NSMakeRange(index, 0)) index = NSMaxRange(lineRange) if currentLine == line { textView.scrollRangeToVisible(lineRange) textView.setSelectedRange(lineRange) break } } } } /** [workspacePath : [fileName : filePath]] */ var kz_filePathCache = [String : [String : String]]() /** Search for the given filename in the given workspace. To avoid parsing the project's header file inclusion path, we use the following heuristic: 1. Look in kz_filePathCache. 2. Look for the file in the current workspace. 3. Look in the parent directory of the current workspace, excluding the current workspace because we've already searched there. 4. Keep recursing upwards, but stop if we have gone more than 2 levels up or we have reached /foo/bar. The assumption here is that /foo/bar would actually be /Users/username and searching the developer's entire home directory is likely to be too expensive. Similarly, if the project is in some subdirectory heirarchy, then if we are three levels up then that search is likely to be large and too expensive also. */ func kz_findFile(workspacePath : String, _ fileName : String) -> String? { var thisWorkspaceCache = kz_filePathCache[workspacePath] ?? [:] if let result = thisWorkspaceCache[fileName] { if NSFileManager.defaultManager().fileExistsAtPath(result) { return result } } var searchPath = workspacePath var prevSearchPath : String? = nil var searchCount = 0 while true { let result = kz_findFile(fileName, searchPath, prevSearchPath) if result != nil && !result!.isEmpty { thisWorkspaceCache[fileName] = result kz_filePathCache[workspacePath] = thisWorkspaceCache return result } prevSearchPath = searchPath searchPath = (searchPath as NSString).stringByDeletingLastPathComponent searchCount++ let searchPathCount = searchPath.componentsSeparatedByString("/").count if searchPathCount <= 3 || searchCount >= 2 { return nil } } } func kz_findFile(fileName : String, _ searchPath : String, _ prevSearchPath : String?) -> String? { let args = (prevSearchPath == nil ? ["-L", searchPath, "-name", fileName, "-print", "-quit"] : ["-L", searchPath, "-name", prevSearchPath!, "-prune", "-o", "-name", fileName, "-print", "-quit"]) return KZPluginHelper.runShellCommand("/usr/bin/find", arguments: args) }
mit
rshuston/ClosestPointsWorkshop
ClosestPoints/ClosestPointsTests/CombinationSolverTests.swift
1
11703
// // CombinationSolverTests.swift // ClosestPoints // // Created by Robert Huston on 12/7/16. // Copyright © 2016 Pinpoint Dynamics. All rights reserved. // import XCTest @testable import ClosestPoints class CombinationSolverTests: XCTestCase { func test_findClosestPoints_ReturnsNilForEmptyPointSet() { let points: [Point] = [] let subject = CombinationSolver() let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNil(closestPoints) completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_ReturnsNilForInsufficientPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNil(closestPoints) completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_FindsClosestPointsForTrivialPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[0]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[0]) XCTAssertEqual(closestPoints?.1, points[1]) } else { XCTAssertEqual(closestPoints?.0, points[1]) XCTAssertEqual(closestPoints?.1, points[0]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_CallsMonitorClosureForTrivialPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") var monitorCount = 0 subject.findClosestPoints(points: points, monitor: { (checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in monitorCount += 1 XCTAssertNotNil(checkRect) XCTAssertFalse(NSIsEmptyRect(checkRect!)) XCTAssertNotNil(closestPointsSoFar) XCTAssertEqual(checkPoints?.0, closestPointsSoFar?.0) XCTAssertEqual(checkPoints?.1, closestPointsSoFar?.1) let listOrdered = (closestPointsSoFar?.0 == points[0]) if listOrdered { XCTAssertEqual(closestPointsSoFar?.0, points[0]) XCTAssertEqual(closestPointsSoFar?.1, points[1]) } else { XCTAssertEqual(closestPointsSoFar?.0, points[1]) XCTAssertEqual(closestPointsSoFar?.1, points[0]) } return true }, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertEqual(monitorCount, 1) XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[0]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[0]) XCTAssertEqual(closestPoints?.1, points[1]) } else { XCTAssertEqual(closestPoints?.0, points[1]) XCTAssertEqual(closestPoints?.1, points[0]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_FindsClosestPointsForTrinaryPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 100, y: 100)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[0]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[0]) XCTAssertEqual(closestPoints?.1, points[2]) } else { XCTAssertEqual(closestPoints?.0, points[2]) XCTAssertEqual(closestPoints?.1, points[0]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_CallsMonitorClosureForTrinaryPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 100, y: 100)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") var monitorCount = 0 subject.findClosestPoints(points: points, monitor: { (checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in monitorCount += 1 XCTAssertNotNil(closestPointsSoFar) return true }, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertEqual(monitorCount, 3) // Combination (nCr) of 3C2 = 3 XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[0]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[0]) XCTAssertEqual(closestPoints?.1, points[2]) } else { XCTAssertEqual(closestPoints?.0, points[2]) XCTAssertEqual(closestPoints?.1, points[0]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_CanAbortFromMonitorClosureForTrinaryPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 100, y: 100)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") var monitorCount = 0 subject.findClosestPoints(points: points, monitor: { (checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in monitorCount += 1 XCTAssertNotNil(closestPointsSoFar) return false }, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertEqual(monitorCount, 1) XCTAssertNotNil(closestPoints) XCTAssertEqual(closestPoints?.0, points[0]) XCTAssertEqual(closestPoints?.1, points[1]) completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_FindsClosestPointsForMultiplePointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 100, y: 100)) points.append(Point(x: 10, y: 10)) points.append(Point(x: 101, y: 101)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[1]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[1]) XCTAssertEqual(closestPoints?.1, points[3]) } else { XCTAssertEqual(closestPoints?.0, points[3]) XCTAssertEqual(closestPoints?.1, points[1]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_CallsMonitorClosureForForMultiplePointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 1, y: 2)) points.append(Point(x: 100, y: 100)) points.append(Point(x: 10, y: 10)) points.append(Point(x: 101, y: 101)) points.append(Point(x: 3, y: 4)) let completionExpectation = expectation(description: "completion") var monitorCount = 0 subject.findClosestPoints(points: points, monitor: { (checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in monitorCount += 1 XCTAssertNotNil(closestPointsSoFar) return true }, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertEqual(monitorCount, 10) // Combination (nCr) of 5C2 = 10 XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[1]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[1]) XCTAssertEqual(closestPoints?.1, points[3]) } else { XCTAssertEqual(closestPoints?.0, points[3]) XCTAssertEqual(closestPoints?.1, points[1]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_findClosestPoints_FindsClosestPointsForThirteenPointSet() { var points: [Point] = [] let subject = CombinationSolver() points.append(Point(x: 31, y: 17)) points.append(Point(x: 21, y: 23)) // first of closest pair points.append(Point(x: 3, y: 15)) points.append(Point(x: 15, y: 31)) points.append(Point(x: 35, y: 25)) points.append(Point(x: 29, y: 11)) points.append(Point(x: 17, y: 21)) // second of closest pair points.append(Point(x: 5, y: 27)) points.append(Point(x: 11, y: 9)) points.append(Point(x: 13, y: 37)) points.append(Point(x: 7, y: 19)) points.append(Point(x: 33, y: 5)) points.append(Point(x: 25, y: 29)) let completionExpectation = expectation(description: "completion") subject.findClosestPoints(points: points, monitor: nil, completion: { (closestPoints: (Point, Point)?) -> Void in XCTAssertNotNil(closestPoints) let listOrdered = (closestPoints?.0 == points[1]) if listOrdered { XCTAssertEqual(closestPoints?.0, points[1]) XCTAssertEqual(closestPoints?.1, points[6]) } else { XCTAssertEqual(closestPoints?.0, points[6]) XCTAssertEqual(closestPoints?.1, points[1]) } completionExpectation.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } }
mit
Daltron/Spartan
Example/Spartan/AppDelegate.swift
1
2163
// // AppDelegate.swift // Spartan // // Created by dhint4 on 01/15/2017. // Copyright (c) 2017 dhint4. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the 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
qutheory/vapor
Sources/Vapor/Routing/Application+Routes.swift
2
360
extension Application { public var routes: Routes { if let existing = self.storage[RoutesKey.self] { return existing } else { let new = Routes() self.storage[RoutesKey.self] = new return new } } private struct RoutesKey: StorageKey { typealias Value = Routes } }
mit
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CartLine.swift
1
12321
// // CartLine.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Represents information about the merchandise in the cart. open class CartLineQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CartLine /// An attribute associated with the cart line. /// /// - parameters: /// - key: The key of the attribute. /// @discardableResult open func attribute(alias: String? = nil, key: String, _ subfields: (AttributeQuery) -> Void) -> CartLineQuery { var args: [String] = [] args.append("key:\(GraphQL.quoteString(input: key))") let argsString = "(\(args.joined(separator: ",")))" let subquery = AttributeQuery() subfields(subquery) addField(field: "attribute", aliasSuffix: alias, args: argsString, subfields: subquery) return self } /// The attributes associated with the cart line. Attributes are represented as /// key-value pairs. @discardableResult open func attributes(alias: String? = nil, _ subfields: (AttributeQuery) -> Void) -> CartLineQuery { let subquery = AttributeQuery() subfields(subquery) addField(field: "attributes", aliasSuffix: alias, subfields: subquery) return self } /// The cost of the merchandise that the buyer will pay for at checkout. The /// costs are subject to change and changes will be reflected at checkout. @discardableResult open func cost(alias: String? = nil, _ subfields: (CartLineCostQuery) -> Void) -> CartLineQuery { let subquery = CartLineCostQuery() subfields(subquery) addField(field: "cost", aliasSuffix: alias, subfields: subquery) return self } /// The discounts that have been applied to the cart line. @discardableResult open func discountAllocations(alias: String? = nil, _ subfields: (CartDiscountAllocationQuery) -> Void) -> CartLineQuery { let subquery = CartDiscountAllocationQuery() subfields(subquery) addField(field: "discountAllocations", aliasSuffix: alias, subfields: subquery) return self } /// The estimated cost of the merchandise that the buyer will pay for at /// checkout. The estimated costs are subject to change and changes will be /// reflected at checkout. @available(*, deprecated, message:"Use `cost` instead.") @discardableResult open func estimatedCost(alias: String? = nil, _ subfields: (CartLineEstimatedCostQuery) -> Void) -> CartLineQuery { let subquery = CartLineEstimatedCostQuery() subfields(subquery) addField(field: "estimatedCost", aliasSuffix: alias, subfields: subquery) return self } /// A globally-unique identifier. @discardableResult open func id(alias: String? = nil) -> CartLineQuery { addField(field: "id", aliasSuffix: alias) return self } /// The merchandise that the buyer intends to purchase. @discardableResult open func merchandise(alias: String? = nil, _ subfields: (MerchandiseQuery) -> Void) -> CartLineQuery { let subquery = MerchandiseQuery() subfields(subquery) addField(field: "merchandise", aliasSuffix: alias, subfields: subquery) return self } /// The quantity of the merchandise that the customer intends to purchase. @discardableResult open func quantity(alias: String? = nil) -> CartLineQuery { addField(field: "quantity", aliasSuffix: alias) return self } /// The selling plan associated with the cart line and the effect that each /// selling plan has on variants when they're purchased. @discardableResult open func sellingPlanAllocation(alias: String? = nil, _ subfields: (SellingPlanAllocationQuery) -> Void) -> CartLineQuery { let subquery = SellingPlanAllocationQuery() subfields(subquery) addField(field: "sellingPlanAllocation", aliasSuffix: alias, subfields: subquery) return self } } /// Represents information about the merchandise in the cart. open class CartLine: GraphQL.AbstractResponse, GraphQLObject, Node { public typealias Query = CartLineQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "attribute": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try Attribute(fields: value) case "attributes": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try value.map { return try Attribute(fields: $0) } case "cost": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try CartLineCost(fields: value) case "discountAllocations": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try value.map { return try UnknownCartDiscountAllocation.create(fields: $0) } case "estimatedCost": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try CartLineEstimatedCost(fields: value) case "id": guard let value = value as? String else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return GraphQL.ID(rawValue: value) case "merchandise": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try UnknownMerchandise.create(fields: value) case "quantity": guard let value = value as? Int else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return Int32(value) case "sellingPlanAllocation": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } return try SellingPlanAllocation(fields: value) default: throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue) } } /// An attribute associated with the cart line. open var attribute: Storefront.Attribute? { return internalGetAttribute() } open func aliasedAttribute(alias: String) -> Storefront.Attribute? { return internalGetAttribute(alias: alias) } func internalGetAttribute(alias: String? = nil) -> Storefront.Attribute? { return field(field: "attribute", aliasSuffix: alias) as! Storefront.Attribute? } /// The attributes associated with the cart line. Attributes are represented as /// key-value pairs. open var attributes: [Storefront.Attribute] { return internalGetAttributes() } func internalGetAttributes(alias: String? = nil) -> [Storefront.Attribute] { return field(field: "attributes", aliasSuffix: alias) as! [Storefront.Attribute] } /// The cost of the merchandise that the buyer will pay for at checkout. The /// costs are subject to change and changes will be reflected at checkout. open var cost: Storefront.CartLineCost { return internalGetCost() } func internalGetCost(alias: String? = nil) -> Storefront.CartLineCost { return field(field: "cost", aliasSuffix: alias) as! Storefront.CartLineCost } /// The discounts that have been applied to the cart line. open var discountAllocations: [CartDiscountAllocation] { return internalGetDiscountAllocations() } func internalGetDiscountAllocations(alias: String? = nil) -> [CartDiscountAllocation] { return field(field: "discountAllocations", aliasSuffix: alias) as! [CartDiscountAllocation] } /// The estimated cost of the merchandise that the buyer will pay for at /// checkout. The estimated costs are subject to change and changes will be /// reflected at checkout. @available(*, deprecated, message:"Use `cost` instead.") open var estimatedCost: Storefront.CartLineEstimatedCost { return internalGetEstimatedCost() } func internalGetEstimatedCost(alias: String? = nil) -> Storefront.CartLineEstimatedCost { return field(field: "estimatedCost", aliasSuffix: alias) as! Storefront.CartLineEstimatedCost } /// A globally-unique identifier. open var id: GraphQL.ID { return internalGetId() } func internalGetId(alias: String? = nil) -> GraphQL.ID { return field(field: "id", aliasSuffix: alias) as! GraphQL.ID } /// The merchandise that the buyer intends to purchase. open var merchandise: Merchandise { return internalGetMerchandise() } func internalGetMerchandise(alias: String? = nil) -> Merchandise { return field(field: "merchandise", aliasSuffix: alias) as! Merchandise } /// The quantity of the merchandise that the customer intends to purchase. open var quantity: Int32 { return internalGetQuantity() } func internalGetQuantity(alias: String? = nil) -> Int32 { return field(field: "quantity", aliasSuffix: alias) as! Int32 } /// The selling plan associated with the cart line and the effect that each /// selling plan has on variants when they're purchased. open var sellingPlanAllocation: Storefront.SellingPlanAllocation? { return internalGetSellingPlanAllocation() } func internalGetSellingPlanAllocation(alias: String? = nil) -> Storefront.SellingPlanAllocation? { return field(field: "sellingPlanAllocation", aliasSuffix: alias) as! Storefront.SellingPlanAllocation? } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "attribute": if let value = internalGetAttribute() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "attributes": internalGetAttributes().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "cost": response.append(internalGetCost()) response.append(contentsOf: internalGetCost().childResponseObjectMap()) case "discountAllocations": internalGetDiscountAllocations().forEach { response.append(($0 as! GraphQL.AbstractResponse)) response.append(contentsOf: ($0 as! GraphQL.AbstractResponse).childResponseObjectMap()) } case "estimatedCost": response.append(internalGetEstimatedCost()) response.append(contentsOf: internalGetEstimatedCost().childResponseObjectMap()) case "merchandise": response.append((internalGetMerchandise() as! GraphQL.AbstractResponse)) response.append(contentsOf: (internalGetMerchandise() as! GraphQL.AbstractResponse).childResponseObjectMap()) case "sellingPlanAllocation": if let value = internalGetSellingPlanAllocation() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } default: break } } return response } } }
mit
victor-pavlychko/SwiftyTasks
SwiftyTasks/Tasks/AsyncBlockTask.swift
1
2916
// // AsyncBlockTask.swift // SwiftyTasks // // Created by Victor Pavlychko on 9/12/16. // Copyright © 2016 address.wtf. All rights reserved. // import Foundation /// `AsyncTask` subclass to wrap any asynchronous code block into an `AsyncTask` public final class AsyncBlockTask<ResultType>: AsyncTask<ResultType> { private var _block: ((AsyncBlockTask<ResultType>) throws -> Void)! /// Initializes `AsyncBlockTask` with a code block tacking completion handler with result /// /// - Parameters: /// - block: code block /// - completionBlock: completion handler passed to the code block /// - result: task result returned from the code block /// - Returns: Newly created `AsyncBlockTask` instance public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType) -> Void) throws -> Void) { _block = { try block($0.finish) } } /// Initializes `AsyncBlockTask` with a code block tacking completion handler with optional result and error /// /// - Parameters: /// - block: code block /// - completionBlock: completion handler passed to the code block /// - result: task result returned from the code block /// - error: task error returned from the code block /// - Returns: Newly created `AsyncBlockTask` instance public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType?, _ error: Error?) -> Void) throws -> Void) { _block = { try block($0.finish) } } /// Initializes `AsyncBlockTask` with a code block tacking completion handler with optional result /// /// - Parameters: /// - block: code block /// - completionBlock: completion handler passed to the code block /// - result: optional task result returned from the code block /// - Returns: Newly created `AsyncBlockTask` instance public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType?) -> Void) throws -> Void) { _block = { try block($0.finish) } } /// Initializes `AsyncBlockTask` with a code block tacking completion handler with a result block /// /// - Parameters: /// - block: code block /// - completionBlock: completion handler passed to the code block /// - resultBlock: task result returned from the code block /// - Returns: Newly created `AsyncBlockTask` instance public init(_ block: @escaping (_ completionBlock: @escaping (_ resultBlock: () throws -> ResultType) -> Void) throws -> Void) { _block = { try block($0.finish) } } /// Starts execution. Do not call this method yourself. public override func main() { do { try _block(self) _block = nil } catch { finish(error: error) } } }
mit
mparrish91/gifRecipes
framework/vendor/MiniKeychain/MiniKeychain/MiniKeychain.swift
1
66344
// // MiniKeychain.swift // MiniKeychain // // Created by sonson on 2016/08/18. // Copyright © 2016年 sonson. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #endif import Security class MiniKeychain { let service: String? let accessGroup: String? public init() { self.service = nil self.accessGroup = nil } public init(service: String) { self.service = service self.accessGroup = nil } public init(accessGroup: String) { if let bundleIdentifier = Bundle.main.bundleIdentifier { self.service = bundleIdentifier } else { self.service = nil } self.accessGroup = accessGroup } public init(service: String, accessGroup: String) { self.service = service self.accessGroup = accessGroup } func getDefaultQuery() -> [String: Any] { var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword as String] if let service = self.service { query[kSecAttrService as String] = service } query[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny as String // Access group is not supported on any simulators. #if (!arch(i386) && !arch(x86_64)) || (!os(iOS) && !os(watchOS) && !os(tvOS)) if let accessGroup = self.accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } #endif return query } public func save(key: String, data: Data) throws { var query = getDefaultQuery() query[kSecAttrAccount as String] = key query[kSecValueData as String] = data SecItemDelete(query as CFDictionary) let status: OSStatus = SecItemAdd(query as CFDictionary, nil) let message = Status(status: status).description if status != noErr { let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) print("OSStatus error:[\(error.code)] \(error.localizedDescription)") throw error } } public func data(of key: String) throws -> Data { var query = getDefaultQuery() query[kSecAttrAccount as String] = key query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne if let service = service { query[kSecAttrService as String] = service } var result: AnyObject? let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } if status == noErr { if let data = result as? Data { return data } else { let error = NSError(domain: "a", code: Int(1), userInfo: [NSLocalizedDescriptionKey: "a"]) throw error } } else { let message = Status(status: status).description let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) print("OSStatus error:[\(error.code)] \(error.localizedDescription)") throw error } } public func keys() throws -> [String] { var query = getDefaultQuery() query[kSecReturnData as String] = kCFBooleanFalse query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitAll if let service = service { query[kSecAttrService as String] = service } var result: AnyObject? let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } let message = Status(status: status).description let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) print("OSStatus error:[\(error.code)] \(error.localizedDescription)") switch status { case noErr: if let dictionaries = result as? [[String: Any]] { return dictionaries.flatMap({$0["acct"] as? String}) } else { let error = NSError(domain: "a", code: Int(Status.unexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: ""]) throw error } case errSecItemNotFound: return [] default: throw error } } @discardableResult public func delete(key: String) -> Bool { var query = getDefaultQuery() query[kSecAttrAccount as String] = key let status: OSStatus = SecItemDelete(query as CFDictionary) return status == noErr } @discardableResult public func clear() -> Bool { let query = getDefaultQuery() let status: OSStatus = SecItemDelete(query as CFDictionary) return status == noErr } } public enum Status: OSStatus, Error { case success = 0 case unimplemented = -4 case diskFull = -34 case io = -36 case opWr = -49 case param = -50 case wrPerm = -61 case allocate = -108 case userCanceled = -128 case badReq = -909 case internalComponent = -2070 case notAvailable = -25291 case readOnly = -25292 case authFailed = -25293 case noSuchKeychain = -25294 case invalidKeychain = -25295 case duplicateKeychain = -25296 case duplicateCallback = -25297 case invalidCallback = -25298 case duplicateItem = -25299 case itemNotFound = -25300 case bufferTooSmall = -25301 case dataTooLarge = -25302 case noSuchAttr = -25303 case invalidItemRef = -25304 case invalidSearchRef = -25305 case noSuchClass = -25306 case noDefaultKeychain = -25307 case interactionNotAllowed = -25308 case readOnlyAttr = -25309 case wrongSecVersion = -25310 case keySizeNotAllowed = -25311 case noStorageModule = -25312 case noCertificateModule = -25313 case noPolicyModule = -25314 case interactionRequired = -25315 case dataNotAvailable = -25316 case dataNotModifiable = -25317 case createChainFailed = -25318 case invalidPrefsDomain = -25319 case inDarkWake = -25320 case aclNotSimple = -25240 case policyNotFound = -25241 case invalidTrustSetting = -25242 case noAccessForItem = -25243 case invalidOwnerEdit = -25244 case trustNotAvailable = -25245 case unsupportedFormat = -25256 case unknownFormat = -25257 case keyIsSensitive = -25258 case multiplePrivKeys = -25259 case passphraseRequired = -25260 case invalidPasswordRef = -25261 case invalidTrustSettings = -25262 case noTrustSettings = -25263 case pkcs12VerifyFailure = -25264 case invalidCertificate = -26265 case notSigner = -26267 case policyDenied = -26270 case invalidKey = -26274 case decode = -26275 case `internal` = -26276 case unsupportedAlgorithm = -26268 case unsupportedOperation = -26271 case unsupportedPadding = -26273 case itemInvalidKey = -34000 case itemInvalidKeyType = -34001 case itemInvalidValue = -34002 case itemClassMissing = -34003 case itemMatchUnsupported = -34004 case useItemListUnsupported = -34005 case useKeychainUnsupported = -34006 case useKeychainListUnsupported = -34007 case returnDataUnsupported = -34008 case returnAttributesUnsupported = -34009 case returnRefUnsupported = -34010 case returnPersitentRefUnsupported = -34011 case valueRefUnsupported = -34012 case valuePersistentRefUnsupported = -34013 case returnMissingPointer = -34014 case matchLimitUnsupported = -34015 case itemIllegalQuery = -34016 case waitForCallback = -34017 case missingEntitlement = -34018 case upgradePending = -34019 case mpSignatureInvalid = -25327 case otrTooOld = -25328 case otrIDTooNew = -25329 case serviceNotAvailable = -67585 case insufficientClientID = -67586 case deviceReset = -67587 case deviceFailed = -67588 case appleAddAppACLSubject = -67589 case applePublicKeyIncomplete = -67590 case appleSignatureMismatch = -67591 case appleInvalidKeyStartDate = -67592 case appleInvalidKeyEndDate = -67593 case conversionError = -67594 case appleSSLv2Rollback = -67595 case quotaExceeded = -67596 case fileTooBig = -67597 case invalidDatabaseBlob = -67598 case invalidKeyBlob = -67599 case incompatibleDatabaseBlob = -67600 case incompatibleKeyBlob = -67601 case hostNameMismatch = -67602 case unknownCriticalExtensionFlag = -67603 case noBasicConstraints = -67604 case noBasicConstraintsCA = -67605 case invalidAuthorityKeyID = -67606 case invalidSubjectKeyID = -67607 case invalidKeyUsageForPolicy = -67608 case invalidExtendedKeyUsage = -67609 case invalidIDLinkage = -67610 case pathLengthConstraintExceeded = -67611 case invalidRoot = -67612 case crlExpired = -67613 case crlNotValidYet = -67614 case crlNotFound = -67615 case crlServerDown = -67616 case crlBadURI = -67617 case unknownCertExtension = -67618 case unknownCRLExtension = -67619 case crlNotTrusted = -67620 case crlPolicyFailed = -67621 case idpFailure = -67622 case smimeEmailAddressesNotFound = -67623 case smimeBadExtendedKeyUsage = -67624 case smimeBadKeyUsage = -67625 case smimeKeyUsageNotCritical = -67626 case smimeNoEmailAddress = -67627 case smimeSubjAltNameNotCritical = -67628 case sslBadExtendedKeyUsage = -67629 case ocspBadResponse = -67630 case ocspBadRequest = -67631 case ocspUnavailable = -67632 case ocspStatusUnrecognized = -67633 case endOfData = -67634 case incompleteCertRevocationCheck = -67635 case networkFailure = -67636 case ocspNotTrustedToAnchor = -67637 case recordModified = -67638 case ocspSignatureError = -67639 case ocspNoSigner = -67640 case ocspResponderMalformedReq = -67641 case ocspResponderInternalError = -67642 case ocspResponderTryLater = -67643 case ocspResponderSignatureRequired = -67644 case ocspResponderUnauthorized = -67645 case ocspResponseNonceMismatch = -67646 case codeSigningBadCertChainLength = -67647 case codeSigningNoBasicConstraints = -67648 case codeSigningBadPathLengthConstraint = -67649 case codeSigningNoExtendedKeyUsage = -67650 case codeSigningDevelopment = -67651 case resourceSignBadCertChainLength = -67652 case resourceSignBadExtKeyUsage = -67653 case trustSettingDeny = -67654 case invalidSubjectName = -67655 case unknownQualifiedCertStatement = -67656 case mobileMeRequestQueued = -67657 case mobileMeRequestRedirected = -67658 case mobileMeServerError = -67659 case mobileMeServerNotAvailable = -67660 case mobileMeServerAlreadyExists = -67661 case mobileMeServerServiceErr = -67662 case mobileMeRequestAlreadyPending = -67663 case mobileMeNoRequestPending = -67664 case mobileMeCSRVerifyFailure = -67665 case mobileMeFailedConsistencyCheck = -67666 case notInitialized = -67667 case invalidHandleUsage = -67668 case pvcReferentNotFound = -67669 case functionIntegrityFail = -67670 case internalError = -67671 case memoryError = -67672 case invalidData = -67673 case mdsError = -67674 case invalidPointer = -67675 case selfCheckFailed = -67676 case functionFailed = -67677 case moduleManifestVerifyFailed = -67678 case invalidGUID = -67679 case invalidHandle = -67680 case invalidDBList = -67681 case invalidPassthroughID = -67682 case invalidNetworkAddress = -67683 case crlAlreadySigned = -67684 case invalidNumberOfFields = -67685 case verificationFailure = -67686 case unknownTag = -67687 case invalidSignature = -67688 case invalidName = -67689 case invalidCertificateRef = -67690 case invalidCertificateGroup = -67691 case tagNotFound = -67692 case invalidQuery = -67693 case invalidValue = -67694 case callbackFailed = -67695 case aclDeleteFailed = -67696 case aclReplaceFailed = -67697 case aclAddFailed = -67698 case aclChangeFailed = -67699 case invalidAccessCredentials = -67700 case invalidRecord = -67701 case invalidACL = -67702 case invalidSampleValue = -67703 case incompatibleVersion = -67704 case privilegeNotGranted = -67705 case invalidScope = -67706 case pvcAlreadyConfigured = -67707 case invalidPVC = -67708 case emmLoadFailed = -67709 case emmUnloadFailed = -67710 case addinLoadFailed = -67711 case invalidKeyRef = -67712 case invalidKeyHierarchy = -67713 case addinUnloadFailed = -67714 case libraryReferenceNotFound = -67715 case invalidAddinFunctionTable = -67716 case invalidServiceMask = -67717 case moduleNotLoaded = -67718 case invalidSubServiceID = -67719 case attributeNotInContext = -67720 case moduleManagerInitializeFailed = -67721 case moduleManagerNotFound = -67722 case eventNotificationCallbackNotFound = -67723 case inputLengthError = -67724 case outputLengthError = -67725 case privilegeNotSupported = -67726 case deviceError = -67727 case attachHandleBusy = -67728 case notLoggedIn = -67729 case algorithmMismatch = -67730 case keyUsageIncorrect = -67731 case keyBlobTypeIncorrect = -67732 case keyHeaderInconsistent = -67733 case unsupportedKeyFormat = -67734 case unsupportedKeySize = -67735 case invalidKeyUsageMask = -67736 case unsupportedKeyUsageMask = -67737 case invalidKeyAttributeMask = -67738 case unsupportedKeyAttributeMask = -67739 case invalidKeyLabel = -67740 case unsupportedKeyLabel = -67741 case invalidKeyFormat = -67742 case unsupportedVectorOfBuffers = -67743 case invalidInputVector = -67744 case invalidOutputVector = -67745 case invalidContext = -67746 case invalidAlgorithm = -67747 case invalidAttributeKey = -67748 case missingAttributeKey = -67749 case invalidAttributeInitVector = -67750 case missingAttributeInitVector = -67751 case invalidAttributeSalt = -67752 case missingAttributeSalt = -67753 case invalidAttributePadding = -67754 case missingAttributePadding = -67755 case invalidAttributeRandom = -67756 case missingAttributeRandom = -67757 case invalidAttributeSeed = -67758 case missingAttributeSeed = -67759 case invalidAttributePassphrase = -67760 case missingAttributePassphrase = -67761 case invalidAttributeKeyLength = -67762 case missingAttributeKeyLength = -67763 case invalidAttributeBlockSize = -67764 case missingAttributeBlockSize = -67765 case invalidAttributeOutputSize = -67766 case missingAttributeOutputSize = -67767 case invalidAttributeRounds = -67768 case missingAttributeRounds = -67769 case invalidAlgorithmParms = -67770 case missingAlgorithmParms = -67771 case invalidAttributeLabel = -67772 case missingAttributeLabel = -67773 case invalidAttributeKeyType = -67774 case missingAttributeKeyType = -67775 case invalidAttributeMode = -67776 case missingAttributeMode = -67777 case invalidAttributeEffectiveBits = -67778 case missingAttributeEffectiveBits = -67779 case invalidAttributeStartDate = -67780 case missingAttributeStartDate = -67781 case invalidAttributeEndDate = -67782 case missingAttributeEndDate = -67783 case invalidAttributeVersion = -67784 case missingAttributeVersion = -67785 case invalidAttributePrime = -67786 case missingAttributePrime = -67787 case invalidAttributeBase = -67788 case missingAttributeBase = -67789 case invalidAttributeSubprime = -67790 case missingAttributeSubprime = -67791 case invalidAttributeIterationCount = -67792 case missingAttributeIterationCount = -67793 case invalidAttributeDLDBHandle = -67794 case missingAttributeDLDBHandle = -67795 case invalidAttributeAccessCredentials = -67796 case missingAttributeAccessCredentials = -67797 case invalidAttributePublicKeyFormat = -67798 case missingAttributePublicKeyFormat = -67799 case invalidAttributePrivateKeyFormat = -67800 case missingAttributePrivateKeyFormat = -67801 case invalidAttributeSymmetricKeyFormat = -67802 case missingAttributeSymmetricKeyFormat = -67803 case invalidAttributeWrappedKeyFormat = -67804 case missingAttributeWrappedKeyFormat = -67805 case stagedOperationInProgress = -67806 case stagedOperationNotStarted = -67807 case verifyFailed = -67808 case querySizeUnknown = -67809 case blockSizeMismatch = -67810 case publicKeyInconsistent = -67811 case deviceVerifyFailed = -67812 case invalidLoginName = -67813 case alreadyLoggedIn = -67814 case invalidDigestAlgorithm = -67815 case invalidCRLGroup = -67816 case certificateCannotOperate = -67817 case certificateExpired = -67818 case certificateNotValidYet = -67819 case certificateRevoked = -67820 case certificateSuspended = -67821 case insufficientCredentials = -67822 case invalidAction = -67823 case invalidAuthority = -67824 case verifyActionFailed = -67825 case invalidCertAuthority = -67826 case invaldCRLAuthority = -67827 case invalidCRLEncoding = -67828 case invalidCRLType = -67829 case invalidCRL = -67830 case invalidFormType = -67831 case invalidID = -67832 case invalidIdentifier = -67833 case invalidIndex = -67834 case invalidPolicyIdentifiers = -67835 case invalidTimeString = -67836 case invalidReason = -67837 case invalidRequestInputs = -67838 case invalidResponseVector = -67839 case invalidStopOnPolicy = -67840 case invalidTuple = -67841 case multipleValuesUnsupported = -67842 case notTrusted = -67843 case noDefaultAuthority = -67844 case rejectedForm = -67845 case requestLost = -67846 case requestRejected = -67847 case unsupportedAddressType = -67848 case unsupportedService = -67849 case invalidTupleGroup = -67850 case invalidBaseACLs = -67851 case invalidTupleCredendtials = -67852 case invalidEncoding = -67853 case invalidValidityPeriod = -67854 case invalidRequestor = -67855 case requestDescriptor = -67856 case invalidBundleInfo = -67857 case invalidCRLIndex = -67858 case noFieldValues = -67859 case unsupportedFieldFormat = -67860 case unsupportedIndexInfo = -67861 case unsupportedLocality = -67862 case unsupportedNumAttributes = -67863 case unsupportedNumIndexes = -67864 case unsupportedNumRecordTypes = -67865 case fieldSpecifiedMultiple = -67866 case incompatibleFieldFormat = -67867 case invalidParsingModule = -67868 case databaseLocked = -67869 case datastoreIsOpen = -67870 case missingValue = -67871 case unsupportedQueryLimits = -67872 case unsupportedNumSelectionPreds = -67873 case unsupportedOperator = -67874 case invalidDBLocation = -67875 case invalidAccessRequest = -67876 case invalidIndexInfo = -67877 case invalidNewOwner = -67878 case invalidModifyMode = -67879 case missingRequiredExtension = -67880 case extendedKeyUsageNotCritical = -67881 case timestampMissing = -67882 case timestampInvalid = -67883 case timestampNotTrusted = -67884 case timestampServiceNotAvailable = -67885 case timestampBadAlg = -67886 case timestampBadRequest = -67887 case timestampBadDataFormat = -67888 case timestampTimeNotAvailable = -67889 case timestampUnacceptedPolicy = -67890 case timestampUnacceptedExtension = -67891 case timestampAddInfoNotAvailable = -67892 case timestampSystemFailure = -67893 case signingTimeMissing = -67894 case timestampRejection = -67895 case timestampWaiting = -67896 case timestampRevocationWarning = -67897 case timestampRevocationNotification = -67898 case unexpectedError = -99999 } extension Status: RawRepresentable, CustomStringConvertible { public init(status: OSStatus) { if let mappedStatus = Status(rawValue: status) { self = mappedStatus } else { self = .unexpectedError } } public var description: String { switch self { case .success: return "No error." case .unimplemented: return "Function or operation not implemented." case .diskFull: return "The disk is full." case .io: return "I/O error (bummers)" case .opWr: return "file already open with with write permission" case .param: return "One or more parameters passed to a function were not valid." case .wrPerm: return "write permissions error" case .allocate: return "Failed to allocate memory." case .userCanceled: return "User canceled the operation." case .badReq: return "Bad parameter or invalid state for operation." case .internalComponent: return "" case .notAvailable: return "No keychain is available. You may need to restart your computer." case .readOnly: return "This keychain cannot be modified." case .authFailed: return "The user name or passphrase you entered is not correct." case .noSuchKeychain: return "The specified keychain could not be found." case .invalidKeychain: return "The specified keychain is not a valid keychain file." case .duplicateKeychain: return "A keychain with the same name already exists." case .duplicateCallback: return "The specified callback function is already installed." case .invalidCallback: return "The specified callback function is not valid." case .duplicateItem: return "The specified item already exists in the keychain." case .itemNotFound: return "The specified item could not be found in the keychain." case .bufferTooSmall: return "There is not enough memory available to use the specified item." case .dataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case .noSuchAttr: return "The specified attribute does not exist." case .invalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case .invalidSearchRef: return "Unable to search the current keychain." case .noSuchClass: return "The specified item does not appear to be a valid keychain item." case .noDefaultKeychain: return "A default keychain could not be found." case .interactionNotAllowed: return "User interaction is not allowed." case .readOnlyAttr: return "The specified attribute could not be modified." case .wrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case .keySizeNotAllowed: return "This item specifies a key size which is too large." case .noStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case .noCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case .noPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case .interactionRequired: return "User interaction is required, but is currently not allowed." case .dataNotAvailable: return "The contents of this item cannot be retrieved." case .dataNotModifiable: return "The contents of this item cannot be modified." case .createChainFailed: return "One or more certificates required to validate this certificate cannot be found." case .invalidPrefsDomain: return "The specified preferences domain is not valid." case .inDarkWake: return "In dark wake, no UI possible" case .aclNotSimple: return "The specified access control list is not in standard (simple) form." case .policyNotFound: return "The specified policy cannot be found." case .invalidTrustSetting: return "The specified trust setting is invalid." case .noAccessForItem: return "The specified item has no access control." case .invalidOwnerEdit: return "Invalid attempt to change the owner of this item." case .trustNotAvailable: return "No trust results are available." case .unsupportedFormat: return "Import/Export format unsupported." case .unknownFormat: return "Unknown format in import." case .keyIsSensitive: return "Key material must be wrapped for export." case .multiplePrivKeys: return "An attempt was made to import multiple private keys." case .passphraseRequired: return "Passphrase is required for import/export." case .invalidPasswordRef: return "The password reference was invalid." case .invalidTrustSettings: return "The Trust Settings Record was corrupted." case .noTrustSettings: return "No Trust Settings were found." case .pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case .invalidCertificate: return "This certificate could not be decoded." case .notSigner: return "A certificate was not signed by its proposed parent." case .policyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case .invalidKey: return "The provided key material was not valid." case .decode: return "Unable to decode the provided data." case .`internal`: return "An internal error occurred in the Security framework." case .unsupportedAlgorithm: return "An unsupported algorithm was encountered." case .unsupportedOperation: return "The operation you requested is not supported by this key." case .unsupportedPadding: return "The padding you requested is not supported." case .itemInvalidKey: return "A string key in dictionary is not one of the supported keys." case .itemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case .itemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case .itemClassMissing: return "No kSecItemClass key was specified in a dictionary." case .itemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case .useItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case .useKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case .useKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case .returnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case .returnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case .returnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case .returnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case .valueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case .valuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case .returnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case .matchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case .itemIllegalQuery: return "The caller passed in a query which contained too many keys." case .waitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case .missingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case .upgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case .mpSignatureInvalid: return "Signature invalid on MP message" case .otrTooOld: return "Message is too old to use" case .otrIDTooNew: return "Key ID is too new to use! Message from the future?" case .serviceNotAvailable: return "The required service is not available." case .insufficientClientID: return "The client ID is not correct." case .deviceReset: return "A device reset has occurred." case .deviceFailed: return "A device failure has occurred." case .appleAddAppACLSubject: return "Adding an application ACL subject failed." case .applePublicKeyIncomplete: return "The public key is incomplete." case .appleSignatureMismatch: return "A signature mismatch has occurred." case .appleInvalidKeyStartDate: return "The specified key has an invalid start date." case .appleInvalidKeyEndDate: return "The specified key has an invalid end date." case .conversionError: return "A conversion error has occurred." case .appleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case .quotaExceeded: return "The quota was exceeded." case .fileTooBig: return "The file is too big." case .invalidDatabaseBlob: return "The specified database has an invalid blob." case .invalidKeyBlob: return "The specified database has an invalid key blob." case .incompatibleDatabaseBlob: return "The specified database has an incompatible blob." case .incompatibleKeyBlob: return "The specified database has an incompatible key blob." case .hostNameMismatch: return "A host name mismatch has occurred." case .unknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case .noBasicConstraints: return "No basic constraints were found." case .noBasicConstraintsCA: return "No basic CA constraints were found." case .invalidAuthorityKeyID: return "The authority key ID is not valid." case .invalidSubjectKeyID: return "The subject key ID is not valid." case .invalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case .invalidExtendedKeyUsage: return "The extended key usage is not valid." case .invalidIDLinkage: return "The ID linkage is not valid." case .pathLengthConstraintExceeded: return "The path length constraint was exceeded." case .invalidRoot: return "The root or anchor certificate is not valid." case .crlExpired: return "The CRL has expired." case .crlNotValidYet: return "The CRL is not yet valid." case .crlNotFound: return "The CRL was not found." case .crlServerDown: return "The CRL server is down." case .crlBadURI: return "The CRL has a bad Uniform Resource Identifier." case .unknownCertExtension: return "An unknown certificate extension was encountered." case .unknownCRLExtension: return "An unknown CRL extension was encountered." case .crlNotTrusted: return "The CRL is not trusted." case .crlPolicyFailed: return "The CRL policy failed." case .idpFailure: return "The issuing distribution point was not valid." case .smimeEmailAddressesNotFound: return "An email address mismatch was encountered." case .smimeBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case .smimeBadKeyUsage: return "The key usage is not compatible with SMIME." case .smimeKeyUsageNotCritical: return "The key usage extension is not marked as critical." case .smimeNoEmailAddress: return "No email address was found in the certificate." case .smimeSubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case .sslBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case .ocspBadResponse: return "The OCSP response was incorrect or could not be parsed." case .ocspBadRequest: return "The OCSP request was incorrect or could not be parsed." case .ocspUnavailable: return "OCSP service is unavailable." case .ocspStatusUnrecognized: return "The OCSP server did not recognize this certificate." case .endOfData: return "An end-of-data was detected." case .incompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case .networkFailure: return "A network failure occurred." case .ocspNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case .recordModified: return "The record was modified." case .ocspSignatureError: return "The OCSP response had an invalid signature." case .ocspNoSigner: return "The OCSP response had no signer." case .ocspResponderMalformedReq: return "The OCSP responder was given a malformed request." case .ocspResponderInternalError: return "The OCSP responder encountered an internal error." case .ocspResponderTryLater: return "The OCSP responder is busy, try again later." case .ocspResponderSignatureRequired: return "The OCSP responder requires a signature." case .ocspResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case .ocspResponseNonceMismatch: return "The OCSP response nonce did not match the request." case .codeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case .codeSigningNoBasicConstraints: return "Code signing found no basic constraints." case .codeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case .codeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case .codeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case .resourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case .resourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case .trustSettingDeny: return "The trust setting for this policy was set to Deny." case .invalidSubjectName: return "An invalid certificate subject name was encountered." case .unknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case .mobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case .mobileMeRequestRedirected: return "The MobileMe request was redirected." case .mobileMeServerError: return "A MobileMe server error occurred." case .mobileMeServerNotAvailable: return "The MobileMe server is not available." case .mobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case .mobileMeServerServiceErr: return "A MobileMe service error has occurred." case .mobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case .mobileMeNoRequestPending: return "MobileMe has no request pending." case .mobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case .mobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case .notInitialized: return "A function was called without initializing CSSM." case .invalidHandleUsage: return "The CSSM handle does not match with the service type." case .pvcReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case .functionIntegrityFail: return "A function address was not within the verified module." case .internalError: return "An internal error has occurred." case .memoryError: return "A memory error has occurred." case .invalidData: return "Invalid data was encountered." case .mdsError: return "A Module Directory Service error has occurred." case .invalidPointer: return "An invalid pointer was encountered." case .selfCheckFailed: return "Self-check has failed." case .functionFailed: return "A function has failed." case .moduleManifestVerifyFailed: return "A module manifest verification failure has occurred." case .invalidGUID: return "An invalid GUID was encountered." case .invalidHandle: return "An invalid handle was encountered." case .invalidDBList: return "An invalid DB list was encountered." case .invalidPassthroughID: return "An invalid passthrough ID was encountered." case .invalidNetworkAddress: return "An invalid network address was encountered." case .crlAlreadySigned: return "The certificate revocation list is already signed." case .invalidNumberOfFields: return "An invalid number of fields were encountered." case .verificationFailure: return "A verification failure occurred." case .unknownTag: return "An unknown tag was encountered." case .invalidSignature: return "An invalid signature was encountered." case .invalidName: return "An invalid name was encountered." case .invalidCertificateRef: return "An invalid certificate reference was encountered." case .invalidCertificateGroup: return "An invalid certificate group was encountered." case .tagNotFound: return "The specified tag was not found." case .invalidQuery: return "The specified query was not valid." case .invalidValue: return "An invalid value was detected." case .callbackFailed: return "A callback has failed." case .aclDeleteFailed: return "An ACL delete operation has failed." case .aclReplaceFailed: return "An ACL replace operation has failed." case .aclAddFailed: return "An ACL add operation has failed." case .aclChangeFailed: return "An ACL change operation has failed." case .invalidAccessCredentials: return "Invalid access credentials were encountered." case .invalidRecord: return "An invalid record was encountered." case .invalidACL: return "An invalid ACL was encountered." case .invalidSampleValue: return "An invalid sample value was encountered." case .incompatibleVersion: return "An incompatible version was encountered." case .privilegeNotGranted: return "The privilege was not granted." case .invalidScope: return "An invalid scope was encountered." case .pvcAlreadyConfigured: return "The PVC is already configured." case .invalidPVC: return "An invalid PVC was encountered." case .emmLoadFailed: return "The EMM load has failed." case .emmUnloadFailed: return "The EMM unload has failed." case .addinLoadFailed: return "The add-in load operation has failed." case .invalidKeyRef: return "An invalid key was encountered." case .invalidKeyHierarchy: return "An invalid key hierarchy was encountered." case .addinUnloadFailed: return "The add-in unload operation has failed." case .libraryReferenceNotFound: return "A library reference was not found." case .invalidAddinFunctionTable: return "An invalid add-in function table was encountered." case .invalidServiceMask: return "An invalid service mask was encountered." case .moduleNotLoaded: return "A module was not loaded." case .invalidSubServiceID: return "An invalid subservice ID was encountered." case .attributeNotInContext: return "An attribute was not in the context." case .moduleManagerInitializeFailed: return "A module failed to initialize." case .moduleManagerNotFound: return "A module was not found." case .eventNotificationCallbackNotFound: return "An event notification callback was not found." case .inputLengthError: return "An input length error was encountered." case .outputLengthError: return "An output length error was encountered." case .privilegeNotSupported: return "The privilege is not supported." case .deviceError: return "A device error was encountered." case .attachHandleBusy: return "The CSP handle was busy." case .notLoggedIn: return "You are not logged in." case .algorithmMismatch: return "An algorithm mismatch was encountered." case .keyUsageIncorrect: return "The key usage is incorrect." case .keyBlobTypeIncorrect: return "The key blob type is incorrect." case .keyHeaderInconsistent: return "The key header is inconsistent." case .unsupportedKeyFormat: return "The key header format is not supported." case .unsupportedKeySize: return "The key size is not supported." case .invalidKeyUsageMask: return "The key usage mask is not valid." case .unsupportedKeyUsageMask: return "The key usage mask is not supported." case .invalidKeyAttributeMask: return "The key attribute mask is not valid." case .unsupportedKeyAttributeMask: return "The key attribute mask is not supported." case .invalidKeyLabel: return "The key label is not valid." case .unsupportedKeyLabel: return "The key label is not supported." case .invalidKeyFormat: return "The key format is not valid." case .unsupportedVectorOfBuffers: return "The vector of buffers is not supported." case .invalidInputVector: return "The input vector is not valid." case .invalidOutputVector: return "The output vector is not valid." case .invalidContext: return "An invalid context was encountered." case .invalidAlgorithm: return "An invalid algorithm was encountered." case .invalidAttributeKey: return "A key attribute was not valid." case .missingAttributeKey: return "A key attribute was missing." case .invalidAttributeInitVector: return "An init vector attribute was not valid." case .missingAttributeInitVector: return "An init vector attribute was missing." case .invalidAttributeSalt: return "A salt attribute was not valid." case .missingAttributeSalt: return "A salt attribute was missing." case .invalidAttributePadding: return "A padding attribute was not valid." case .missingAttributePadding: return "A padding attribute was missing." case .invalidAttributeRandom: return "A random number attribute was not valid." case .missingAttributeRandom: return "A random number attribute was missing." case .invalidAttributeSeed: return "A seed attribute was not valid." case .missingAttributeSeed: return "A seed attribute was missing." case .invalidAttributePassphrase: return "A passphrase attribute was not valid." case .missingAttributePassphrase: return "A passphrase attribute was missing." case .invalidAttributeKeyLength: return "A key length attribute was not valid." case .missingAttributeKeyLength: return "A key length attribute was missing." case .invalidAttributeBlockSize: return "A block size attribute was not valid." case .missingAttributeBlockSize: return "A block size attribute was missing." case .invalidAttributeOutputSize: return "An output size attribute was not valid." case .missingAttributeOutputSize: return "An output size attribute was missing." case .invalidAttributeRounds: return "The number of rounds attribute was not valid." case .missingAttributeRounds: return "The number of rounds attribute was missing." case .invalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case .missingAlgorithmParms: return "An algorithm parameters attribute was missing." case .invalidAttributeLabel: return "A label attribute was not valid." case .missingAttributeLabel: return "A label attribute was missing." case .invalidAttributeKeyType: return "A key type attribute was not valid." case .missingAttributeKeyType: return "A key type attribute was missing." case .invalidAttributeMode: return "A mode attribute was not valid." case .missingAttributeMode: return "A mode attribute was missing." case .invalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case .missingAttributeEffectiveBits: return "An effective bits attribute was missing." case .invalidAttributeStartDate: return "A start date attribute was not valid." case .missingAttributeStartDate: return "A start date attribute was missing." case .invalidAttributeEndDate: return "An end date attribute was not valid." case .missingAttributeEndDate: return "An end date attribute was missing." case .invalidAttributeVersion: return "A version attribute was not valid." case .missingAttributeVersion: return "A version attribute was missing." case .invalidAttributePrime: return "A prime attribute was not valid." case .missingAttributePrime: return "A prime attribute was missing." case .invalidAttributeBase: return "A base attribute was not valid." case .missingAttributeBase: return "A base attribute was missing." case .invalidAttributeSubprime: return "A subprime attribute was not valid." case .missingAttributeSubprime: return "A subprime attribute was missing." case .invalidAttributeIterationCount: return "An iteration count attribute was not valid." case .missingAttributeIterationCount: return "An iteration count attribute was missing." case .invalidAttributeDLDBHandle: return "A database handle attribute was not valid." case .missingAttributeDLDBHandle: return "A database handle attribute was missing." case .invalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case .missingAttributeAccessCredentials: return "An access credentials attribute was missing." case .invalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case .missingAttributePublicKeyFormat: return "A public key format attribute was missing." case .invalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case .missingAttributePrivateKeyFormat: return "A private key format attribute was missing." case .invalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case .missingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case .invalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case .missingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case .stagedOperationInProgress: return "A staged operation is in progress." case .stagedOperationNotStarted: return "A staged operation was not started." case .verifyFailed: return "A cryptographic verification failure has occurred." case .querySizeUnknown: return "The query size is unknown." case .blockSizeMismatch: return "A block size mismatch occurred." case .publicKeyInconsistent: return "The public key was inconsistent." case .deviceVerifyFailed: return "A device verification failure has occurred." case .invalidLoginName: return "An invalid login name was detected." case .alreadyLoggedIn: return "The user is already logged in." case .invalidDigestAlgorithm: return "An invalid digest algorithm was detected." case .invalidCRLGroup: return "An invalid CRL group was detected." case .certificateCannotOperate: return "The certificate cannot operate." case .certificateExpired: return "An expired certificate was detected." case .certificateNotValidYet: return "The certificate is not yet valid." case .certificateRevoked: return "The certificate was revoked." case .certificateSuspended: return "The certificate was suspended." case .insufficientCredentials: return "Insufficient credentials were detected." case .invalidAction: return "The action was not valid." case .invalidAuthority: return "The authority was not valid." case .verifyActionFailed: return "A verify action has failed." case .invalidCertAuthority: return "The certificate authority was not valid." case .invaldCRLAuthority: return "The CRL authority was not valid." case .invalidCRLEncoding: return "The CRL encoding was not valid." case .invalidCRLType: return "The CRL type was not valid." case .invalidCRL: return "The CRL was not valid." case .invalidFormType: return "The form type was not valid." case .invalidID: return "The ID was not valid." case .invalidIdentifier: return "The identifier was not valid." case .invalidIndex: return "The index was not valid." case .invalidPolicyIdentifiers: return "The policy identifiers are not valid." case .invalidTimeString: return "The time specified was not valid." case .invalidReason: return "The trust policy reason was not valid." case .invalidRequestInputs: return "The request inputs are not valid." case .invalidResponseVector: return "The response vector was not valid." case .invalidStopOnPolicy: return "The stop-on policy was not valid." case .invalidTuple: return "The tuple was not valid." case .multipleValuesUnsupported: return "Multiple values are not supported." case .notTrusted: return "The trust policy was not trusted." case .noDefaultAuthority: return "No default authority was detected." case .rejectedForm: return "The trust policy had a rejected form." case .requestLost: return "The request was lost." case .requestRejected: return "The request was rejected." case .unsupportedAddressType: return "The address type is not supported." case .unsupportedService: return "The service is not supported." case .invalidTupleGroup: return "The tuple group was not valid." case .invalidBaseACLs: return "The base ACLs are not valid." case .invalidTupleCredendtials: return "The tuple credentials are not valid." case .invalidEncoding: return "The encoding was not valid." case .invalidValidityPeriod: return "The validity period was not valid." case .invalidRequestor: return "The requestor was not valid." case .requestDescriptor: return "The request descriptor was not valid." case .invalidBundleInfo: return "The bundle information was not valid." case .invalidCRLIndex: return "The CRL index was not valid." case .noFieldValues: return "No field values were detected." case .unsupportedFieldFormat: return "The field format is not supported." case .unsupportedIndexInfo: return "The index information is not supported." case .unsupportedLocality: return "The locality is not supported." case .unsupportedNumAttributes: return "The number of attributes is not supported." case .unsupportedNumIndexes: return "The number of indexes is not supported." case .unsupportedNumRecordTypes: return "The number of record types is not supported." case .fieldSpecifiedMultiple: return "Too many fields were specified." case .incompatibleFieldFormat: return "The field format was incompatible." case .invalidParsingModule: return "The parsing module was not valid." case .databaseLocked: return "The database is locked." case .datastoreIsOpen: return "The data store is open." case .missingValue: return "A missing value was detected." case .unsupportedQueryLimits: return "The query limits are not supported." case .unsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case .unsupportedOperator: return "The operator is not supported." case .invalidDBLocation: return "The database location is not valid." case .invalidAccessRequest: return "The access request is not valid." case .invalidIndexInfo: return "The index information is not valid." case .invalidNewOwner: return "The new owner is not valid." case .invalidModifyMode: return "The modify mode is not valid." case .missingRequiredExtension: return "A required certificate extension is missing." case .extendedKeyUsageNotCritical: return "The extended key usage extension was not marked critical." case .timestampMissing: return "A timestamp was expected but was not found." case .timestampInvalid: return "The timestamp was not valid." case .timestampNotTrusted: return "The timestamp was not trusted." case .timestampServiceNotAvailable: return "The timestamp service is not available." case .timestampBadAlg: return "An unrecognized or unsupported Algorithm Identifier in timestamp." case .timestampBadRequest: return "The timestamp transaction is not permitted or supported." case .timestampBadDataFormat: return "The timestamp data submitted has the wrong format." case .timestampTimeNotAvailable: return "The time source for the Timestamp Authority is not available." case .timestampUnacceptedPolicy: return "The requested policy is not supported by the Timestamp Authority." case .timestampUnacceptedExtension: return "The requested extension is not supported by the Timestamp Authority." case .timestampAddInfoNotAvailable: return "The additional information requested is not available." case .timestampSystemFailure: return "The timestamp request cannot be handled due to system failure." case .signingTimeMissing: return "A signing time was expected but was not found." case .timestampRejection: return "A timestamp transaction was rejected." case .timestampWaiting: return "A timestamp transaction is waiting." case .timestampRevocationWarning: return "A timestamp authority revocation warning was issued." case .timestampRevocationNotification: return "A timestamp authority revocation notification was issued." case .unexpectedError: return "Unexpected error has occurred." } } }
mit
grafiti-io/SwiftCharts
SwiftCharts/Views/ChartLinesView.swift
3
3122
// // ChartLinesView.swift // swift_charts // // Created by ischuetz on 11/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public protocol ChartLinesViewPathGenerator { func generatePath(points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath } open class ChartLinesView: UIView { open let lineColor: UIColor open let lineWidth: CGFloat open let lineJoin: LineJoin open let lineCap: LineCap open let animDuration: Float open let animDelay: Float open let dashPattern: [Double]? public init(path: UIBezierPath, frame: CGRect, lineColor: UIColor, lineWidth: CGFloat, lineJoin: LineJoin, lineCap: LineCap, animDuration: Float, animDelay: Float, dashPattern: [Double]?) { self.lineColor = lineColor self.lineWidth = lineWidth self.lineJoin = lineJoin self.lineCap = lineCap self.animDuration = animDuration self.animDelay = animDelay self.dashPattern = dashPattern super.init(frame: frame) backgroundColor = UIColor.clear show(path: path) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func createLineMask(frame: CGRect) -> CALayer { let lineMaskLayer = CAShapeLayer() var maskRect = frame maskRect.origin.y = 0 maskRect.size.height = frame.size.height let path = CGPath(rect: maskRect, transform: nil) lineMaskLayer.path = path return lineMaskLayer } open func generateLayer(path: UIBezierPath) -> CAShapeLayer { let lineLayer = CAShapeLayer() lineLayer.lineJoin = lineJoin.CALayerString lineLayer.lineCap = lineCap.CALayerString lineLayer.fillColor = UIColor.clear.cgColor lineLayer.lineWidth = lineWidth lineLayer.path = path.cgPath lineLayer.strokeColor = lineColor.cgColor if dashPattern != nil { lineLayer.lineDashPattern = dashPattern as [NSNumber]? } if animDuration > 0 { lineLayer.strokeEnd = 0.0 let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = CFTimeInterval(animDuration) pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathAnimation.fromValue = NSNumber(value: 0 as Float) pathAnimation.toValue = NSNumber(value: 1 as Float) pathAnimation.autoreverses = false pathAnimation.isRemovedOnCompletion = false pathAnimation.fillMode = kCAFillModeForwards pathAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay) lineLayer.add(pathAnimation, forKey: "strokeEndAnimation") } else { lineLayer.strokeEnd = 1 } return lineLayer } fileprivate func show(path: UIBezierPath) { layer.addSublayer(generateLayer(path: path)) } }
apache-2.0
keencode/SwiftValidator
ValidatorTests/ValidatorTests.swift
1
4306
// // ValidatorTests.swift // ValidatorTests // // Created by Jeff Potter on 11/20/14. // Copyright (c) 2014 jpotts18. All rights reserved. // import UIKit import XCTest import Validator class ValidatorTests: XCTestCase { let USERNAME_REGEX = "^[a-z0-9_-]{3,16}$" let VALID_ZIP = "12345" let INVALID_ZIP = "1234" let VALID_EMAIL = "jiggy@gmail.com" let INVALID_EMAIL = "This is not a valid email" let CONFIRM_TXT_FIELD = UITextField() let CONFIRM_TEXT = "Confirm this!" let CONFIRM_TEXT_DIFF = "I am not the same as the string above" let VALID_PASSWORD = "Super$ecret" let INVALID_PASSWORD = "abc" let LEN_3 = "hey" let LEN_5 = "Howdy" let LEN_20 = "Paint the cat orange" override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: Required func testRequired() { XCTAssertTrue(RequiredRule().validate("Something"), "Required should be valid") } func testRequiredInvalid() { XCTAssertFalse(RequiredRule().validate(""), "Required should be invalid") } // MARK: Regex func testRegex(){ XCTAssertTrue(RegexRule(regex: USERNAME_REGEX).validate("darth_vader8"), "RegexRule should be valid") } func testRegexInvalid(){ XCTAssertFalse(RegexRule(regex: USERNAME_REGEX).validate("DarthVader"), "RegexRule should be invalid") } // MARK: Zipcode func testZipCode() { XCTAssertTrue(ZipCodeRule().validate(VALID_ZIP), "Zipcode should be valid") } func testZipCodeInvalid() { XCTAssertFalse(ZipCodeRule().validate(INVALID_ZIP), "Zipcode should be invalid") } // MARK: Email func testEmail() { XCTAssertTrue(EmailRule().validate(VALID_EMAIL), "Email should be valid") } func testEmailInvalid() { XCTAssertFalse(EmailRule().validate(INVALID_EMAIL), "Email should be invalid") } // MARK: Confirm against field func testConfirmSame(){ CONFIRM_TXT_FIELD.text = CONFIRM_TEXT XCTAssertTrue(ConfirmationRule(confirmField: CONFIRM_TXT_FIELD).validate(CONFIRM_TEXT), "Should confirm successfully") } func testConfirmDifferent() { CONFIRM_TXT_FIELD.text = CONFIRM_TEXT XCTAssertFalse(ConfirmationRule(confirmField: CONFIRM_TXT_FIELD).validate(CONFIRM_TEXT_DIFF), "Should fail confirm") } // MARK: Password func testPassword() { XCTAssertTrue(PasswordRule().validate(VALID_PASSWORD), "Password should be valid") } func testPasswordInvalid(){ XCTAssertFalse(EmailRule().validate(INVALID_PASSWORD), "Password is invalid") } // MARK: Max Length func testMaxLength(){ XCTAssertTrue(MaxLengthRule().validate(LEN_3),"Max Length should be valid") } func testMaxLengthInvalid(){ XCTAssertFalse(MaxLengthRule().validate(LEN_20),"Max Length should be invalid") } func testMaxLengthParameterAndGreaterThan(){ XCTAssertTrue(MaxLengthRule(length: 20).validate(LEN_20), "Max Length should be 20 and <= length") } // MARK: Min Length func testMinLength(){ XCTAssertTrue(MinLengthRule().validate(LEN_3),"Min Length should be valid") } func testMinLengthInvalid(){ XCTAssertFalse(MinLengthRule().validate("no"),"Min Length should be Invalid") } func testMinLengthWithParameter(){ XCTAssertTrue(MinLengthRule(length: 5).validate(LEN_5), "Min Len should be set to 5 and >= length") } // MARK: Full Name func testFullName(){ XCTAssertTrue(FullNameRule().validate("Jeff Potter"), "Full Name should be valid") } func testFullNameWith3Names(){ XCTAssertTrue(FullNameRule().validate("Jeff Van Buren"), "Full Name should be valid") } func testFullNameInvalid(){ XCTAssertFalse(FullNameRule().validate("Carl"), "Full Name should be invalid") } }
mit
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Places/Country.swift
1
6269
// // Country.swift // // // Created by Vladislav Fitc on 12/04/2020. // // swiftlint:disable type_body_length import Foundation public enum Country: String, Codable { case afghanistan = "af" case alandIslands = "ax" case albania = "al" case algeria = "dz" case americanSamoa = "as" case andorra = "ad" case angola = "ao" case anguilla = "ai" case antarctica = "aq" case antiguaAndBarbuda = "ag" case argentina = "ar" case armenia = "am" case aruba = "aw" case australia = "au" case austria = "at" case azerbaijan = "az" case bahamas = "bs" case bahrain = "bh" case bangladesh = "bd" case barbados = "bb" case belarus = "by" case belgium = "be" case belize = "bz" case benin = "bj" case bermuda = "bm" case bhutan = "bt" case bolivia = "bo" case caribbeanNetherlands = "bq" case bosniaAndHerzegovina = "ba" case botswana = "bw" case bouvetIsland = "bv" case brazil = "br" case britishIndianOceanTerritory = "io" case bruneiDarussalam = "bn" case bulgaria = "bg" case burkinaFaso = "bf" case burundi = "bi" case caboVerde = "cv" case cambodia = "kh" case cameroon = "cm" case canada = "ca" case caymanIslands = "ky" case centralAfricanRepublic = "cf" case chad = "td" case chile = "cl" case china = "cn" case christmasIsland = "cx" case cocosIslands = "cc" case colombia = "co" case comoros = "km" case republicOfTheCongo = "cg" case democraticRepublicOfTheCongo = "cd" case cookIslands = "ck" case costaRica = "cr" case ivoryCoast = "ci" case croatia = "hr" case cuba = "cu" case curacao = "cw" case cyprus = "cy" case czechRepublic = "cz" case denmark = "dk" case djibouti = "dj" case dominica = "dm" case dominicanRepublic = "do" case ecuador = "ec" case egypt = "eg" case elSalvador = "sv" case equatorialGuinea = "gq" case eritrea = "er" case estonia = "ee" case eswatini = "sz" case ethiopia = "et" case falklandIslands = "fk" case faroeIslands = "fo" case fiji = "fj" case finland = "fi" case france = "fr" case frenchGuiana = "gf" case frenchPolynesia = "pf" case frenchSouthernAndAntarcticLands = "tf" case gabon = "ga" case gambia = "gm" case georgia = "ge" case germany = "de" case ghana = "gh" case gibraltar = "gi" case greece = "gr" case greenland = "gl" case grenada = "gd" case guadeloupe = "gp" case guam = "gu" case guatemala = "gt" case bailiwickOfGuernsey = "gg" case guinea = "gn" case guineaBissau = "gw" case guyana = "gy" case haiti = "ht" case heardIslandAndMcDonaldIslands = "hm" case vaticanCity = "va" case honduras = "hn" case hongKong = "hk" case hungary = "hu" case iceland = "is" case india = "in" case indonesia = "id" case iran = "ir" case iraq = "iq" case ireland = "ie" case isleOfMan = "im" case israel = "il" case italy = "it" case jamaica = "jm" case japan = "jp" case jersey = "je" case jordan = "jo" case kazakhstan = "kz" case kenya = "ke" case kiribati = "ki" case northKorea = "kp" case southKorea = "kr" case kuwait = "kw" case kyrgyzstan = "kg" case laos = "la" case latvia = "lv" case lebanon = "lb" case lesotho = "ls" case liberia = "lr" case libya = "ly" case liechtenstein = "li" case lithuania = "lt" case luxembourg = "lu" case macau = "mo" case madagascar = "mg" case malawi = "mw" case malaysia = "my" case maldives = "mv" case mali = "ml" case malta = "mt" case marshallIslands = "mh" case martinique = "mq" case mauritania = "mr" case mauritius = "mu" case mayotte = "yt" case mexico = "mx" case micronesia = "fm" case moldova = "md" case monaco = "mc" case mongolia = "mn" case montenegro = "me" case montserrat = "ms" case morocco = "ma" case mozambique = "mz" case myanmar = "mm" case namibia = "na" case nauru = "nr" case nepal = "np" case netherlands = "nl" case newCaledonia = "nc" case newZealand = "nz" case nicaragua = "ni" case niger = "ne" case nigeria = "ng" case niue = "nu" case norfolkIsland = "nf" case northMacedonia = "mk" case northernMarianaIslands = "mp" case norway = "no" case oman = "om" case pakistan = "pk" case palau = "pw" case palestine = "ps" case panama = "pa" case papuaNewGuinea = "pg" case paraguay = "py" case peru = "pe" case philippines = "ph" case pitcairnIslands = "pn" case poland = "pl" case portugal = "pt" case puertoRico = "pr" case qatar = "qa" case reunion = "re" case romania = "ro" case russia = "ru" case rwanda = "rw" case saintBarthelemy = "bl" case saintHelena = "sh" case saintKittsAndNevis = "kn" case saintLucia = "lc" case saintMartin = "mf" case saintPierreAndMiquelon = "pm" case saintVincentAndTheGrenadines = "vc" case samoa = "ws" case sanMarino = "sm" case saoTomeAndPrincipe = "st" case saudiArabia = "sa" case senegal = "sn" case serbia = "rs" case seychelles = "sc" case sierraLeone = "sl" case singapore = "sg" case sintMaarten = "sx" case slovakia = "sk" case slovenia = "si" case solomonIslands = "sb" case somalia = "so" case southAfrica = "za" case southGeorgiaAndTheSouthSandwichIslands = "gs" case southSudan = "ss" case spain = "es" case sriLanka = "lk" case sudan = "sd" case suriname = "sr" case svalbardAndJanMayen = "sj" case sweden = "se" case switzerland = "ch" case syria = "sy" case taiwan = "tw" case tajikistan = "tj" case tanzania = "tz" case thailand = "th" case timorLeste = "tl" case togo = "tg" case tokelau = "tk" case tonga = "to" case trinidadAndTobago = "tt" case tunisia = "tn" case turkey = "tr" case turkmenistan = "tm" case turksAndCaicosIslands = "tc" case tuvalu = "tv" case uganda = "ug" case ukraine = "ua" case unitedArabEmirates = "ae" case unitedKingdom = "gb" case unitedStates = "us" case unitedStatesMinorOutlyingIslands = "um" case uruguay = "uy" case uzbekistan = "uz" case vanuatu = "vu" case venezuela = "ve" case vietnam = "vn" case virginIslandsGB = "vg" case virginIslandsUS = "vi" case wallisAndFutuna = "wf" case westernSahara = "eh" case yemen = "ye" case zambia = "zm" case zimbabwe = "zw" }
mit
apple/swift-nio
Sources/NIOPerformanceTester/ByteBufferWriteMultipleBenchmarks.swift
1
2653
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore final class ByteBufferReadWriteMultipleIntegersBenchmark<I: FixedWidthInteger>: Benchmark { private let iterations: Int private let numberOfInts: Int private var buffer: ByteBuffer = ByteBuffer() init(iterations: Int, numberOfInts: Int) { self.iterations = iterations self.numberOfInts = numberOfInts } func setUp() throws { self.buffer.reserveCapacity(self.numberOfInts * MemoryLayout<I>.size) } func tearDown() { } func run() throws -> Int { var result: I = 0 for _ in 0..<self.iterations { for i in I(0)..<I(10) { self.buffer.writeInteger(i) } for _ in I(0)..<I(10) { result = result &+ self.buffer.readInteger(as: I.self)! } } precondition(result == I(self.iterations) * 45) return self.buffer.readableBytes } } final class ByteBufferMultiReadWriteTenIntegersBenchmark<I: FixedWidthInteger>: Benchmark { private let iterations: Int private var buffer: ByteBuffer = ByteBuffer() init(iterations: Int) { self.iterations = iterations } func setUp() throws { self.buffer.reserveCapacity(10 * MemoryLayout<I>.size) } func tearDown() { } func run() throws -> Int { var result: I = 0 for _ in 0..<self.iterations { self.buffer.writeMultipleIntegers( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, as: (I, I, I, I, I, I, I, I, I, I).self ) let value = self.buffer.readMultipleIntegers(as: (I, I, I, I, I, I, I, I, I, I).self)! result = result &+ value.0 result = result &+ value.1 result = result &+ value.2 result = result &+ value.3 result = result &+ value.4 result = result &+ value.5 result = result &+ value.6 result = result &+ value.7 result = result &+ value.8 result = result &+ value.9 } precondition(result == I(self.iterations) * 45) return self.buffer.readableBytes } }
apache-2.0
Candyroot/DesignPattern
state/state/GumballMachine.swift
1
1710
// // GumballMachine.swift // state // // Created by Bing Liu on 12/2/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Foundation class GumballMachine { let soldOutState: State! let noQuarterState: State! let hasQuarterState: State! let soldState: State! let winnerState: State! var state: State! var count = 0 var description: String { let desc = "\nMighty Gumball, Inc.\n" + "Swift-enabled Standing Gumball Model #2014\n" + "Inventory: \(count) gumballs\n" return count > 0 ? (desc + "Machine is waiting for quarter\n") : (desc + "Machine is sold out") } init(numberGumballs: Int) { soldOutState = SoldOutState(gumballMachine: self) noQuarterState = NoQuarterState(gumballMachine: self) hasQuarterState = HasQuarterState(gumballMachine: self) soldState = SoldState(gumballMachine: self) winnerState = WinnerState(gumballMachine: self) count = numberGumballs if numberGumballs > 0 { state = noQuarterState } else { state = soldOutState } } func insertQuarter() { state.insertQuarter() } func ejectQuarter() { state.ejectQuarter() } func turnCrank() { state.turnCrank() state.dispense() } func setState(state: State) { self.state = state } func releaseBall() { println("A gumball comes rolling out the slot...") if count != 0 { count-- } } func refill(count: Int) { self.count = count state = noQuarterState } }
apache-2.0
S2dentik/Taylor
Taylor/main.swift
4
168
// // main.swift // Taylor // // Created by Andrei Raifura on 9/3/15. // Copyright (c) 2015 YOPESO. All rights reserved. // import TaylorFramework Taylor().run()
mit
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/Ex/Character.swift
31
402
// // Character.swift // ExSwift // // Created by Cenny Davidsson on 2014-12-08. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Character { /** If the character represents an integer that fits into an Int, returns the corresponding integer. */ public func toInt () -> Int? { return String(self).toInt() } }
gpl-2.0
tsaqib/samples
backgroundExtensionDemo/backgroundExtensionDemo/ViewController.swift
1
932
// // ViewController.swift // backgroundExtensionDemo // // Created by Tanzim Saqib on 10/27/15. // Copyright © 2015 Tanzim Saqib. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imgView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSelect(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: BlurExtraLight(imgView) case 1: BlurLight(imgView) case 2: BlurDark(imgView) case 3: BlurReset() default: print("Invalid option") } } }
mit
sora0077/iTunesKit
iTunesKit/src/Endpoint/Lookup.swift
1
5880
// // Lookup.swift // iTunesKit // // Created by 林達也 on 2015/10/06. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation import APIKit public struct Lookup { public private(set) var parameters: [String: AnyObject]? = [:] public init(id: Int, country: String = "US") { parameters?["id"] = id parameters?["country"] = country } } extension Lookup: iTunesRequestToken { public typealias Response = [SearchResult] public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .GET } public var path: String { return "https://itunes.apple.com/lookup" } public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { print(request, object) return (object["results"] as! [[String: AnyObject]]).map { v in guard let wrapperType = SearchResultWrapperType(rawValue: v["wrapperType"] as! String) else { return .Unsupported(v) } switch wrapperType { case .Track: return .Track(SearchResultTrack( kind: SearchResultKind(rawValue: v["kind"] as! String)!, artistId: v["artistId"] as! Int, collectionId: v["collectionId"] as! Int, trackId: v["trackId"] as! Int, artistName: v["artistName"] as! String, collectionName: v["collectionName"] as! String, trackName: v["trackName"] as! String, collectionCensoredName: v["collectionCensoredName"] as! String, trackCensoredName: v["trackCensoredName"] as! String, artistViewUrl: v["artistViewUrl"] as! String, collectionViewUrl: v["collectionViewUrl"] as! String, trackViewUrl: v["trackViewUrl"] as! String, previewUrl: v["previewUrl"] as! String, artworkUrl30: v["artworkUrl30"] as! String, artworkUrl60: v["artworkUrl60"] as! String, artworkUrl100: v["artworkUrl100"] as! String, collectionPrice: v["collectionPrice"] as! Float, trackPrice: v["trackPrice"] as! Float, releaseDate: v["releaseDate"] as! String, collectionExplicitness: v["collectionExplicitness"] as! String, trackExplicitness: v["trackExplicitness"] as! String, discCount: v["discCount"] as! Int, discNumber: v["discNumber"] as! Int, trackCount: v["trackCount"] as! Int, trackNumber: v["trackNumber"] as! Int, trackTimeMillis: v["trackTimeMillis"] as! Int, country: v["country"] as! String, currency: v["currency"] as! String, primaryGenreName: v["primaryGenreName"] as! String, radioStationUrl: v["radioStationUrl"] as? String, isStreamable: v["isStreamable"] as! Bool )) case .Artist: return .Artist(SearchResultArtist( artistType: v["artistType"] as! String, artistName: v["artistName"] as! String, artistLinkUrl: v["artistLinkUrl"] as! String, artistId: v["artistId"] as! Int, amgArtistId: v["amgArtistId"] as? Int, primaryGenreName: v["primaryGenreName"] as! String, primaryGenreId: v["primaryGenreId"] as! Int, radioStationUrl: v["radioStationUrl"] as? String )) case .Collection: return .Collection(SearchResultCollection( collectionType: v["collectionType"] as! String, artistId: v["artistId"] as! Int, collectionId: v["collectionId"] as! Int, amgArtistId: v["amgArtistId"] as! Int, artistName: v["artistName"] as! String, collectionName: v["collectionName"] as! String, collectionCensoredName: v["collectionCensoredName"] as! String, artistViewUrl: v["artistViewUrl"] as! String, collectionViewUrl: v["collectionViewUrl"] as! String, artworkUrl30: v["artworkUrl30"] as! String, artworkUrl60: v["artworkUrl60"] as! String, artworkUrl100: v["artworkUrl100"] as! String, collectionPrice: v["collectionPrice"] as! Float, collectionExplicitness: v["collectionExplicitness"] as! String, trackCount: v["trackCount"] as! Int, copyright: v["copyright"] as! String, country: v["country"] as! String, currency: v["currency"] as! String, releaseDate: v["releaseDate"] as! String, primaryGenreName: v["primaryGenreName"] as! String, radioStationUrl: v["radioStationUrl"] as? String )) } } } }
mit
TwilioDevEd/api-snippets
video/conversations/specify-constraints/specify-constraints.swift
2
677
// See the "Create a Conversation" guide for details of the acceptHandler ... outgoingInvite = self.client?.inviteToConversation("alice", localMedia: self.setupLocalMedia(), handler: self.acceptHandler) ... func setupLocalMedia() -> TWCLocalMedia { // Create LocalMedia with a camera track and no microphone track var localMedia = TWCLocalMedia(delegate: self) localMedia!.addCameraTrack() return localMedia! } // MARK: TWCLocalMediaDelegate extension ViewController: TWCLocalMediaDelegate { func localMedia(media: TWCLocalMedia, didAddVideoTrack videoTrack: TWCVideoTrack) { videoTrack.attach(self.localMediaView) } }
mit
SusanDoggie/Doggie
Sources/DoggieGeometry/ApplePlatform/Geometry/CGAffineTransform.swift
1
2569
// // CGAffineTransform.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(macOS) extension AffineTransform { @inlinable @inline(__always) public init(_ transform: SDTransform) { self.init( m11: CGFloat(transform.a), m12: CGFloat(transform.d), m21: CGFloat(transform.b), m22: CGFloat(transform.e), tX: CGFloat(transform.c), tY: CGFloat(transform.f) ) } } extension SDTransform { @inlinable @inline(__always) public init(_ m: AffineTransform) { self.a = Double(m.m11) self.b = Double(m.m21) self.c = Double(m.tX) self.d = Double(m.m12) self.e = Double(m.m22) self.f = Double(m.tY) } } #endif #if canImport(CoreGraphics) extension CGAffineTransform { @inlinable @inline(__always) public init(_ m: SDTransform) { self.init( a: CGFloat(m.a), b: CGFloat(m.d), c: CGFloat(m.b), d: CGFloat(m.e), tx: CGFloat(m.c), ty: CGFloat(m.f) ) } } extension SDTransform { @inlinable @inline(__always) public init(_ m: CGAffineTransform) { self.a = Double(m.a) self.b = Double(m.c) self.c = Double(m.tx) self.d = Double(m.b) self.e = Double(m.d) self.f = Double(m.ty) } } #endif
mit
zhuhaow/NEKit
src/GeoIP/GeoIP.swift
1
618
import Foundation import MMDB open class GeoIP { // Back in the days, MMDB ships a bundled GeoLite2 database. However, that has changed // due to license change of the database. Now developers must initialize it by themselves. // In order to maintain the API compatibility while expose the issue ASAP, we set the type // to `MMDB!` so it will crash during development if one forgets to initialize it. // Please initialize it first! public static var database: MMDB! public static func LookUp(_ ipAddress: String) -> MMDBCountry? { return GeoIP.database.lookup(ipAddress) } }
bsd-3-clause
devxoul/MoyaSugar
Package.swift
1
721
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "MoyaSugar", platforms: [ .macOS(.v10_12), .iOS(.v10), .tvOS(.v10), .watchOS(.v3) ], products: [ .library(name: "MoyaSugar", targets: ["MoyaSugar"]), ], dependencies: [ .package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "14.0.0-beta.2")), .package(url: "https://github.com/devxoul/Immutable.git", .upToNextMajor(from: "0.5.0")), .package(url: "https://github.com/devxoul/Then.git", .upToNextMajor(from: "2.2.0")), ], targets: [ .target(name: "MoyaSugar", dependencies: ["Moya"]), .testTarget(name: "MoyaSugarTests", dependencies: ["MoyaSugar", "Immutable", "Then"]), ] )
mit
mohamede1945/quran-ios
Quran/Errors+Description.swift
2
2439
// // Errors+Description.swift // Quran // // Created by Mohamed Afifi on 4/28/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import BatchDownloader import SQLitePersistence extension FileSystemError: LocalizedError { public var errorDescription: String { let text: String switch self { case .unknown: text = NSLocalizedString("FileSystemError_Unknown", comment: "") case .noDiskSpace: text = NSLocalizedString("FileSystemError_NoDiskSpace", comment: "") } return text } } extension NetworkError: LocalizedError { public var errorDescription: String { let text: String switch self { case .unknown: text = NSLocalizedString("unknown_error_message", comment: "Error description") case .serverError: text = NSLocalizedString("unknown_error_message", comment: "Error description") case .notConnectedToInternet: text = NSLocalizedString("NetworkError_NotConnectedToInternet", comment: "Error description") case .internationalRoamingOff: text = NSLocalizedString("NetworkError_InternationalRoamingOff", comment: "Error description") case .serverNotReachable: text = NSLocalizedString("NetworkError_ServerNotReachable", comment: "Error description") case .connectionLost: text = NSLocalizedString("NetworkError_ConnectionLost", comment: "Error description") } return text } } extension ParsingError: LocalizedError { public var errorDescription: String { return NSLocalizedString("NetworkError_Parsing", comment: "When a parsing error occurs") } } extension PersistenceError: LocalizedError { public var errorDescription: String { return NSLocalizedString("unknown_error_message", comment: "") } }
gpl-3.0
jcantosm/coursera.ios
mediaplayer/mediaplayer/ViewController.swift
1
4784
// // ViewController.swift // audioplayer // // Created by Javier Cantos on 23/12/15. // Copyright © 2015 Javier Cantos. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var player : AVAudioPlayer! var canciones : Array<Array<String>> = Array<Array<String>>() @IBOutlet weak var uiLabelTitulo: UILabel! @IBOutlet weak var uiImgPortada: UIImageView! @IBOutlet weak var uiPickerCanciones: UIPickerView! @IBOutlet weak var uiControlAudio: UISegmentedControl! @IBOutlet weak var uiSliderVolumen: UISlider! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // inicializamos lista de canciones self.canciones.append(["Amor Es Solo Amar", "PALABRAMUJER.PNG", "AmarEsSoloAmor"]) self.canciones.append(["El Despertar", "ADAGIO.PNG", "ElDespertar"]) self.canciones.append(["Pantera En Libertad", "MONICA4.0.PNG", "PanteraEnLibertad"]) self.canciones.append(["Chicas Malas", "CHICASMALAS.PNG", "ChicasMalas"]) self.canciones.append(["Sobreviviré", "MINAGE.PNG", "Sobrevivire"]) let cancionURL = NSBundle.mainBundle().URLForResource(self.canciones[0][2], withExtension: "mp3") do { try self.player = AVAudioPlayer(contentsOfURL: cancionURL!) // volumen x defecto del reproductor self.player.volume = self.uiSliderVolumen.value // mostramos titulo / portada cancion seleccionada self.uiLabelTitulo.text = self.canciones[0][0] self.uiImgPortada.image = UIImage(named: "media\(self.canciones[0][1])") } catch { print("Error al iniciar reproductor de audio.") } } 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 self.canciones.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.canciones[row][0] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let cancionURL = NSBundle.mainBundle().URLForResource(self.canciones[row][2], withExtension: "mp3") do { try self.player = AVAudioPlayer(contentsOfURL: cancionURL!) self.uiControlAudio.selectedSegmentIndex = 0 // mostramos titulo / portada cancion seleccionada self.uiLabelTitulo.text = self.canciones[row][0] self.uiImgPortada.image = UIImage(named: self.canciones[row][1]) // empezamos a reproducir la cancion seleccionada self.player.play() } catch { print("Error al iniciar reproductor de audio.") } } @IBAction func changeVolume() { self.player.volume = self.uiSliderVolumen.value } @IBAction func audiocontrol() { // iniciamos reproduccion de la cancion if (self.uiControlAudio.selectedSegmentIndex == 0) { print("play()") if (self.player != nil && !self.player.playing) { self.player.play() } } // pausamos reproduccion de la cancion if (self.uiControlAudio.selectedSegmentIndex == 1) { print("pause()") if (self.player != nil && self.player.playing) { self.player.pause() } } // paramos reproduccion de la cancion if (self.uiControlAudio.selectedSegmentIndex == 2) { print("stop()") if (self.player != nil && self.player.playing) { self.player.stop() self.player.currentTime = 0 } } // reproducción aleatoria de la cancion if (self.uiControlAudio.selectedSegmentIndex == 3) { print("shuffle()") // numero aleatorio let random : Int = Int(arc4random() % 5) // seleccion aleatoria de cancion self.uiPickerCanciones.selectRow(random, inComponent: 0, animated: true) self.pickerView(self.uiPickerCanciones, didSelectRow: random, inComponent: 0) } } }
apache-2.0
royhsu/RHAnimatedTitleView
Example/RHAnimatedTitleViewTests/RHAnimatedTitleViewTests.swift
1
935
// // RHAnimatedTitleViewTests.swift // RHAnimatedTitleViewTests // // Created by Roy Hsu on 2015/3/31. // Copyright (c) 2015年 tinyWorld. All rights reserved. // import UIKit import XCTest class RHAnimatedTitleViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
nshetty26/MH4UDatabase
MH4UDBEngine.swift
1
1999
// // MH4UDBEngine.swift // MH4UDatabase // // Created by Neil Shetty on 3/27/15. // Copyright (c) 2015 GuthuDesigns. All rights reserved. // import Foundation func dbQuery(query : String) -> FMResultSet? { let mh4uDB = FMDatabase(path: NSBundle.mainBundle().pathForResource("mh4u", ofType: ".db")); if !mh4uDB.open() { return nil; } else { return mh4uDB.executeQuery(query, withArgumentsInArray: nil); } } func retrieveMonsters(monsterID : Int?) -> NSArray { var monsterArray: [Monster] = []; var query : String; if (monsterID != nil) { query = "SELECT * FROM Monsters where monsters._id = \(monsterID)"; } else { query = "SELECT * FROM Monsters"; } if let s = dbQuery(query) { while (s.next()) { var monster = Monster(); monster.monsterID = s.intForColumn("_id"); monster.monsterClass = s.stringForColumn("class"); monster.monsterName = s.stringForColumn("name"); monster.trait = s.stringForColumn("trait") monster.iconName = s.stringForColumn("icon_name"); monsterArray.append(monster); } } monsterArray.sort({$0.monsterName < $1.monsterName}); return monsterArray; } func retrieveMonsterDamageForMonster(monster : Monster) { var damageArray : [MonsterDamage] = []; // MonsterDamage *md = [[MonsterDamage alloc] init]; // md.bodyPart = [s stringForColumn:@"body_part"]; // md.cutDamage = [s intForColumn:@"cut"]; // md.impactDamage = [s intForColumn:@"impact"]; // md.shotDamage = [s intForColumn:@"shot"]; // md.fireDamage = [s intForColumn:@"fire"]; // md.waterDamage = [s intForColumn:@"water"]; // md.iceDamage = [s intForColumn:@"ice"]; // md.thunderDamage = md.cutDamage = [s intForColumn:@"thunder"]; // md.dragonDamage = [s intForColumn:@"dragon"]; // md.stun = [s intForColumn:@"ko"]; // [monsterDamageArray addObject:md]; }
mit
kesara/ios-calculator
Calculator/AppDelegate.swift
1
2175
// // AppDelegate.swift // Calculator // // Created by Kesara Rathnayake on 17/10/17. // Copyright © 2017 fq.nz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
ZeeQL/ZeeQL3
Tests/ZeeQLTests/CodeObjectModelTests.swift
1
2011
// // CodeObjectModelTests.swift // ZeeQL3 // // Created by Helge Hess on 13.12.17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // // // CodeEntityModelTests.swift // ZeeQL // // Created by Helge Hess on 28/02/17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // import XCTest @testable import ZeeQL class CodeObjectModelTests: XCTestCase { func testCodeObjectSchema() throws { class OGoObject : ActiveRecord { let objectVersion = Value.Int(column: "object_version", 0) } class Address : OGoObject, CodeObjectType { // Boxed values, annotated with Attribute information let id = Value.Int (column: "address_id") let dbStatus = Value.String(column: "db_status", width: 50) let companyId = Value.Int (column: "company_id") let type = Value.String(width: 50) // TODO: an enum? // TODO: We can do this, but we don't get automagic KVC then. let name1 : String? = nil let name2 : String? = nil let name3 : String? = nil let street : String? = nil let zip = Value.OptString(width: 50, nil) let zipcity : String? = nil let country : String? = nil let state : String? = nil let district : String? = nil // TODO // - This could be a 'fault'. //let person = ToOne<Person>() // auto: key: "company_id") static let entity : ZeeQL.Entity = CodeObjectEntity<Address>(table: "address") } let entity = Address.entity XCTAssertEqual(entity.externalName, "address") let attrs = entity.attributes XCTAssertEqual(attrs.count, 14) let pkeys = entity.primaryKeyAttributeNames XCTAssertNotNil(pkeys) XCTAssertEqual(pkeys?.count ?? -1, 1) XCTAssertEqual(pkeys?[0] ?? "", "id") } static var allTests = [ ( "testCodeObjectSchema", testCodeObjectSchema ) ] }
apache-2.0
zSOLz/viper-base
ViperBase/ViperBaseTests/Services/ServiceTest.swift
1
4242
// // ServiceTest.swift // ViperBaseTests // // Created by SOL on 28.04.17. // Copyright © 2017 SOL. All rights reserved. // import XCTest @testable import ViperBase class ServiceTest: XCTestCase { func testRegisteredInManagerMethod() { let customService = CustomServiceSubclassMock() let customManager = ServiceManager(parent: ServiceManager.general) customManager.register(service: customService) XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService) ServiceManager.general.register(service: customService) XCTAssertEqual(CustomServiceMock.registered(), customService) XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService) customManager.unregister(service: customService) XCTAssertEqual(CustomServiceMock.registered(), customService) XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService) ServiceManager.general.unregister(service: customService) } func testStartStopMethods() { let service = CustomServiceMock() XCTAssertFalse(service.isStarted) service.start() XCTAssertTrue(service.isStarted) service.stop() XCTAssertFalse(service.isStarted) } /* // Test for this method always fails: Unknown swift compiler bug. Maybe you can solve it :) func testIsRegisteredInManagerMethod() { let customSubclassService = CustomServiceMock() let customManager = ServiceManager(parent: ServiceManager.general) XCTAssertFalse(CustomServiceMock.isRegistered()) XCTAssertFalse(CustomServiceMock.isRegistered(inManager: customManager)) XCTAssertFalse(CustomServiceSubclassMock.isRegistered()) XCTAssertFalse(CustomServiceSubclassMock.isRegistered(inManager: customManager)) XCTAssertFalse(AnotherCustomServiceMock.isRegistered()) XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager)) customManager.register(service: customSubclassService) XCTAssertFalse(CustomServiceMock.isRegistered()) XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager)) XCTAssertFalse(CustomServiceSubclassMock.isRegistered()) XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager)) XCTAssertFalse(AnotherCustomServiceMock.isRegistered()) XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager)) ServiceManager.general.register(service: customSubclassService) XCTAssertTrue(CustomServiceMock.isRegistered()) XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager)) XCTAssertTrue(CustomServiceSubclassMock.isRegistered()) XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager)) XCTAssertFalse(AnotherCustomServiceMock.isRegistered()) XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager)) customManager.unregister(service: customSubclassService) XCTAssertTrue(CustomServiceMock.isRegistered()) XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager)) XCTAssertTrue(CustomServiceSubclassMock.isRegistered()) XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager)) XCTAssertFalse(AnotherCustomServiceMock.isRegistered()) XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager)) ServiceManager.general.unregister(service: customSubclassService) XCTAssertFalse(CustomServiceMock.isRegistered()) XCTAssertFalse(CustomServiceMock.isRegistered(inManager: customManager)) XCTAssertFalse(CustomServiceSubclassMock.isRegistered()) XCTAssertFalse(CustomServiceSubclassMock.isRegistered(inManager: customManager)) XCTAssertFalse(AnotherCustomServiceMock.isRegistered()) XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager)) } */ }
mit
systers/PowerUp
Powerup/AppStoreReviewManager.swift
1
1727
// // AppStoreReviewManager.swift // Powerup import Foundation import StoreKit enum AppStoreReviewManager { static let minimumReviewWorthyActionCount = 4 static func requestReviewIfAppropriate() { let defaults = UserDefaults.standard let bundle = Bundle.main // Read the current number of actions that the user has performed since the last requested review from the User Defaults. var actionCount = defaults.integer(forKey: .reviewWorthyActionCount) /* Note: This sample project uses an extension on UserDefaults to eliminate the need for using “stringly” typed keys when accessing values. This is a good practice to follow in order to avoid accidentally mistyping a key as it can cause hard-to-find bugs in your app. You can find this extension in UserDefaults+Key.swift. */ actionCount += 1 defaults.set(actionCount, forKey: .reviewWorthyActionCount) guard actionCount >= minimumReviewWorthyActionCount else { return } let bundleVersionKey = kCFBundleVersionKey as String let currentVersion = bundle.object(forInfoDictionaryKey: bundleVersionKey) as? String let lastVersion = defaults.string(forKey: .lastReviewRequestAppVersion) // Check if this is the first request for this version of the app before continuing. guard lastVersion == nil || lastVersion != currentVersion else { return } SKStoreReviewController.requestReview() // Reset the action count and store the current version in User Defaults so that you don’t request again on this version of the app. defaults.set(0, forKey: .reviewWorthyActionCount) defaults.set(currentVersion, forKey: .lastReviewRequestAppVersion) } }
gpl-2.0
borisyurkevich/ECAB
ECAB/GameMenuViewController.swift
1
6449
// // GameMenuViewController.swift // ECAB // // Created by Boris Yurkevich on 29/05/2021. // Copyright © 2021 Oliver Braddick and Jan Atkinson. All rights reserved. // import UIKit import os final class GameMenuViewController: UIViewController { weak var delelgate: GameMenuDelegate? @IBOutlet private weak var menuView: MenuView! @IBOutlet private weak var menuStrip: UIView! @IBOutlet private weak var backLabel: UILabel! @IBOutlet private weak var forwardLabel: UILabel! @IBOutlet private weak var skipLabel: UILabel! @IBOutlet private weak var pauseLabel: UILabel! private let borderWidth: CGFloat = 1.0 private let borderColor: CGColor = UIColor.darkGray.cgColor private var buttonColor: UIColor? private var activity: UIActivityIndicatorView? override func viewDidLoad() { super.viewDidLoad() addMenuBorders() setTextColor() menuView.delegate = self buttonColor = backLabel.backgroundColor } func toggleNavigationButtons(isEnabled: Bool) { forwardLabel.isEnabled = isEnabled backLabel.isEnabled = isEnabled skipLabel.isEnabled = isEnabled } func updatePauseButtonState(isHidden: Bool) { pauseLabel.isHidden = isHidden } func updateBackButtonTitle(_ title: String) { backLabel.text = title } func startAnimatingPauseButton() { pauseLabel.text = "" activity = UIActivityIndicatorView(style: .medium) guard let activity = activity else { return } activity.startAnimating() pauseLabel.addSubview(activity) activity.translatesAutoresizingMaskIntoConstraints = false activity.centerYAnchor.constraint(equalTo: pauseLabel.centerYAnchor).isActive = true activity.centerXAnchor.constraint(equalTo: pauseLabel.centerXAnchor).isActive = true } func stopAnimatingPauseButton() { activity?.removeFromSuperview() self.pauseLabel.text = "Pause" self.pauseLabel.textColor = UIColor.label } // MARK: - Private private func addMenuBorders() { backLabel.layer.borderWidth = borderWidth backLabel.layer.borderColor = borderColor forwardLabel.layer.borderWidth = borderWidth forwardLabel.layer.borderColor = borderColor skipLabel.layer.borderWidth = borderWidth skipLabel.layer.borderColor = borderColor pauseLabel.layer.borderWidth = borderWidth pauseLabel.layer.borderColor = borderColor } private func setTextColor() { backLabel.textColor = UIColor.label forwardLabel.textColor = UIColor.label skipLabel.textColor = UIColor.label pauseLabel.textColor = UIColor.label } } extension GameMenuViewController: MenuViewDelegate { func reset(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { backLabel.backgroundColor = buttonColor backLabel.textColor = UIColor.label } else if location.x < skipLabel.frame.origin.x { forwardLabel.backgroundColor = buttonColor forwardLabel.textColor = UIColor.label } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { skipLabel.backgroundColor = buttonColor skipLabel.textColor = UIColor.label } else if location.x >= pauseLabel.frame.origin.x { pauseLabel.backgroundColor = buttonColor pauseLabel.textColor = UIColor.label } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } func highlight(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { if backLabel.isEnabled { backLabel.backgroundColor = view.tintColor backLabel.textColor = UIColor.lightText } } else if location.x < skipLabel.frame.origin.x { if forwardLabel.isEnabled { forwardLabel.backgroundColor = view.tintColor forwardLabel.textColor = UIColor.lightText } } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { if skipLabel.isEnabled { skipLabel.backgroundColor = view.tintColor skipLabel.textColor = UIColor.lightText } } else if location.x >= pauseLabel.frame.origin.x { if pauseLabel.isEnabled { pauseLabel.backgroundColor = view.tintColor pauseLabel.textColor = UIColor.lightText } } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } func handleTouch(location: CGPoint) { DispatchQueue.main.async { [unowned self] in if location.x < forwardLabel.frame.origin.x { if backLabel.isEnabled { backLabel.backgroundColor = buttonColor backLabel.textColor = UIColor.label delelgate?.presentPreviousScreen() } } else if location.x < skipLabel.frame.origin.x { if forwardLabel.isEnabled { forwardLabel.backgroundColor = buttonColor forwardLabel.textColor = UIColor.label delelgate?.presentNextScreen() } } else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width { if skipLabel.isEnabled { skipLabel.backgroundColor = buttonColor skipLabel.textColor = UIColor.label delelgate?.skip() } } else if location.x >= pauseLabel.frame.origin.x { if pauseLabel.isEnabled { pauseLabel.backgroundColor = buttonColor pauseLabel.textColor = UIColor.label delelgate?.presentPause() } } else { os_log(.debug, "touch outise buttons area: %@", location.debugDescription) } } } }
mit
roecrew/AudioKit
Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/KnobLarge.swift
1
2441
// // KnobLarge.swift // Swift Synth // // Created by Matthew Fecher on 1/8/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit protocol KnobLargeDelegate { func updateKnobValue(value: Double, tag: Int) } @IBDesignable class KnobLarge: Knob { var delegate: KnobLargeDelegate? // Image Declarations var knob212_base = UIImage(named: "knob212_base") var knob212_indicator = UIImage(named: "knob212_indicator") override func drawRect(rect: CGRect) { drawKnobLarge(knobValue: knobValue) } // MARK: - Set Percentages override func setPercentagesWithTouchPoint(touchPoint: CGPoint) { super.setPercentagesWithTouchPoint(touchPoint) delegate?.updateKnobValue(value, tag: self.tag) setNeedsDisplay() } // MARK: - PaintCode generated code func drawKnobLarge(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// Picture Drawing let picturePath = UIBezierPath(rect: CGRect(x: 10, y: 10, width: 106, height: 106)) CGContextSaveGState(context) picturePath.addClip() knob212_base!.drawInRect(CGRectMake(10, 10, knob212_base!.size.width, knob212_base!.size.height)) CGContextRestoreGState(context) //// Picture 2 Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 63, 63) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let picture2Path = UIBezierPath(rect: CGRect(x: -53, y: -53, width: 106, height: 106)) CGContextSaveGState(context) picture2Path.addClip() knob212_indicator!.drawInRect(CGRectMake(-53, -53, knob212_indicator!.size.width, knob212_indicator!.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } // MARK: - Allow knobs to appear in IB override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() let bundle = NSBundle(forClass: self.dynamicType) knob212_base = UIImage(named: "knob212_base", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)! knob212_indicator = UIImage(named: "knob212_indicator", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)! } }
mit
QuarkX/Quark
Sources/Mustache/Compiling/TemplateAST/SectionTag.swift
2
2327
// 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. /** A SectionTag represents a regular or inverted section tag such as {{#section}}...{{/section}} or {{^section}}...{{/section}}. */ final class SectionTag: LocatedTag { let openingToken: TemplateToken let innerTemplateAST: TemplateAST init(innerTemplateAST: TemplateAST, openingToken: TemplateToken, innerTemplateString: String) { self.innerTemplateAST = innerTemplateAST self.openingToken = openingToken self.innerTemplateString = innerTemplateString } // Mark: - Tag protocol let type: TagType = .Section let innerTemplateString: String var tagDelimiterPair: TagDelimiterPair { return openingToken.tagDelimiterPair! } var description: String { return "\(openingToken.templateSubstring) at \(openingToken.locationDescription)" } func render(context: Context) throws -> Rendering { let renderingEngine = RenderingEngine(templateAST: innerTemplateAST, context: context) return try renderingEngine.render() } // Mark: - LocatedTag var templateID: TemplateID? { return openingToken.templateID } var lineNumber: Int { return openingToken.lineNumber } }
mit
brokenseal/WhereIsMaFood
WhereIsMaFood/ShowWebsiteModalViewController.swift
1
646
// // ShowWebsiteModalViewController.swift // WhereIsMaFood // // Created by Davide Callegari on 08/08/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import UIKit class ShowWebsiteModalViewController: UIViewController { @IBOutlet weak var webView: UIWebView! var url: URL? @IBAction func goBack(_ sender: Any) { dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // FIXME: bail out? if let url = url { let request = URLRequest(url: url) webView.loadRequest(request) } } func setup(url: URL) { self.url = url } }
mit
JesusAntonioGil/Design-Patterns-Swift-2
CreationalPatterns/FactoryMethodPattern/FactoryMethodPattern/Model/CardFactory.swift
1
566
// // CardFactory.swift // FactoryMethodPattern // // Created by Jesus Antonio Gil on 17/12/15. // Copyright © 2015 Jesus Antonio Gil. All rights reserved. // import UIKit enum CardType { case FacelessManipulator, RaidLeader } class CardFactory: NSObject { //MARK: PUBLIC class func createCard(cardType:CardType) -> Card? { switch cardType { case .FacelessManipulator: return FacelessManipulatorCard() case .RaidLeader: return RaidLeaderCard() } } }
mit
maxvol/RxCloudKit
RxCloudKit/RecordFetcher.swift
1
1552
// // Fetcher.swift // RxCloudKit // // Created by Maxim Volgin on 22/06/2017. // Copyright (c) RxSwiftCommunity. All rights reserved. // import RxSwift import CloudKit @available(iOS 10, *) final class RecordFetcher { typealias Observer = AnyObserver<CKRecord> private let observer: Observer private let database: CKDatabase private let limit: Int init(observer: Observer, database: CKDatabase, query: CKQuery, limit: Int) { self.observer = observer self.database = database self.limit = limit self.fetch(query: query) } private func recordFetchedBlock(record: CKRecord) { self.observer.on(.next(record)) } private func queryCompletionBlock(cursor: CKQueryOperation.Cursor?, error: Error?) { if let error = error { observer.on(.error(error)) return } if let cursor = cursor { let operation = CKQueryOperation(cursor: cursor) self.setupAndAdd(operation: operation) return } observer.on(.completed) } private func fetch(query: CKQuery) { let operation = CKQueryOperation(query: query) self.setupAndAdd(operation: operation) } private func setupAndAdd(operation: CKQueryOperation) { operation.resultsLimit = self.limit operation.recordFetchedBlock = self.recordFetchedBlock operation.queryCompletionBlock = self.queryCompletionBlock self.database.add(operation) } }
mit
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Features/Shared/CloudKitOperation.swift
2
13647
// // CloudKitOperation.swift // Operations // // Created by Daniel Thorpe on 22/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation import CloudKit // MARK: - OPRCKOperation public class OPRCKOperation<T where T: NSOperation, T: CKOperationType>: ReachableOperation<T> { override init(_ operation: T, connectivity: Reachability.Connectivity = .AnyConnectionKind) { super.init(operation, connectivity: connectivity) name = "OPRCKOperation<\(T.self)>" } } // MARK: - Cloud Kit Error Recovery public class CloudKitRecovery<T where T: NSOperation, T: CKOperationType> { public typealias V = OPRCKOperation<T> public typealias ErrorResponse = (delay: Delay?, configure: V -> Void) public typealias Handler = (error: NSError, log: LoggerType, suggested: ErrorResponse) -> ErrorResponse? typealias Payload = (Delay?, V) var defaultHandlers: [CKErrorCode: Handler] var customHandlers: [CKErrorCode: Handler] init() { defaultHandlers = [:] customHandlers = [:] addDefaultHandlers() } internal func recoverWithInfo(info: RetryFailureInfo<V>, payload: Payload) -> ErrorResponse? { guard let (code, error) = cloudKitErrorsFromInfo(info) else { return .None } // We take the payload, if not nil, and return the delay, and configuration block let suggestion: ErrorResponse = (payload.0, info.configure ) var response: ErrorResponse? = .None response = defaultHandlers[code]?(error: error, log: info.log, suggested: suggestion) response = customHandlers[code]?(error: error, log: info.log, suggested: response ?? suggestion) return response // 5. Consider how we might pass the result of the default into the custom } func addDefaultHandlers() { let exit: Handler = { error, log, _ in log.fatal("Exiting due to CloudKit Error: \(error)") return .None } let retry: Handler = { error, log, suggestion in if let interval = (error.userInfo[CKErrorRetryAfterKey] as? NSNumber).map({ $0.doubleValue }) { return (Delay.By(interval), suggestion.configure) } return suggestion } setDefaultHandlerForCode(.InternalError, handler: exit) setDefaultHandlerForCode(.MissingEntitlement, handler: exit) setDefaultHandlerForCode(.InvalidArguments, handler: exit) setDefaultHandlerForCode(.ServerRejectedRequest, handler: exit) setDefaultHandlerForCode(.AssetFileNotFound, handler: exit) setDefaultHandlerForCode(.IncompatibleVersion, handler: exit) setDefaultHandlerForCode(.ConstraintViolation, handler: exit) setDefaultHandlerForCode(.BadDatabase, handler: exit) setDefaultHandlerForCode(.QuotaExceeded, handler: exit) setDefaultHandlerForCode(.OperationCancelled, handler: exit) setDefaultHandlerForCode(.NetworkUnavailable, handler: retry) setDefaultHandlerForCode(.NetworkFailure, handler: retry) setDefaultHandlerForCode(.ServiceUnavailable, handler: retry) setDefaultHandlerForCode(.RequestRateLimited, handler: retry) setDefaultHandlerForCode(.AssetFileModified, handler: retry) setDefaultHandlerForCode(.BatchRequestFailed, handler: retry) setDefaultHandlerForCode(.ZoneBusy, handler: retry) } func setDefaultHandlerForCode(code: CKErrorCode, handler: Handler) { defaultHandlers.updateValue(handler, forKey: code) } func setCustomHandlerForCode(code: CKErrorCode, handler: Handler) { customHandlers.updateValue(handler, forKey: code) } internal func cloudKitErrorsFromInfo(info: RetryFailureInfo<OPRCKOperation<T>>) -> (code: CKErrorCode, error: NSError)? { let mapped: [(CKErrorCode, NSError)] = info.errors.flatMap { error in let error = error as NSError if error.domain == CKErrorDomain, let code = CKErrorCode(rawValue: error.code) { return (code, error) } return .None } return mapped.first } } // MARK: - CloudKitOperation /** # CloudKitOperation CloudKitOperation is a generic operation which can be used to configure and schedule the execution of Apple's CKOperation subclasses. ## Generics CloudKitOperation is generic over the type of the CKOperation. See Apple's documentation on their CloudKit NSOperation classes. ## Initialization CloudKitOperation is initialized with a block which should return an instance of the required operation. Note that some CKOperation subclasses have static methods to return standard instances. Given Swift's treatment of trailing closure arguments, this means that the following is a standard initialization pattern: ```swift let operation = CloudKitOperation { CKFetchRecordZonesOperation.fetchAllRecordZonesOperation() } ``` This works because, the initializer only takes a trailing closure. The closure receives no arguments and is only one line, so the return is not needed. ## Configuration Most CKOperation subclasses need various properties setting before they are added to a queue. Sometimes these can be done via their initializers. However, it is also possible to set the properties directly. This can be done directly onto the CloudKitOperation. For example, given the above: ```swift let container = CKContainer.defaultContainer() operation.container = container operation.database = container.privateCloudDatabase ``` This will set the container and the database through the CloudKitOperation into the wrapped CKOperation instance. ## Completion All CKOperation subclasses have a completion block which should be set. This completion block receives the "results" of the operation, and an `NSError` argument. However, CloudKitOperation features its own semi-automatic error handling system. Therefore, the only completion block needed is one which receives the "results". Essentially, all that is needed is to manage the happy path of the operation. For all CKOperation subclasses, this can be configured directly on the CloudKitOperation instance, using a pattern of `setOperationKindCompletionBlock { }`. For example, given the above: ```swift operation.setFetchRecordZonesCompletionBlock { zonesByID in // Do something with the zonesByID } ``` Note, that for the automatic error handling to kick in, the happy path must be set (as above). ### Error Handling When the completion block is set as above, any errors receives from the CKOperation subclass are intercepted, and instead of the provided block being executed, the operation finsihes with an error. However, CloudKitOperation is a subclass of RetryOperation, which is actually a GroupOperation subclass, and when a child operation finishes with an error, RetryOperation will consult its error handler, and attempt to retry the operation. In the case of CloudKitOperation, the error handler, which is configured internally has automatic support for many common error kinds. When the CKOperation receives an error, the CKErrorCode is extracted, and the handler consults a CloudKitRecovery instance to check for a particular way to handle that error code. In some cases, this will result in a tuple being returned. The tuple is an optional Delay, and a new instance of the CKOperation class. This is why the initializer takes a block which returns an instance of the CKOperation subclass, rather than just an instance directly. In addition, any configuration set on the operation is captured and applied again to new instances of the CKOperation subclass. The delay is used to automatically respect any wait periods returned in the CloudKit NSError object. If none are given, a random time delay between 0.1 and 1.0 seconds is used. If the error recovery does not have a handler, or the handler returns nil (no tuple), the CloudKitOperation will finish (with the errors). ### Custom Error Handling To provide bespoke error handling, further configure the CloudKitOperation by calling setErrorHandlerForCode. For example: ```swift operation.setErrorHandlerForCode(.PartialFailure) { error, log, suggested in return suggested } ``` Note that the error handler receives the received error, a logger object, and the suggested tuple, which could be modified before being returned. Alternatively, return nil to not retry. */ public final class CloudKitOperation<T where T: NSOperation, T: CKOperationType>: RetryOperation<OPRCKOperation<T>> { public typealias ErrorHandler = CloudKitRecovery<T>.Handler let recovery: CloudKitRecovery<T> var operation: T { return current.operation } public convenience init(_ body: () -> T?) { self.init(generator: AnyGenerator(body: body), connectivity: .AnyConnectionKind, reachability: ReachabilityManager(DeviceReachability())) } convenience init(connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType, _ body: () -> T?) { self.init(generator: AnyGenerator(body: body), connectivity: .AnyConnectionKind, reachability: reachability) } init<G where G: GeneratorType, G.Element == T>(generator gen: G, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) { // Creates a standard random delay between retries let strategy: WaitStrategy = .Random((0.1, 1.0)) let delay = MapGenerator(strategy.generator()) { Delay.By($0) } // Maps the generator to wrap the target operation. let generator = MapGenerator(gen) { operation -> OPRCKOperation<T> in let op = OPRCKOperation(operation, connectivity: connectivity) op.reachability = reachability return op } // Creates a CloudKitRecovery object let _recovery = CloudKitRecovery<T>() // Creates a Retry Handler using the recovery object let handler: Handler = { info, payload in guard let (delay, configure) = _recovery.recoverWithInfo(info, payload: payload) else { return .None } let (_, operation) = payload configure(operation) return (delay, operation) } recovery = _recovery super.init(delay: delay, generator: generator, retry: handler) name = "CloudKitOperation<\(T.self)>" } public func setErrorHandlerForCode(code: CKErrorCode, handler: ErrorHandler) { recovery.setCustomHandlerForCode(code, handler: handler) } override func childOperation(child: NSOperation, didFinishWithErrors errors: [ErrorType]) { if !(child is OPRCKOperation<T>) { super.childOperation(child, didFinishWithErrors: errors) } } } // MARK: - BatchedCloudKitOperation class CloudKitOperationGenerator<T where T: NSOperation, T: CKOperationType>: GeneratorType { let connectivity: Reachability.Connectivity let reachability: SystemReachabilityType var generator: AnyGenerator<T> var more: Bool = true init<G where G: GeneratorType, G.Element == T>(generator: G, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) { self.generator = AnyGenerator(generator) self.connectivity = connectivity self.reachability = reachability } func next() -> CloudKitOperation<T>? { guard more else { return .None } return CloudKitOperation(generator: generator, connectivity: connectivity, reachability: reachability) } } public class BatchedCloudKitOperation<T where T: NSOperation, T: CKBatchedOperationType>: RepeatedOperation<CloudKitOperation<T>> { public var enableBatchProcessing: Bool var generator: CloudKitOperationGenerator<T> public var operation: T { return current.operation } public convenience init(enableBatchProcessing enable: Bool = true, _ body: () -> T?) { self.init(generator: AnyGenerator(body: body), enableBatchProcessing: enable, connectivity: .AnyConnectionKind, reachability: ReachabilityManager(DeviceReachability())) } convenience init(enableBatchProcessing enable: Bool = true, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType, _ body: () -> T?) { self.init(generator: AnyGenerator(body: body), enableBatchProcessing: enable, connectivity: connectivity, reachability: reachability) } init<G where G: GeneratorType, G.Element == T>(generator gen: G, enableBatchProcessing enable: Bool = true, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) { enableBatchProcessing = enable generator = CloudKitOperationGenerator(generator: gen, connectivity: connectivity, reachability: reachability) // Creates a standard fixed delay between batches (not reties) let strategy: WaitStrategy = .Fixed(0.1) let delay = MapGenerator(strategy.generator()) { Delay.By($0) } let tuple = TupleGenerator(primary: generator, secondary: delay) super.init(generator: AnyGenerator(tuple)) } public override func willFinishOperation(operation: NSOperation, withErrors errors: [ErrorType]) { if errors.isEmpty, let cloudKitOperation = operation as? CloudKitOperation<T> { generator.more = enableBatchProcessing && cloudKitOperation.current.moreComing } super.willFinishOperation(operation, withErrors: errors) } }
gpl-3.0
a736220388/FinestFood
FinestFood/FinestFood/classes/common/Constant.swift
1
4139
// // Constant.swift // FinestFood // // Created by qianfeng on 16/8/15. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit public let kScreenWidth = UIScreen.mainScreen().bounds.width public let kScreenHeight = UIScreen.mainScreen().bounds.height public let FSScrollViewUrl = "http://api.guozhoumoapp.com/v1/banners?channel=iOS" //专题集合(体验课...) public let FSScrollViewListlUrl = "http://api.guozhoumoapp.com/v1/collections/%d/posts?gender=%d&generation=%d&limit=%d&offset=%d" public let FSSearchWordUrl = "http://api.guozhoumoapp.com/v1/search/hot_words" public let FSSearchItemResultUrl = "http://api.guozhoumoapp.com/v1/search/item?keyword=%@&limit=%d&offset=%d&sort=" public let FSSearchPostResultUrl = "http://api.guozhoumoapp.com/v1/search/post?keyword=%@&limit=%d&offset=%d&sort=" public let FSFoodListUrl = "http://api.guozhoumoapp.com/v1/channels/2/items?gender=%d&generation=%d&limit=%d&offset=%d" //宅家 public let FSFoodMoreListUrl = "http://api.guozhoumoapp.com/v1/channels/%d/items?limit=%d&offset=%d" public let FSFoodDetailUrl = "http://api.guozhoumoapp.com/v1/posts/%d" public let FLFoodListUrl = "http://api.guozhoumoapp.com/v2/items?gender=%d&generation=%d&limit=%d&offset=%d" public let FLFoodDetailUrl = "http://api.guozhoumoapp.com/v2/items/%d/comments?limit=%d&offset=%d"//单品中商品的detail public let FLFoodSearchDetailUrl = "http://api.guozhoumoapp.com/v2/items/%d"//搜索中商品的detail public let CGHomeOutUrl = "http://api.guozhoumoapp.com/v1/channel_groups/all" //查看全部 public let CGSubjectUrl = "http://api.guozhoumoapp.com/v1/collections?limit=%d&offset=%d" //登录 public let MineLoginUrl = "http://api.guozhoumoapp.com/v1/account/signin" //postBody:mobile=18550217023&password=123456 //登陆后获取用户信息 public let UserInfoPostUrl = "http://api.guozhoumoapp.com/v1/users/me/post_likes?limit==%d&offset=%d" public let UserInfoListUrl = "http://api.guozhoumoapp.com/v1/users/me/favorite_lists?limit==%d&offset=%d" //注册 public let MineRegisterUrl = "http://api.guozhoumoapp.com/v1/account/mobile_exist" //post:mobile=18550217032 //{ // "code": 200, // "data": { // "exist": false // }, // "message": "OK" //} //http://api.guozhoumoapp.com/v1/account/sms_token // { // "code": 200, // "data": { // "token": "xwg6e9f6z5" // }, // "message": "OK" //} //http://api.guozhoumoapp.com/v1/account/send_verification_code //access_token=I7iUQTM%2Bbmpucs6rWeMAAMoCFx4%3D&mobile=18550217032 // { // "code": 200, // "data": {}, // "message": "OK" //} /* 精选 滚动视图 http://api.guozhoumoapp.com/v1/banners?channel=iOS 滚动视图详情 1,体验课:http://api.guozhoumoapp.com/v1/collections/4/posts?gender=1&generation=0&limit=20&offset=0 2,下厨房:http://api.guozhoumoapp.com/v1/collections/3/posts?gender=1&generation=0&limit=20&offset=0 3,来一发:http://api.guozhoumoapp.com/v1/collections/1/posts?gender=1&generation=0&limit=20&offset=0 4,周末宅家:http://api.guozhoumoapp.com/v1/collections/2/posts?gender=1&generation=0&limit=20&offset=0 内容 http://api.guozhoumoapp.com/v1/channels/2/items?gender=1&generation=0&limit=20&offset=0 搜索 http://api.guozhoumoapp.com/v1/search/hot_words? 商品:http://api.guozhoumoapp.com/v1/search/item?keyword=%E6%89%8B%E5%B7%A5&limit=20&offset=0&sort= 攻略:http://api.guozhoumoapp.com/v1/search/post?keyword=%E4%B8%8A%E6%B5%B7&limit=20&offset=0&sort= 周末逛店 内容:http://api.guozhoumoapp.com/v1/channels/12/items?limit=20&offset=0 尝美食 内容:http://api.guozhoumoapp.com/v1/channels/15/items?limit=20&offset=0 体验课 内容:http://api.guozhoumoapp.com/v1/channels/13/items?limit=20&offset=0 周边游 内容:http://api.guozhoumoapp.com/v1/channels/14/items?limit=20&offset=0 单品 内容:http://api.guozhoumoapp.com/v2/items?gender=1&generation=0&limit=20&offset=0 宅家,出门 http://api.guozhoumoapp.com/v1/channel_groups/all 专题集合 http://api.guozhoumoapp.com/v1/collections?limit=6&offset=0 */
mit
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/NSExpression.swift
1
1045
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSExpression { // + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...; public convenience init(format expressionFormat: __shared String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: expressionFormat, arguments: va_args) } } extension NSExpression { public convenience init<Root, Value>(forKeyPath keyPath: KeyPath<Root, Value>) { self.init(forKeyPath: _bridgeKeyPathToString(keyPath)) } }
apache-2.0
peterxhu/ARGoal
ARGoal/Virtual Objects/FieldGoal.swift
1
469
// // FieldGoal.swift // ARGoal // // Created by Peter Hu on 6/17/17. // Copyright © 2017 App Doctor Hu. All rights reserved. // import Foundation import SceneKit class FieldGoal: VirtualObject { override init() { super.init(modelName: "goal", fileExtension: "scn", thumbImageFilename: "fieldGoal", title: "Field Goal") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
jbourjeli/SwiftLabelPhoto
Photos++/FontAwesomeService.swift
1
6836
// // FontAwesomeService.swift // Photos++ // // Created by Joseph Bourjeli on 9/23/16. // Copyright © 2016 WorkSmarterComputing. All rights reserved. // import UIKit import CoreText public enum FontAwesomeIcon: String{ case faCheck="\u{f00c}" case faCheckSquareO="\u{f046}" case faMoney="\u{f0d6}" case faCC="\u{f09d}" case faCCAmex="\u{f1f3}" case faCCDiscover="\u{f1f2}" case faCCMastercard="\u{f1f1}" case faCCVisa="\u{f1f0}" case faBuilding="\u{f1ad}" case faHome="\u{f015}" case faCar="\u{f1b9}" case faEnvelope="\u{f0e0}" case faEnvelopeO="\u{f003}" case faPhone="\u{f095}" case faExternalLink="\u{f08e}" case faBan="\u{f05e}" case faTable="\u{f0ce}" case faRepeat="\u{f01e}" case faMinusCircle="\u{f056}" case faTrashO="\u{f014}" case faArchive="\u{f187}" case faEllipsisV="\u{f142}" case faEllipsisH="\u{f141}" case faFilter="\u{f0b0}" case faPencil="\u{f040}" case faCameraRetro="\u{f083}" case faShareSquareO="\u{f045}" case faShareAlt="\u{f1e0}" case faShare="\u{f064}" case faStar="\u{f005}" case faHandPaperO="\u{f256}" case faExclamationTriangle="\u{f071}" case faThumbsOUp="\u{f087}" case faPlus="\u{f067}" case faFolderOpen="\u{f07c}" case faUser="\u{f007}" case faSunO="\u{f185}" case faCloud="\u{f0c2}" case faBook="\u{f02d}" case faCog="\u{f013}" case faCogs="\u{f085}" case faGavel="\u{f0e3}" case faVolumeUp="\u{f028}" case faBars="\u{f0c9}" case faBarChart="\u{f080}" case faCommentO="\u{f0e5}" case faCommentsO="\u{f0e6}" case faTag="\u{f02b}" ; } public class FontAwesome { let icon: FontAwesomeIcon var textColor: UIColor { didSet { self.renderedImage = nil } } var size: CGSize { didSet { self.renderedImage = nil } } private var renderedImage: UIImage? public init(_ icon: FontAwesomeIcon) { self.icon = icon self.textColor = UIColor.black self.size = CGSize(width: 10, height: 10) } public convenience init(_ icon: FontAwesomeIcon, textColor: UIColor, size: CGSize) { self.init(icon) self.textColor = textColor self.size = size } public convenience init(_ icon: FontAwesomeIcon, size: CGSize) { self.init(icon) self.size = size } public func image() -> UIImage { if let renderedImage = self.renderedImage { return renderedImage } let paragraph = NSMutableParagraphStyle() paragraph.alignment = NSTextAlignment.center // Taken from FontAwesome.io's Fixed Width Icon CSS let fontAspectRatio: CGFloat = 1.28571429 let fontSize = min(self.size.width / fontAspectRatio, self.size.height) let attributedString = NSAttributedString( string: self.icon.rawValue as String, attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(fontSize: fontSize)!, NSForegroundColorAttributeName: self.textColor, NSParagraphStyleAttributeName: paragraph]) UIGraphicsBeginImageContextWithOptions(self.size, false , 0.0) let boundingRect = CGRect(x:0, y:(self.size.height - fontSize) / 2, width:self.size.width, height:fontSize) attributedString.draw(in: boundingRect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.renderedImage = image return image! } } public class FontAwesomeUtils { public static let smallFont = UIFont.fontAwesomeOfSize(fontSize: 12) public static let regularFont = UIFont.fontAwesomeOfSize(fontSize: 16) public static let bigFont = UIFont.fontAwesomeOfSize(fontSize: 20) } public extension UIImage { public static func imageFromfontAwesomeIcon(name: FontAwesomeIcon, withTextColor textColor: UIColor, ofSize size: CGSize) -> UIImage { let paragraph = NSMutableParagraphStyle() paragraph.alignment = NSTextAlignment.center // Taken from FontAwesome.io's Fixed Width Icon CSS let fontAspectRatio: CGFloat = 1.28571429 let fontSize = min(size.width / fontAspectRatio, size.height) let attributedString = NSAttributedString(string: name.rawValue as String, attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(fontSize: fontSize)!, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: paragraph]) UIGraphicsBeginImageContextWithOptions(size, false , 0.0) attributedString.draw(in: CGRect(x:0, y:(size.height - fontSize) / 2, width: size.width, height:fontSize)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } public extension UIFont { public static func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont? { let name = "FontAwesome" if (UIFont.fontNames(forFamilyName: name).isEmpty ) { FontLoader.loadFont(name: name) } return UIFont(name: name, size: fontSize) } } private class FontLoader { class func loadFont(name: String) { let bundle = Bundle(for: FontLoader.self) var fontURL: URL let identifier = bundle.bundleIdentifier if identifier?.hasPrefix("org.cocoapods") == true { // If this framework is added using CocoaPods, resources is placed under a subdirectory fontURL = bundle.url(forResource: name, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle")! as URL } else { fontURL = bundle.url(forResource: name, withExtension: "otf")! as URL } let data = NSData(contentsOf: fontURL as URL)! let provider = CGDataProvider(data: data) let font = CGFont(provider!) var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } }
mit
MadeByHecho/Timber
Timber/Logger.swift
1
1265
// // Logger.swift // Timber // // Created by Scott Petit on 9/7/14. // Copyright (c) 2014 Scott Petit. All rights reserved. // import Foundation public protocol LoggerType { var messageFormatter: MessageFormatterType { get } func logMessage(message: LogMessage) } public enum LogLevel: Int, Comparable { case None = 0 case Error case Warn case Info case Debug case Verbose func toString() -> String { switch self { case .None: return "None" case .Error: return "ERROR" case .Warn: return "WARNING" case .Info: return "INFO" case .Debug: return "DEBUG" case .Verbose: return "VERBOSE" } } } public func ==(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue == rhs.rawValue } public func <=(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue <= rhs.rawValue } public func >=(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue >= rhs.rawValue } public func >(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue > rhs.rawValue } public func <(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
mit
jopamer/swift
tools/SwiftSyntax/SwiftSyntax.swift
1
4104
//===--------------- SwiftLanguage.swift - Swift Syntax Library -----------===// // // 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 // //===----------------------------------------------------------------------===// // This file provides main entry point into the Syntax library. //===----------------------------------------------------------------------===// import Foundation #if os(macOS) import Darwin #elseif os(Linux) import Glibc #endif /// A list of possible errors that could be encountered while parsing a /// Syntax tree. public enum ParserError: Error, CustomStringConvertible { case swiftcFailed(Int, String) case invalidFile public var description: String { switch self{ case let .swiftcFailed(exitCode, stderr): let stderrLines = stderr.split(separator: "\n") return """ swiftc returned with non-zero exit code \(exitCode) stderr: \(stderrLines.joined(separator: "\n ")) """ case .invalidFile: return "swiftc created an invalid syntax file" } } } /// Deserializes the syntax tree from its serialized form to an object tree in /// Swift. To deserialize incrementally transferred syntax trees, the same /// instance of the deserializer must be used for all subsequent /// deserializations. public final class SyntaxTreeDeserializer { // FIXME: This lookup table just accumulates nodes, we should invalidate nodes // that are no longer used at some point and remove them from the table /// Syntax nodes that have already been parsed and are able to be reused if /// they were omitted in an incremental syntax tree transfer private var nodeLookupTable: [SyntaxNodeId: RawSyntax] = [:] /// The IDs of the nodes that were reused as part of incremental syntax /// parsing during the last deserialization public var reusedNodeIds: Set<SyntaxNodeId> = [] public init() { } /// Decode a serialized form of SourceFileSyntax to a syntax tree. /// - Parameter data: The UTF-8 represenation of the serialized syntax tree /// - Returns: A top-level Syntax node representing the contents of the tree, /// if the parse was successful. public func deserialize(_ data: Data) throws -> SourceFileSyntax { reusedNodeIds = [] let decoder = JSONDecoder() decoder.userInfo[.rawSyntaxDecodedCallback] = self.addToLookupTable decoder.userInfo[.omittedNodeLookupFunction] = self.lookupNode let raw = try decoder.decode(RawSyntax.self, from: data) guard let file = makeSyntax(raw) as? SourceFileSyntax else { throw ParserError.invalidFile } return file } // MARK: Incremental deserialization helper functions private func lookupNode(id: SyntaxNodeId) -> RawSyntax? { reusedNodeIds.insert(id) return nodeLookupTable[id] } private func addToLookupTable(_ node: RawSyntax) { nodeLookupTable[node.id] = node } } /// Namespace for functions to retrieve a syntax tree from the swift compiler /// and deserializing it. public enum SyntaxTreeParser { /// Parses the Swift file at the provided URL into a full-fidelity Syntax tree /// - Parameter url: The URL you wish to parse. /// - Returns: A top-level Syntax node representing the contents of the tree, /// if the parse was successful. /// - Throws: `ParseError.couldNotFindSwiftc` if `swiftc` could not be /// located, `ParseError.invalidFile` if the file is invalid. /// FIXME: Fill this out with all error cases. public static func parse(_ url: URL) throws -> SourceFileSyntax { let swiftcRunner = try SwiftcRunner(sourceFile: url) let result = try swiftcRunner.invoke() let syntaxTreeData = result.stdoutData let deserializer = SyntaxTreeDeserializer() return try deserializer.deserialize(syntaxTreeData) } }
apache-2.0
tominated/Quake3BSPParser
Sources/BSPTypes.swift
1
4211
// // BSPTypes.swift // Quake3BSPParser // // Created by Thomas Brunoli on 28/05/2017. // Copyright © 2017 Quake3BSPParser. All rights reserved. // import Foundation import simd public struct Quake3BSP { public var entities: BSPEntities?; public var textures: Array<BSPTexture> = []; public var planes: Array<BSPPlane> = []; public var nodes: Array<BSPNode> = []; public var leaves: Array<BSPLeaf> = []; public var leafFaces: Array<BSPLeafFace> = []; public var leafBrushes: Array<BSPLeafBrush> = []; public var models: Array<BSPModel> = []; public var brushes: Array<BSPBrush> = []; public var brushSides: Array<BSPBrushSide> = []; public var vertices: Array<BSPVertex> = []; public var meshVerts: Array<BSPMeshVert> = []; public var effects: Array<BSPEffect> = []; public var faces: Array<BSPFace> = []; public var lightmaps: Array<BSPLightmap> = []; public var lightVols: Array<BSPLightVol> = []; public var visdata: BSPVisdata?; init() {} } public struct BSPEntities { public let entities: String; } public struct BSPTexture { public let name: String; public let surfaceFlags: Int32; public let contentFlags: Int32; } public struct BSPPlane { public let normal: float3; public let distance: Float32; } public struct BSPNode { public enum NodeChild { case node(Int); case leaf(Int); } public let planeIndex: Int32; public let leftChild: NodeChild; public let rightChild: NodeChild; public let boundingBoxMin: int3; public let boundingBoxMax: int3; } public struct BSPLeaf { public let cluster: Int32; public let area: Int32; public let boundingBoxMin: int3; public let boundingBoxMax: int3; public let leafFaceIndices: CountableRange<Int32>; public let leafBrushIndices: CountableRange<Int32>; } public struct BSPLeafFace { public let faceIndex: Int32; } public struct BSPLeafBrush { public let brushIndex: Int32; } public struct BSPModel { public let boundingBoxMin: float3; public let boundingBoxMax: float3; public let faceIndices: CountableRange<Int32>; public let brushIndices: CountableRange<Int32>; } public struct BSPBrush { public let brushSideIndices: CountableRange<Int32>; public let textureIndex: Int32; } public struct BSPBrushSide { public let planeIndex: Int32; public let textureIndex: Int32; } public struct BSPVertex { public let position: float3; public let surfaceTextureCoord: float2; public let lightmapTextureCoord: float2; public let normal: float3; public let color: float4; public init( position: float3, surfaceTextureCoord: float2, lightmapTextureCoord: float2, normal: float3, color: float4 ) { self.position = position self.surfaceTextureCoord = surfaceTextureCoord self.lightmapTextureCoord = lightmapTextureCoord self.normal = normal self.color = color } } public struct BSPMeshVert { public let vertexIndexOffset: Int32; } public struct BSPEffect { public let name: String; public let brushIndex: Int32; } public struct BSPFace { public enum FaceType: Int32 { case polygon = 1, patch, mesh, billboard; } public let textureIndex: Int32; public let effectIndex: Int32?; public let type: FaceType; public let vertexIndices: CountableRange<Int32>; public let meshVertIndices: CountableRange<Int32>; public let lightmapIndex: Int32; public let lightmapStart: int2; public let lightmapSize: int2; public let lightmapOrigin: float3; public let lightmapSVector: float3; public let lightmapTVector: float3; public let normal: float3; public let size: int2; } public struct BSPLightmap { public let lightmap: Array<(UInt8, UInt8, UInt8)>; } public struct BSPLightVol { public let ambientColor: (UInt8, UInt8, UInt8); public let directionalColor: (UInt8, UInt8, UInt8); public let direction: (UInt8, UInt8); } public struct BSPVisdata { public let numVectors: Int32; public let vectorSize: Int32; public let vectors: Array<UInt8>; }
mit
blockchain/My-Wallet-V3-iOS
Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyDomain/DelegatedCustodyTransactionServiceAPI.swift
1
2030
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import Foundation import MoneyKit import ToolKit public protocol DelegatedCustodyTransactionServiceAPI { func buildTransaction( _ transaction: DelegatedCustodyTransactionInput ) -> AnyPublisher<DelegatedCustodyTransactionOutput, DelegatedCustodyTransactionServiceError> func sign( _ transaction: DelegatedCustodyTransactionOutput, privateKey: Data ) -> Result<DelegatedCustodySignedTransactionOutput, DelegatedCustodyTransactionServiceError> func pushTransaction( _ transaction: DelegatedCustodySignedTransactionOutput, currency: CryptoCurrency ) -> AnyPublisher<String, DelegatedCustodyTransactionServiceError> } public enum DelegatedCustodyTransactionServiceError: Error { case authenticationError(AuthenticationDataRepositoryError) case networkError(NetworkError) case signing(DelegatedCustodySigningError) } public enum AuthenticationDataRepositoryError: Error { case missingGUID case missingSharedKey } public struct DelegatedCustodySignedTransactionOutput { public struct SignedPreImage { public let preImage: String public let signingKey: String public let signatureAlgorithm: DelegatedCustodySignatureAlgorithm public let signature: String public init( preImage: String, signingKey: String, signatureAlgorithm: DelegatedCustodySignatureAlgorithm, signature: String ) { self.preImage = preImage self.signingKey = signingKey self.signatureAlgorithm = signatureAlgorithm self.signature = signature } } public let rawTx: JSONValue public let signatures: [SignedPreImage] public init( rawTx: JSONValue, signatures: [DelegatedCustodySignedTransactionOutput.SignedPreImage] ) { self.rawTx = rawTx self.signatures = signatures } }
lgpl-3.0
huonw/swift
stdlib/public/SDK/SafariServices/SafariServices.swift
18
860
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import SafariServices // Clang module import _SwiftSafariServicesOverlayShims #if os(macOS) @available(macOS, introduced: 10.11) public func SFSafariServicesAvailable(_ version: SFSafariServicesVersion = SFSafariServicesVersion.version10_0) -> Bool { return _swift_SafariServices_isSafariServicesAvailable(version) } #endif
apache-2.0
Diego5529/tcc-swift
tcc-swift/src/model/User+CoreDataProperties.swift
1
1207
// // User+CoreDataProperties.swift // // // Created by Diego on 8/7/16. // // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension User { @NSManaged var birth_date: NSTimeInterval @NSManaged var created_at: NSTimeInterval @NSManaged var current_sign_in_at: NSTimeInterval @NSManaged var current_sign_in_ip: String? @NSManaged var email: String? @NSManaged var encrypted_password: String? @NSManaged var genre: String? @NSManaged var last_sign_in_at: NSTimeInterval @NSManaged var last_sign_in_ip: String? @NSManaged var long_name: String? @NSManaged var name: String? @NSManaged var phone_number: String? @NSManaged var remember_created_at: NSTimeInterval @NSManaged var reset_password_sent_at: NSTimeInterval @NSManaged var reset_password_token: String? @NSManaged var sign_in_count: Int16 @NSManaged var updated_at: NSTimeInterval @NSManaged var user_id: Int16 @NSManaged var has_many_invitation: Guest? @NSManaged var has_many_users_company_type: UserCompanyType? }
mit
eofster/Telephone
UseCases/Calls.swift
1
735
// // Calls.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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. // public protocol Calls { var haveActive: Bool { get } var haveUnansweredIncoming: Bool { get } }
gpl-3.0
NickAger/elm-slider
ServerSlider/WebSocketServer/Packages/Reflection-0.14.0/Package.swift
5
75
import PackageDescription let package = Package( name: "Reflection" )
mit
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/UIImage/ImageRepresentable/ImageRepresentable+Transform.swift
1
1159
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit extension ImageRepresentable { /// Returns `ImageRepresentable` instance with the given transform. /// /// **Usage** /// /// ```swift /// func setIcon(_ icon: ImageRepresentable) { /// let newIcon = icon /// .alignment(.leading) /// .transform(TintColorImageTransform(tintColor: .white)) /// .alignment(.trailing) // last one wins when using plugin. /// /// let iconView = UIImageView() /// iconView.setImage(newIcon) /// /// let transform: ImageTransform = newIcon.plugin()! /// print(transform.id) /// // "TintColorImageTransform-tintColor:(#FFFFFF)" /// /// let alignment: ImageRepresentableAlignment = newIcon.plugin()! /// print(alignment) /// // "trailing" /// } /// ``` /// /// - Parameter value: The transform value for the image. /// - Returns: An `ImageRepresentable` instance. public func transform(_ value: ImageTransform) -> ImageRepresentable { append(value) } }
mit
imagineon/ViewConfigurator
Sources/UIKitExtensionsSorceryGeneration/UITableView+PropertyConfigurationSet.swift
1
6862
// Generated using Sourcery 0.12.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import UIKit @available(iOS 2.0, *) public extension ConfigurationSet where Base: UITableView { func dataSource(_ newValue: UITableViewDataSource?) -> Self { return set { (configurable: UITableView) in configurable.dataSource = newValue } } func delegate(_ newValue: UITableViewDelegate?) -> Self { return set { (configurable: UITableView) in configurable.delegate = newValue } } @available(iOS 10.0, *) func prefetchDataSource(_ newValue: UITableViewDataSourcePrefetching?) -> Self { return set { (configurable: UITableView) in configurable.prefetchDataSource = newValue } } @available(iOS 11.0, *) func dragDelegate(_ newValue: UITableViewDragDelegate?) -> Self { return set { (configurable: UITableView) in configurable.dragDelegate = newValue } } @available(iOS 11.0, *) func dropDelegate(_ newValue: UITableViewDropDelegate?) -> Self { return set { (configurable: UITableView) in configurable.dropDelegate = newValue } } func rowHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.rowHeight = newValue } } func sectionHeaderHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.sectionHeaderHeight = newValue } } func sectionFooterHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.sectionFooterHeight = newValue } } @available(iOS 7.0, *) func estimatedRowHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.estimatedRowHeight = newValue } } @available(iOS 7.0, *) func estimatedSectionHeaderHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.estimatedSectionHeaderHeight = newValue } } @available(iOS 7.0, *) func estimatedSectionFooterHeight(_ newValue: CGFloat) -> Self { return set { (configurable: UITableView) in configurable.estimatedSectionFooterHeight = newValue } } @available(iOS 7.0, *) func separatorInset(_ newValue: UIEdgeInsets) -> Self { return set { (configurable: UITableView) in configurable.separatorInset = newValue } } @available(iOS 11.0, *) func separatorInsetReference(_ newValue: UITableViewSeparatorInsetReference) -> Self { return set { (configurable: UITableView) in configurable.separatorInsetReference = newValue } } @available(iOS 3.2, *) func backgroundView(_ newValue: UIView?) -> Self { return set { (configurable: UITableView) in configurable.backgroundView = newValue } } func isEditing(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.isEditing = newValue } } @available(iOS 3.0, *) func allowsSelection(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.allowsSelection = newValue } } func allowsSelectionDuringEditing(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.allowsSelectionDuringEditing = newValue } } @available(iOS 5.0, *) func allowsMultipleSelection(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.allowsMultipleSelection = newValue } } @available(iOS 5.0, *) func allowsMultipleSelectionDuringEditing(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.allowsMultipleSelectionDuringEditing = newValue } } func sectionIndexMinimumDisplayRowCount(_ newValue: Int) -> Self { return set { (configurable: UITableView) in configurable.sectionIndexMinimumDisplayRowCount = newValue } } @available(iOS 6.0, *) func sectionIndexColor(_ newValue: UIColor?) -> Self { return set { (configurable: UITableView) in configurable.sectionIndexColor = newValue } } @available(iOS 7.0, *) func sectionIndexBackgroundColor(_ newValue: UIColor?) -> Self { return set { (configurable: UITableView) in configurable.sectionIndexBackgroundColor = newValue } } @available(iOS 6.0, *) func sectionIndexTrackingBackgroundColor(_ newValue: UIColor?) -> Self { return set { (configurable: UITableView) in configurable.sectionIndexTrackingBackgroundColor = newValue } } func separatorStyle(_ newValue: UITableViewCellSeparatorStyle) -> Self { return set { (configurable: UITableView) in configurable.separatorStyle = newValue } } func separatorColor(_ newValue: UIColor?) -> Self { return set { (configurable: UITableView) in configurable.separatorColor = newValue } } @available(iOS 8.0, *) func separatorEffect(_ newValue: UIVisualEffect?) -> Self { return set { (configurable: UITableView) in configurable.separatorEffect = newValue } } @available(iOS 9.0, *) func cellLayoutMarginsFollowReadableWidth(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.cellLayoutMarginsFollowReadableWidth = newValue } } @available(iOS 11.0, *) func insetsContentViewsToSafeArea(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.insetsContentViewsToSafeArea = newValue } } func tableHeaderView(_ newValue: UIView?) -> Self { return set { (configurable: UITableView) in configurable.tableHeaderView = newValue } } func tableFooterView(_ newValue: UIView?) -> Self { return set { (configurable: UITableView) in configurable.tableFooterView = newValue } } @available(iOS 9.0, *) func remembersLastFocusedIndexPath(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.remembersLastFocusedIndexPath = newValue } } @available(iOS 11.0, *) func dragInteractionEnabled(_ newValue: Bool) -> Self { return set { (configurable: UITableView) in configurable.dragInteractionEnabled = newValue } } }
mit
robrix/Madness
Madness/Combinator.swift
1
648
// Copyright © 2015 Rob Rix. All rights reserved. /// Parses `open`, followed by `parser` and `close`. Returns the value returned by `parser`. public func between<C: Collection, T, U, V>(_ open: @escaping Parser<C, T>.Function, _ close: @escaping Parser<C, U>.Function) -> (@escaping Parser<C, V>.Function) -> Parser<C, V>.Function { return { open *> $0 <* close } } /// Parses 0 or more `parser` until `end`. Returns the list of values returned by `parser`. public func manyTill<C: Collection, T, U>(_ parser: @escaping Parser<C, T>.Function, _ end: @escaping Parser<C, U>.Function) -> Parser<C, [T]>.Function { return many(parser) <* end }
mit
duliodenis/dollhouse
Dollhouse/DollhouseTests/DollhouseTests.swift
1
906
// // DollhouseTests.swift // DollhouseTests // // Created by Dulio Denis on 4/11/15. // Copyright (c) 2015 Dulio Denis. All rights reserved. // import UIKit import XCTest class DollhouseTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
yeokm1/nus-soc-print-ios
NUS SOC Print/PrintingViewTableCell.swift
1
976
// // PrintingViewTableCell.swift // NUS SOC Print // // Created by Yeo Kheng Meng on 17/8/14. // Copyright (c) 2014 Yeo Kheng Meng. All rights reserved. // import Foundation import UIKit class PrintingViewTableCell : UITableViewCell { @IBOutlet weak var header: UILabel! @IBOutlet weak var smallFooter: UILabel! @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var tick: UIImageView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var cross: UIImageView! override func prepareForReuse() { super.prepareForReuse() header.text = "" smallFooter.text = "" progressBar.hidden = true progressBar.setProgress(0, animated: false) tick.hidden = true cross.hidden = true if(activityIndicator.isAnimating()){ activityIndicator.stopAnimating() } activityIndicator.hidden = true } }
mit
ytfhqqu/iCC98
iCC98/iCC98/BoardTableViewController.swift
1
5597
// // BoardTableViewController.swift // iCC98 // // Created by Duo Xu on 5/4/17. // Copyright © 2017 Duo Xu. // // 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 SVProgressHUD import CC98Kit class BoardTableViewController: BaseTableViewController { // MARK: - Data /** 设置数据。 - parameter parentBoardId: 父版面的标识。 */ func setData(parentBoardId: Int) { shouldGetRootBoards = false fetchData(parentBoardId: parentBoardId) } /// 表示是否要获取根版面的信息。如果为真,在 `viewDidLoad()` 时自动加载根版面的信息;如果为假,则在使用 `setData(parentBoardId:)` 指定版面后,获取其子版面的信息。 private var shouldGetRootBoards = true /// 版面的信息。 private var boards = [BoardInfo]() { didSet { tableView.reloadData() } } /// 表示是否有数据。 override var hasData: Bool { return !boards.isEmpty } /// 获取根版面的数据。 private func fetchData() { isLoading = true _ = CC98API.getRootBoards { [weak self] result in switch result { case .success(_, let data): if let boardInfoArray = data { self?.boards = boardInfoArray } case .failure(let status, let message): SVProgressHUD.showError(statusCode: status, message: message) case .noResponse: SVProgressHUD.showNoResponseError() } self?.isLoading = false } } /// 根据父版面获取子版面的数据。 private func fetchData(parentBoardId: Int) { isLoading = true _ = CC98API.getSubBoards(ofBoard: parentBoardId, accessToken: OAuthUtility.accessToken) { [weak self] result in switch result { case .success(_, let data): if let boardInfoArray = data { self?.boards = boardInfoArray } case .failure(let status, let message): SVProgressHUD.showError(statusCode: status, message: message) case .noResponse: SVProgressHUD.showNoResponseError() } self?.isLoading = false } } // MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() // 获取根版面的数据 if shouldGetRootBoards { fetchData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return boards.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let boardInfo = boards[indexPath.row] let identifier: String // if let childCount = boardInfo.childCount, childCount > 0 { // identifier = "Non-leaf Board Cell" // } else { identifier = "Leaf Board Cell" // } let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) // Configure the cell... if let boardCell = cell as? BoardTableViewCell { boardCell.setData(boardInfo: boardInfo) } return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { let boardInfo = boards[indexPath.row] if segue.identifier == "Subboards", let boardTVC = segue.destination as? BoardTableViewController { boardTVC.setData(parentBoardId: boardInfo.id ?? 0) boardTVC.navigationItem.title = boardInfo.name } else if segue.identifier == "Topics", let topicTVC = segue.destination as? TopicTableViewController { topicTVC.setData(boardId: boardInfo.id ?? 0) topicTVC.navigationItem.title = boardInfo.name } } } }
mit
Alloc-Studio/Hypnos
Hypnos/Hypnos/ViewModel/Controller/Main/LeftViewController.swift
2
3220
// // LeftViewController.swift // Hypnos // // Created by Fay on 16/5/18. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit class LeftViewController: UITableViewController { 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(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, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... 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. } */ }
mit
cuappdev/eatery
Shared/Models/Eatery.swift
1
8278
// // Eatery.swift // Eatery // // Created by William Ma on 3/9/19. // Copyright © 2019 CUAppDev. All rights reserved. // import CoreLocation import UIKit // MARK: - Eatery Data /// Different meals served by eateries enum Meal: String { case breakfast = "Breakfast" case brunch = "Brunch" case liteLunch = "Lite Lunch" case lunch = "Lunch" case dinner = "Dinner" } /// Assorted types of payment accepted by an Eatery enum PaymentMethod: String { case brb = "Meal Plan - Debit" case swipes = "Meal Plan - Swipe" case cash = "Cash" case cornellCard = "Cornell Card" case creditCard = "Major Credit Cards" case nfc = "Mobile Payments" case other = "Other" } /// Different types of eateries on campus enum EateryType: String { case dining = "all you care to eat dining room" case cafe = "cafe" case cart = "cart" case foodCourt = "food court" case convenienceStore = "convenience store" case coffeeShop = "coffee shop" case bakery = "bakery" case unknown = "" } enum EateryStatus { static func equalsIgnoreAssociatedValue(_ lhs: EateryStatus, rhs: EateryStatus) -> Bool { switch (lhs, rhs) { case (.openingSoon, .openingSoon), (.open, .open), (.closingSoon, .closingSoon), (.closed, .closed): return true default: return false } } case openingSoon(minutesUntilOpen: Int) case open case closingSoon(minutesUntilClose: Int) case closed } // MARK: - Eatery protocol Eatery { /// A string of the form YYYY-MM-dd (ISO 8601 Calendar dates) /// Read more: https://en.wikipedia.org/wiki/ISO_8601#Calendar_dates typealias DayString = String typealias EventName = String var id: Int { get } var name: String { get } var displayName: String { get } var imageUrl: URL? { get } var eateryType: EateryType { get } var address: String { get } var paymentMethods: [PaymentMethod] { get } var location: CLLocation { get } var phone: String { get } var events: [DayString: [EventName: Event]] { get } var allEvents: [Event] { get } } /// Converts the date to its day for use with eatery events private let dayFormatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withFullDate, .withDashSeparatorInDate] formatter.timeZone = TimeZone(identifier: "America/New_York") return formatter }() // MARK: - Utils extension Eatery { /// The event at an exact date and time, or nil if such an event does not /// exist. func event(atExactly date: Date) -> Event? { return allEvents.first { $0.dateInterval.contains(date) } } /// The events that happen within the specified time interval, regardless of /// the day the event occurs on /// i.e. events that are active for any amount of time during the interval. func events(in dateInterval: DateInterval) -> [Event] { return allEvents.filter { dateInterval.intersects($0.dateInterval) } } /// The events by name that occur on the specified day // Since events may extend past midnight, this function is required to pick // a specific day for an event. func eventsByName(onDayOf date: Date) -> [EventName: Event] { let dayString = dayFormatter.string(from: date) return events[dayString] ?? [:] } func isOpen(onDayOf date: Date) -> Bool { return !eventsByName(onDayOf: date).isEmpty } func isOpenToday() -> Bool { return isOpen(onDayOf: Date()) } func isOpen(atExactly date: Date) -> Bool { return event(atExactly: date) != nil } func activeEvent(atExactly date: Date) -> Event? { let calendar = Calendar.current guard let yesterday = calendar.date(byAdding: .day, value: -1, to: date), let tomorrow = calendar.date(byAdding: .day, value: 1, to: date) else { return nil } return events(in: DateInterval(start: yesterday, end: tomorrow)) .filter { // disregard events that are not currently happening or that have happened in the past $0.occurs(atExactly: date) || date < $0.start }.min { (lhs, rhs) -> Bool in if lhs.occurs(atExactly: date) { return true } else if rhs.occurs(atExactly: date) { return false } let timeUntilLeftStart = lhs.start.timeIntervalSince(date) let timeUntilRightStart = rhs.start.timeIntervalSince(date) return timeUntilLeftStart < timeUntilRightStart } } func currentActiveEvent() -> Event? { return activeEvent(atExactly: Date()) } func status(onDayOf date: Date) -> EateryStatus { guard isOpen(onDayOf: date) else { return .closed } guard let event = activeEvent(atExactly: date) else { return .closed } switch event.status(atExactly: date) { case .notStarted: return .closed case .startingSoon: let minutesUntilOpen = Int(event.start.timeIntervalSinceNow / 60) + 1 return .openingSoon(minutesUntilOpen: minutesUntilOpen) case .started: return .open case .endingSoon: let minutesUntilClose = Int(event.end.timeIntervalSinceNow / 60) + 1 return .closingSoon(minutesUntilClose: minutesUntilClose) case .ended: return .closed } } func currentStatus() -> EateryStatus { return status(onDayOf: Date()) } } // MARK: - User Defaults / Favoriting extension Eatery { func isFavorite() -> Bool { return UserDefaults.standard.stringArray(forKey: "favorites")?.contains(name) ?? false } func setFavorite(_ newValue: Bool) { var ar = UserDefaults.standard.stringArray(forKey: "favorites") ?? [] if newValue { ar.append(name) } else { ar.removeAll(where: { $0 == name }) } UserDefaults.standard.set(ar, forKey: "favorites") NotificationCenter.default.post(name: .eateryIsFavoriteDidChange, object: self) } } extension NSNotification.Name { static let eateryIsFavoriteDidChange = NSNotification.Name("org.cuappdev.eatery.eateryIsFavoriteDidChangeNotificationName") } // MARK: - Presentation struct EateryPresentation { let statusText: String let statusColor: UIColor let nextEventText: String } private let timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() extension Eatery { func currentPresentation() -> EateryPresentation { let statusText: String let statusColor: UIColor let nextEventText: String switch currentStatus() { case let .openingSoon(minutesUntilOpen): statusText = "Opening" statusColor = .eateryOrange nextEventText = "in \(minutesUntilOpen)m" case .open: statusText = "Open" statusColor = .eateryGreen if let currentEvent = currentActiveEvent() { let endTimeText = timeFormatter.string(from: currentEvent.end) nextEventText = "until \(endTimeText)" } else { nextEventText = "" } case let .closingSoon(minutesUntilClose): statusText = "Closing" statusColor = .eateryOrange nextEventText = "in \(minutesUntilClose)m" case .closed: statusText = "Closed" statusColor = .eateryRed if isOpenToday(), let nextEvent = currentActiveEvent() { let startTimeText = timeFormatter.string(from: nextEvent.start) nextEventText = "until \(startTimeText)" } else { nextEventText = "today" } } return EateryPresentation(statusText: statusText, statusColor: statusColor, nextEventText: nextEventText) } }
mit
binarylevel/Tinylog-iOS
Tinylog/View Controllers/iPad/TLISplitViewController.swift
1
1590
// // TLISplitViewController.swift // Tinylog // // Created by Spiros Gerokostas on 18/10/15. // Copyright © 2015 Spiros Gerokostas. All rights reserved. // import UIKit class TLISplitViewController: UISplitViewController, UISplitViewControllerDelegate { var listsViewController:TLIListsViewController? var listViewController:TLITasksViewController? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) listsViewController = TLIListsViewController() listViewController = TLITasksViewController() let navigationController1:UINavigationController = UINavigationController(rootViewController: listsViewController!) let navigationController2:UINavigationController = UINavigationController(rootViewController: listViewController!) self.viewControllers = [navigationController1, navigationController2] self.delegate = self } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class func sharedSplitViewController()->TLISplitViewController { return TLIAppDelegate.sharedAppDelegate().window?.rootViewController as! TLISplitViewController } override func viewDidLoad() { super.viewDidLoad() } func splitViewController(svc: UISplitViewController, shouldHideViewController vc: UIViewController, inOrientation orientation: UIInterfaceOrientation) -> Bool { return false } }
mit
Turistforeningen/SjekkUT
ios/SjekkUt/model/ProjectExtension.swift
1
1537
// // ProjectExtension.swift // SjekkUt // // Created by Henrik Hartz on 20/04/2017. // Copyright © 2017 Den Norske Turistforening. All rights reserved. // import Foundation extension Project { class func fetchedResults() -> NSFetchedResultsController<Project> { let fetchRequest = Project.fetchRequest() let context = ModelController.instance.managedObjectContext! let results = NSFetchedResultsController.init(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) do { try results.performFetch() } catch(let error) { DntManager.logError(error) } return results } class var validProjectsPredicate:NSPredicate { get { let dateSpan = Project.validDateRange() let predicate = NSPredicate(format: "name != NULL AND isHidden = NO AND (start == NULL || start <= %@) AND (stop == NULL || stop >= %@)", argumentArray: [dateSpan.stop, dateSpan.start]) return predicate } } class var allProjectsPredicate:NSPredicate { get { let predicate = NSPredicate(format: "name != NULL") return predicate } } var isExpired: Bool { get { let expired = (stop?.timeIntervalSinceNow ?? Double.greatestFiniteMagnitude) < -TimeInterval(7 * 24 * 60 * 60) return expired } } static let placeholderImage = UIImage(named: "project-fallback")! }
mit
robbdimitrov/pixelgram-ios
PixelGram/Classes/Screens/Feed/UsersViewController.swift
1
5067
// // UsersViewController.swift // PixelGram // // Created by Robert Dimitrov on 11/21/17. // Copyright © 2017 Robert Dimitrov. All rights reserved. // import UIKit class UsersViewController: CollectionViewController { var viewModel: UsersViewModel? private var dataSource: CollectionViewDataSource? private var page: Int = 0 // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() setupRefreshControl() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadUsers(for: page) { [weak self] in self?.collectionView?.reloadData() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 70) } } // MARK: - Data override func handleRefresh(_ sender: UIRefreshControl) { page = 0 viewModel?.users.removeAll() loadUsers(for: page) { [weak self] in self?.collectionView?.reloadData() if self?.collectionView?.refreshControl?.isRefreshing ?? false { self?.collectionView?.refreshControl?.endRefreshing() } } } func loadUsers(for page: Int, limit: Int = 20, completionBlock: (() -> Void)?) { guard let imageId = viewModel?.imageId else { return } APIClient.shared.loadUsersLikedImage(withId: imageId, page: page, limit: limit, completion: { [weak self] users in self?.page = page self?.viewModel?.users.append(contentsOf: users) completionBlock?() }) { [weak self] error in self?.showError(error: error) } } // MARK: - Helpers func loadNextPage() { let oldCount = viewModel?.users.count ?? 0 loadUsers(for: page + 1) { [weak self] in let count = self?.viewModel?.users.count ?? 0 guard count > oldCount else { return } var indexPaths = [IndexPath]() for index in oldCount...(count - 1) { let indexPath = IndexPath(row: index, section: 0) indexPaths.append(indexPath) } self?.collectionView?.insertItems(at: indexPaths) } } // MARK: - Components func createDataSource() -> CollectionViewDataSource { let dataSource = CollectionViewDataSource(configureCell: { [weak self] (collectionView, indexPath) -> UICollectionViewCell in if indexPath.row == (self?.viewModel?.users.count ?? 0) - 1 { self?.loadNextPage() } return (self?.configureCell(collectionView: collectionView, indexPath: indexPath))! }, numberOfItems: { [weak self] (collectionView, section) -> Int in return self?.viewModel?.numberOfItems ?? 0 }) return dataSource } // MARK: - Cells func configureCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.reuseIdentifier, for: indexPath) if let cell = cell as? UserCell, let userViewModel = viewModel?.userViewModel(forIndex: indexPath.row) { cell.configure(with: userViewModel) } return cell } // MARK: - Reactive func handleCellSelection(collectionView: UICollectionView?) { collectionView?.rx.itemSelected.bind { [weak self] indexPath in self?.openUserProfile(atIndex: indexPath.item) }.disposed(by: disposeBag) } // MARK: - Navigation private func openUserProfile(atIndex index: Int) { if let userId = viewModel?.users[index].id { openUserProfile(withUserId: userId) } } private func openUserProfile(withUserId userId: String) { let viewController = instantiateViewController(withIdentifier: ProfileViewController.storyboardIdentifier) (viewController as? ProfileViewController)?.userId = userId navigationController?.pushViewController(viewController, animated: true) } // MARK: - Config func setupRefreshControl() { collectionView?.alwaysBounceVertical = true collectionView?.refreshControl = refreshControl } override func setupNavigationItem() { super.setupNavigationItem() title = "Likes" } override func configureCollectionView() { dataSource = createDataSource() collectionView?.dataSource = dataSource handleCellSelection(collectionView: collectionView) } }
mit
richardpiazza/LCARSDisplayKit
Sources/LCARSDisplayKit/Arc.swift
1
2971
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) import CoreGraphics import GraphPoint /// Arc of a circle (a continuous length around the circumference) public struct Arc: Graphable { public var size: CGSize = CGSize.zero public var radius: CGFloat = CGFloat(0) public var startDegree: CGFloat = CGFloat(0) public var endDegree: CGFloat = CGFloat(0) /// A `GraphPoint` used to verticaly/horizontaly clip the starting degree public var boundedStart: GraphPoint? /// A `GraphPoint` used to verticaly/horizontaly clip the ending degree public var boundedEnd: GraphPoint? public init() { } public init(radius: CGFloat, startDegree: CGFloat, endDegree: CGFloat) { self.radius = radius self.startDegree = startDegree self.endDegree = endDegree } /// The `GraphPoint` corresponding to the startDegree and radius public var startPoint: GraphPoint { if let boundedStart = self.boundedStart { return GraphPoint.graphPoint(degree: startDegree, radius: radius, boundedBy: boundedStart) } return GraphPoint.graphPoint(degree: startDegree, radius: radius) } /// The `GraphPoint` corresponding to the endDegree and radius public var endPoint: GraphPoint { if let boundedEnd = self.boundedEnd { return GraphPoint.graphPoint(degree: endDegree, radius: radius, boundedBy: boundedEnd) } return GraphPoint.graphPoint(degree: endDegree, radius: radius) } /// Calculates the point of the right angle that joins the start and end points. public var pivot: GraphPoint { let start = startPoint let end = endPoint var pivot = GraphPoint(x: 0, y: 0) if startDegree < 90 { pivot.x = end.x pivot.y = start.y } else if startDegree < 180 { pivot.x = start.x pivot.y = end.y } else if startDegree < 270 { pivot.x = end.x pivot.y = start.y } else { pivot.x = start.x pivot.y = end.y } return pivot } // MARK: - Graphable public var graphPoints: [GraphPoint] { return [startPoint, endPoint] } public var graphFrame: GraphFrame { return GraphFrame.graphFrame(graphPoints: graphPoints, radius: radius, startDegree: startDegree, endDegree: endDegree) } public var path: CGMutablePath { let path: CGMutablePath = CGMutablePath() let gf = graphFrame let offset = gf.graphOriginOffset let translatedPivot = gf.boundedPoint(graphPoint: pivot) path.addArc(center: offset, radius: radius, startAngle: startDegree.radians, endAngle: endDegree.radians, clockwise: false) path.addLine(to: translatedPivot) path.closeSubpath() return path } } #endif
mit
kevinmbeaulieu/Signal-iOS
Signal/src/UserInterface/Strings.swift
2
1011
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Strings re-used in multiple places should be added here. */ @objc class CallStrings: NSObject { static let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action") static let missedCallNotificationBody = NSLocalizedString("MISSED_CALL", comment: "notification title") static let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITH_NAME", comment: "notification title. Embeds {{Caller's Name}}") static let missedCallNotificationBodyWithoutCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITHOUT_NAME", comment: "notification title.") static let callStatusFormat = NSLocalizedString("CALL_STATUS_FORMAT", comment: "embeds {{Call Status}} in call screen label. For ongoing calls, {{Call Status}} is a seconds timer like 01:23, otherwise {{Call Status}} is a short text like 'Ringing', 'Busy', or 'Failed Call'") }
gpl-3.0
austinzheng/swift-compiler-crashes
crashes-duplicates/15200-swift-sourcemanager-getmessage.swift
11
206
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { enum b { deinit { class case ,
mit
austinzheng/swift-compiler-crashes
fixed/00020-swift-typechecker-conformstoprotocol.swift
11
189
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func g<h{class e{}e{
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/11005-swift-sourcemanager-getmessage.swift
11
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for in { func a { struct A { class B { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/21313-std-function-func-swift-type-subst.swift
10
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func h{class B<T where B:A{ var _=b var b:Int
mit
dangnguyenhuu/JSQMessagesSwift
Sources/Categories/JSQSystemSoundPlayer+Messages.swift
1
2094
// // JSQSystemSoundPlayer.swift // JSQMessagesViewController // // Created by Sylvain FAY-CHATELARD on 19/08/2015. // Copyright (c) 2015 Dviance. All rights reserved. // //import JSQSystemSoundPlayer_Swift // //let kJSQMessageReceivedSoundName = "message_received" //let kJSQMessageSentSoundName = "message_sent" // //extension JSQSystemSoundPlayer { // // public class func jsq_playMessageReceivedSound() { // // JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageReceivedSoundName, asAlert: false) // } // // public class func jsq_playMessageReceivedAlert() { // // JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageReceivedSoundName, asAlert: true) // } // // public class func jsq_playMessageSentSound() { // // JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageSentSoundName, asAlert: false) // } // // public class func jsq_playMessageSentAlert() { // // JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageSentSoundName, asAlert: true) // } // // fileprivate class func jsq_playSoundFromJSQMessagesBundle(name: String, asAlert: Bool) { // // // Save sound player original bundle // let originalPlayerBundleIdentifier = JSQSystemSoundPlayer.sharedPlayer.bundle // // if let bundle = Bundle.jsq_messagesBundle() { // // JSQSystemSoundPlayer.sharedPlayer.bundle = bundle // } // // let filename = "JSQMessagesAssets.bundle/Sounds/\(name)" // // if asAlert { // // JSQSystemSoundPlayer.sharedPlayer.playAlertSound(filename, fileExtension: JSQSystemSoundPlayer.TypeAIFF, completion: nil) // } // else { // // JSQSystemSoundPlayer.sharedPlayer.playSound(filename, fileExtension: JSQSystemSoundPlayer.TypeAIFF, completion: nil) // } // // JSQSystemSoundPlayer.sharedPlayer.bundle = originalPlayerBundleIdentifier // } //}
apache-2.0
raymondshadow/SwiftDemo
SwiftApp/Pods/Swiftz/Sources/Swiftz/EitherExt.swift
3
5841
// // EitherExt.swift // Swiftz // // Created by Robert Widmann on 6/21/15. // Copyright © 2015 TypeLift. All rights reserved. // #if SWIFT_PACKAGE import Operadics import Swiftx #endif extension Either /*: Bifunctor*/ { public typealias B = Any public typealias D = Any public typealias PAC = Either<L, R> public typealias PAD = Either<L, D> public typealias PBC = Either<B, R> public typealias PBD = Either<B, D> public func bimap<B, D>(_ f : (L) -> B, _ g : ((R) -> D)) -> Either<B, D> { switch self { case let .Left(bx): return Either<B, D>.Left(f(bx)) case let .Right(bx): return Either<B, D>.Right(g(bx)) } } public func leftMap<B>(_ f : @escaping (L) -> B) -> Either<B, R> { return self.bimap(f, identity) } public func rightMap(_ g : @escaping (R) -> D) -> Either<L, D> { return self.bimap(identity, g) } } extension Either /*: Functor*/ { public typealias FB = Either<L, B> public func fmap<B>(_ f : (R) -> B) -> Either<L, B> { return f <^> self } } extension Either /*: Pointed*/ { public typealias A = R public static func pure(_ r : R) -> Either<L, R> { return .Right(r) } } extension Either /*: Applicative*/ { public typealias FAB = Either<L, (R) -> B> public func ap<B>(_ f : Either<L, (R) -> B>) -> Either<L, B> { return f <*> self } } extension Either /*: Cartesian*/ { public typealias FTOP = Either<L, ()> public typealias FTAB = Either<L, (A, B)> public typealias FTABC = Either<L, (A, B, C)> public typealias FTABCD = Either<L, (A, B, C, D)> public static var unit : Either<L, ()> { return .Right(()) } public func product<B>(_ r : Either<L, B>) -> Either<L, (A, B)> { switch self { case let .Left(c): return .Left(c) case let .Right(d): switch r { case let .Left(e): return .Left(e) case let .Right(f): return .Right((d, f)) } } } public func product<B, C>(_ r : Either<L, B>, _ s : Either<L, C>) -> Either<L, (A, B, C)> { switch self { case let .Left(c): return .Left(c) case let .Right(d): switch r { case let .Left(e): return .Left(e) case let .Right(f): switch s { case let .Left(g): return .Left(g) case let .Right(h): return .Right((d, f, h)) } } } } public func product<B, C, D>(_ r : Either<L, B>, _ s : Either<L, C>, _ t : Either<L, D>) -> Either<L, (A, B, C, D)> { switch self { case let .Left(c): return .Left(c) case let .Right(d): switch r { case let .Left(e): return .Left(e) case let .Right(f): switch s { case let .Left(g): return .Left(g) case let .Right(h): switch t { case let .Left(i): return .Left(i) case let .Right(j): return .Right((d, f, h, j)) } } } } } } extension Either /*: ApplicativeOps*/ { public typealias C = Any public typealias FC = Either<L, C> public typealias FD = Either<L, D> public static func liftA<B>(_ f : @escaping (A) -> B) -> (Either<L, A>) -> Either<L, B> { return { (a : Either<L, A>) -> Either<L, B> in Either<L, (A) -> B>.pure(f) <*> a } } public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Either<L, A>) -> (Either<L, B>) -> Either<L, C> { return { (a : Either<L, A>) -> (Either<L, B>) -> Either<L, C> in { (b : Either<L, B>) -> Either<L, C> in f <^> a <*> b } } } public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> { return { (a : Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (b : Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (c : Either<L, C>) -> Either<L, D> in f <^> a <*> b <*> c } } } } } extension Either /*: Monad*/ { public func bind<B>(_ f : (A) -> Either<L, B>) -> Either<L, B> { return self >>- f } } extension Either /*: MonadOps*/ { public static func liftM<B>(_ f : @escaping (A) -> B) -> (Either<L, A>) -> Either<L, B> { return { (m1 : Either<L, A>) -> Either<L, B> in m1 >>- { (x1 : A) -> Either<L, B> in Either<L, B>.pure(f(x1)) } } } public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Either<L, A>) -> (Either<L, B>) -> Either<L, C> { return { (m1 : Either<L, A>) -> (Either<L, B>) -> Either<L, C> in { (m2 : Either<L, B>) -> Either<L, C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in Either<L, C>.pure(f(x1)(x2)) } } } } } public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> { return { (m1 : Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (m2 : Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (m3 : Either<L, C>) -> Either<L, D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in Either<L, D>.pure(f(x1)(x2)(x3)) } } } } } } } } public func >>->> <L, A, B, C>(_ f : @escaping (A) -> Either<L, B>, g : @escaping (B) -> Either<L, C>) -> ((A) -> Either<L, C>) { return { x in f(x) >>- g } } public func <<-<< <L, A, B, C>(g : @escaping (B) -> Either<L, C>, f : @escaping (A) -> Either<L, B>) -> ((A) -> Either<L, C>) { return f >>->> g } extension Either /*: Foldable*/ { public func foldr<B>(k : (A) -> (B) -> B, _ i : B) -> B { switch self { case .Left(_): return i case .Right(let y): return k(y)(i) } } public func foldl<B>(k : (B) -> (A) -> B, _ i : B) -> B { switch self { case .Left(_): return i case .Right(let y): return k(i)(y) } } public func foldMap<M : Monoid>(_ f : (A) -> M) -> M { switch self { case .Left(_): return M.mempty case .Right(let y): return f(y) } } } public func sequence<L, R>(_ ms : [Either<L, R>]) -> Either<L, [R]> { return ms.reduce(Either<L, [R]>.pure([]), { n, m in return n.bind { xs in return m.bind { x in return Either<L, [R]>.pure(xs + [x]) } } }) }
apache-2.0
deltaDNA/ios-sdk
DeltaDNA/NWPathProtocol.swift
1
210
import Network @available(iOS 12.0, *) internal protocol NWPathProtocol { var status: NWPath.Status { get } var isExpensive: Bool { get } } @available(iOS 12.0, *) extension NWPath: NWPathProtocol {}
apache-2.0
emilstahl/swift
validation-test/compiler_crashers_fixed/2103-swift-typebase-getcanonicaltype.swift
13
481
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol c { protocol C { typealias f : C { class d("[0x31] as String w>? { class func f<T, l func a() -> String { } extension Array { } protocol A { return NSData()) { class func d: a { } private class A : String { } } } } typealias B : f{ class B { } } } } if c {
apache-2.0
Nirma/UIDeviceComplete
Sources/DeviceFamily.swift
1
1724
// // DeviceFamily.swift // // Copyright (c) 2017-2019 Nicholas Maccharoli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public enum DeviceFamily: String { case iPhone case iPod case iPad case unknown public init(rawValue: String) { switch rawValue { case "iPhone": self = .iPhone case "iPod": self = .iPod case "iPad": self = .iPad default: self = .unknown } } } // MARK: Simulator Detection extension DeviceFamily { public var isSimulator: Bool { #if arch(i386) || arch(x86_64) return true #else return false #endif } }
mit
Jamonek/School-For-Me
School For Me/StringExt.swift
1
549
// // StringExt.swift // School For Me // // Created by Jamone Alexander Kelly on 1/7/16. // Copyright © 2016 Jamone Kelly. All rights reserved. // import Foundation import UIKit extension String { // phone number extension coming soon.. } extension NSAttributedString { convenience init?(string text:String, font:UIFont!, kerning: CGFloat!, color:UIColor!) { self.init(string: text, attributes: [NSAttributedStringKey.kern:kerning, NSAttributedStringKey.font:font, NSAttributedStringKey.foregroundColor:color]) } }
apache-2.0
mathcamp/swiftz
swiftz/Num.swift
2
2576
// // Num.swift // swiftz // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // // Num 'typeclass' public protocol Num { typealias N func zero() -> N func succ(n: N) -> N func add(x: N, y: N) -> N func multiply(x: N, y: N) -> N } public let nint8 = NInt8() public class NInt8: Num { public typealias N = Int8 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nint16 = NInt16() public class NInt16: Num { public typealias N = Int16 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nint32 = NInt32() public class NInt32: Num { public typealias N = Int32 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nint64 = NInt64() public class NInt64: Num { public typealias N = Int64 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nuint8 = NUInt8() public class NUInt8: Num { public typealias N = UInt8 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nuint16 = NUInt16() public class NUInt16: Num { public typealias N = UInt16 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nuint32 = NUInt32() public class NUInt32: Num { public typealias N = UInt32 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } } public let nuint64 = NUInt64() public class NUInt64: Num { public typealias N = UInt64 public func zero() -> N { return 0 } public func succ(n: N) -> N { return n + 1 } public func add(x: N, y: N) -> N { return x + y } public func multiply(x: N, y: N) -> N { return x * y } }
bsd-3-clause
GPWiOS/DouYuLive
DouYuTV/DouYuTV/AppDelegate.swift
1
2171
// // AppDelegate.swift // DouYuTV // // Created by GaiPengwei on 2017/4/24. // Copyright © 2017年 GaiPengwei. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UITabBar.appearance().tintColor = UIColor.orange 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ifelseboyxx/xx_Notes
contents/XcodeTemplate/Template/CustomVC.xctemplate/CustomVCSwift/___FILEBASENAME___.swift
1
3111
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // /* * .,:,,, .::,,,::. * .::::,,;;, .,;;:,,....:i: * :i,.::::,;i:. ....,,:::::::::,.... .;i:,. ......;i. * :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i. * ;;..,::::;;;;ri,,,. ..,,:;s1s1ssrr;,.;r, * :;. ,::;ii;:, . ................... .;iirri;;;,,;i, * ,i. .;ri:. ... ............................ .,,:;:,,,;i: * :s,.;r:... ....................................... .::;::s; * ,1r::. .............,,,.,,:,,........................,;iir; * ,s;........... ..::.,;:,,. ...............,;1s * :i,..,. .,:,,::,. .......... .......;1, * ir,....:rrssr;:, ,,.,::. .r5S9989398G95hr;. ....,.:s, * ;r,..,s9855513XHAG3i .,,,,,,,. ,S931,.,,.;s;s&BHHA8s.,..,..:r: * :r;..rGGh, :SAG;;G@BS:.,,,,,,,,,.r83: hHH1sXMBHHHM3..,,,,.ir. * ,si,.1GS, sBMAAX&MBMB5,,,,,,:,,.:&8 3@HXHBMBHBBH#X,.,,,,,,rr * ;1:,,SH: .A@&&B#&8H#BS,,,,,,,,,.,5XS, 3@MHABM&59M#As..,,,,:,is, * .rr,,,;9&1 hBHHBB&8AMGr,,,,,,,,,,,:h&&9s; r9&BMHBHMB9: . .,,,,;ri. * :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr. ...,:rs. * ;s. .:sS8G8GG889hi. ....,,:;:,.:irssrriii:,. ...,,i1, * ;1, ..,....,,isssi;, .,,. ....,.i1, * ;h: i9HHBMBBHAX9: . ...,,,rs, * ,1i.. :A#MBBBBMHB##s ....,,,;si. * .r1,.. ,..;3BMBBBHBB#Bh. .. ....,,,,,i1; * :h;.. .,..;,1XBMMMMBXs,.,, .. :: ,. ....,,,,,,ss. * ih: .. .;;;, ;;:s58A3i,.. ,. ,.:,,. ...,,,,,:,s1, * .s1,.... .,;sh, ,iSAXs;. ,. ,,.i85 ...,,,,,,:i1; * .rh: ... rXG9XBBM#M#MHAX3hss13&&HHXr .....,,,,,,,ih; * .s5: ..... i598X&&A&AAAAAA&XG851r: ........,,,,:,,sh; * . ihr, ... . .. ........,,,,,;11:. * ,s1i. ... ..,,,..,,,.,,.,,.,.. ........,,.,,.;s5i. * .:s1r,...................... ..............;shs, * . .:shr:. .... ..............,ishs. * .,issr;,... ...........................,is1s;. * .,is1si;:,....................,:;ir1sr;, * ..:isssssrrii;::::::;;iirsssssr;:.. * .,::iiirsssssssssrri;;:. */ import UIKit class ___FILEBASENAMEASIDENTIFIER___: UIViewController { //MARK: - LifeCyle override func viewDidLoad() { super.viewDidLoad() } deinit { print("\(object_getClassName(self)) - 释放了!") } //MARK: - Intial Methods //MARK: - Target Methods //MARK: - Private Method //MARK: - Setter Getter Methods //MARK: - External Delegate }
mit
shaps80/InkKit
Pod/Classes/GridLayout.swift
1
109
// // GridLayout.swift // Pods // // Created by Shahpour Benkau on 11/05/2017. // // import CoreGraphics
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/26008-swift-modulefile-getdecl.swift
1
422
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck T> class B{var d={{{}}{
apache-2.0
ben-ng/swift
test/Interpreter/protocol_extensions.swift
10
4915
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // Extend a protocol with a property. extension Sequence { final var myCount: Int { var result = 0 for _ in self { result += 1 } return result } } // CHECK: 4 print(["a", "b", "c", "d"].myCount) // Extend a protocol with a function. extension Collection { final var myIndices: Range<Index> { return startIndex..<endIndex } func clone() -> Self { return self } } // CHECK: 4 print(["a", "b", "c", "d"].clone().myCount) extension Sequence { final public func myEnumerated() -> EnumeratedSequence<Self> { return self.enumerated() } } // CHECK: (0, a) // CHECK-NEXT: (1, b) // CHECK-NEXT: (2, c) for (index, element) in ["a", "b", "c"].myEnumerated() { print("(\(index), \(element))") } extension Sequence { final public func myReduce<T>( _ initial: T, combine: (T, Self.Iterator.Element) -> T ) -> T { var result = initial for value in self { result = combine(result, value) } return result } } // CHECK: 15 print([1, 2, 3, 4, 5].myReduce(0, combine: +)) extension Sequence { final public func myZip<S : Sequence>(_ s: S) -> Zip2Sequence<Self, S> { return Zip2Sequence(_sequence1: self, _sequence2: s) } } // CHECK: (1, a) // CHECK-NEXT: (2, b) // CHECK-NEXT: (3, c) for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) { print("(\(a), \(b))") } // Mutating algorithms. extension MutableCollection where Self: RandomAccessCollection, Self.Iterator.Element : Comparable { public final mutating func myPartition() -> Index { let first = self.first return self.partition(by: { $0 >= first! }) } } extension RangeReplaceableCollection { public final func myJoin<S : Sequence where S.Iterator.Element == Self>( _ elements: S ) -> Self { var result = Self() var iter = elements.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: self) result.append(contentsOf: next) } } return result } } // CHECK: a,b,c print( String( ",".characters.myJoin(["a".characters, "b".characters, "c".characters]) ) ) // Constrained extensions for specific types. extension Collection where Self.Iterator.Element == String { final var myCommaSeparatedList: String { if startIndex == endIndex { return "" } var result = "" var first = true for x in self { if first { first = false } else { result += ", " } result += x } return result } } // CHECK: x, y, z print(["x", "y", "z"].myCommaSeparatedList) // CHECK: {{[tuv], [tuv], [tuv]}} print((["t", "u", "v"] as Set).myCommaSeparatedList) // Existentials protocol ExistP1 { func existP1() } extension ExistP1 { final func runExistP1() { print("runExistP1") self.existP1() } } struct ExistP1_Struct : ExistP1 { func existP1() { print(" - ExistP1_Struct") } } class ExistP1_Class : ExistP1 { func existP1() { print(" - ExistP1_Class") } } // CHECK: runExistP1 // CHECK-NEXT: - ExistP1_Struct var existP1: ExistP1 = ExistP1_Struct() existP1.runExistP1() // CHECK: runExistP1 // CHECK-NEXT: - ExistP1_Class existP1 = ExistP1_Class() existP1.runExistP1() protocol P { mutating func setValue(_ b: Bool) func getValue() -> Bool } extension P { final var extValue: Bool { get { return getValue() } set(newValue) { setValue(newValue) } } } extension Bool : P { mutating func setValue(_ b: Bool) { self = b } func getValue() -> Bool { return self } } class C : P { var theValue: Bool = false func setValue(_ b: Bool) { theValue = b } func getValue() -> Bool { return theValue } } func toggle(_ value: inout Bool) { value = !value } var p: P = true // CHECK: Bool print("Bool") // CHECK: true p.extValue = true print(p.extValue) // CHECK: false p.extValue = false print(p.extValue) // CHECK: true toggle(&p.extValue) print(p.extValue) // CHECK: C print("C") p = C() // CHECK: true p.extValue = true print(p.extValue) // CHECK: false p.extValue = false print(p.extValue) // CHECK: true toggle(&p.extValue) print(p.extValue) // Logical lvalues of existential type. struct HasP { var _p: P var p: P { get { return _p } set { _p = newValue } } } var hasP = HasP(_p: false) // CHECK: true hasP.p.extValue = true print(hasP.p.extValue) // CHECK: false toggle(&hasP.p.extValue) print(hasP.p.extValue) // rdar://problem/20739719 class Super: Init { required init(x: Int) { print("\(x) \(type(of: self))") } } class Sub: Super {} protocol Init { init(x: Int) } extension Init { init() { self.init(x: 17) } } // CHECK: 17 Super _ = Super() // CHECK: 17 Sub _ = Sub() // CHECK: 17 Super var sup: Super.Type = Super.self _ = sup.init() // CHECK: 17 Sub sup = Sub.self _ = sup.init() // CHECK: DONE print("DONE")
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/18441-no-stacktrace.swift
11
255
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for in { case let { protocol a { enum e { func b { [ { class A { var b { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/16337-swift-sourcemanager-getmessage.swift
11
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { for { struct A { class A { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/06332-swift-constraints-constraintgraph-removeconstraint.swift
11
243
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<b> () { class A { func b struct B var b = B class A { func a<T : a
mit
cnoon/swift-compiler-crashes
crashes-duplicates/18631-swift-sourcemanager-getmessage.swift
11
218
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum e { func b { ( var { class C { class case ,
mit
rakaramos/networklayer
NetworkLayer/Request/BaseRequest.swift
1
3231
import Foundation public class BaseRequest: NSOperation { var theURL = NSURL() var bandwidth: Double { return benchmark.bandwidth(incomingData) } private let incomingData = NSMutableData() private var sessionTask: NSURLSessionTask? private var benchmark: Benchmark = Benchmark() private var localURLSession: NSURLSession { return NSURLSession(configuration: localConfig, delegate: self, delegateQueue: nil) } private var localConfig: NSURLSessionConfiguration { return NSURLSessionConfiguration.defaultSessionConfiguration() } var average: Double { get { return benchmark.average } } var innerFinished: Bool = false { didSet { if(innerFinished) { benchmark.stop() } } } override public var finished: Bool { get { return innerFinished } //Note that I am triggering a KVO notification on isFinished as opposed to finished which is what the property name is. This seems to be a Swift-ism as the NSOperation get accessor is called isFinished instead of getFinished and I suspect that is part of why I need to tickle the accessor name instead of the property name. set (newValue) { willChangeValueForKey("isFinished") innerFinished = newValue didChangeValueForKey("isFinished") } } convenience public init(URL: NSURL) { self.init() self.theURL = URL } override public func start() { print("Start fetching \(theURL)") if cancelled { finished = true return } let request = NSMutableURLRequest(URL: theURL) sessionTask = localURLSession.dataTaskWithRequest(request) sessionTask?.resume() } func finish() { finished = true sessionTask?.cancel() } } extension BaseRequest: NSURLSessionDelegate { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { print("Start downloading \(theURL) \(queuePriority.rawValue)") benchmark.start() if cancelled { finish() return } //Check the response code and react appropriately completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if cancelled { finish() return } incomingData.appendData(data) benchmark.tick(incomingData, feshData: data) } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { defer { finished = true } if cancelled { sessionTask?.cancel() return } if NSThread.isMainThread() { print("Main Thread!") } if error != nil { print("Failed to receive response: \(error)") return } //processData() } }
mit
SuPair/VPNOn
VPNOnKit/VPNManager.swift
1
7157
// // VPNManager.swift // VPNOn // // Created by Lex Tang on 12/5/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import Foundation import NetworkExtension import CoreData let kAppGroupIdentifier = "group.VPNOn" final public class VPNManager { lazy var manager: NEVPNManager = { return NEVPNManager.sharedManager() }() lazy var defaults: NSUserDefaults = { return NSUserDefaults(suiteName: kAppGroupIdentifier)! }() public lazy var wormhole: Wormhole = { return Wormhole(appGroupIdentifier: kAppGroupIdentifier, messageDirectoryName: "Wormhole") }() public var status: NEVPNStatus { get { return manager.connection.status } } private let kVPNOnDisplayFlags = "displayFlags" public var displayFlags: Bool { get { if let value = defaults.objectForKey(kVPNOnDisplayFlags) as! Int? { return Bool(value) } return true } set { defaults.setObject(Int(newValue), forKey: kVPNOnDisplayFlags) defaults.synchronize() } } public class var sharedManager : VPNManager { struct Static { static let sharedInstance : VPNManager = { let instance = VPNManager() instance.manager.loadFromPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { debugPrint("Failed to load preferences: \(err.localizedDescription)") } } instance.manager.localizedDescription = "VPN On" instance.manager.enabled = true return instance }() } return Static.sharedInstance } public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) { let p = NEVPNProtocolIPSec() p.authenticationMethod = NEVPNIKEAuthenticationMethod.None p.useExtendedAuthentication = true p.serverAddress = server p.disconnectOnSleep = !alwaysOn manager.localizedDescription = "VPN On - \(title)" if let grp = group { p.localIdentifier = grp } else { p.localIdentifier = "VPN" } if let username = account { p.username = username } if let password = passwordRef { p.passwordReference = password } if let secret = secretRef { p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret p.sharedSecretReference = secret } if let certficiateData = certificate { p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate p.identityData = certficiateData } manager.enabled = true manager.`protocol` = p configOnDemand() #if (arch(i386) || arch(x86_64)) && os(iOS) // #if TARGET_IPHONE_SIMULATOR for Swift print("I'm afraid you can not connect VPN in simulators.") #else manager.saveToPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { debugPrintln("Failed to save profile: \(err.localizedDescription)") } else { var connectError : NSError? self.manager.connection.startVPNTunnelAndReturnError(&connectError) if let connectErr = connectError { debugPrintln("Failed to start tunnel: \(connectErr.localizedDescription)") } } } #endif } public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) { let p = NEVPNProtocolIKEv2() p.authenticationMethod = NEVPNIKEAuthenticationMethod.None p.useExtendedAuthentication = true p.serverAddress = server p.remoteIdentifier = server p.disconnectOnSleep = !alwaysOn p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium // TODO: Add an option into config page manager.localizedDescription = "VPN On - \(title)" if let grp = group { p.localIdentifier = grp } else { p.localIdentifier = "VPN" } if let username = account { p.username = username } if let password = passwordRef { p.passwordReference = password } if let secret = secretRef { p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret p.sharedSecretReference = secret } if let certficiateData = certificate { p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate p.serverCertificateCommonName = server p.serverCertificateIssuerCommonName = server p.identityData = certficiateData } manager.enabled = true manager.`protocol` = p configOnDemand() manager.saveToPreferencesWithCompletionHandler { (error: NSError!) -> Void in if let err = error { debugPrint("Failed to save profile: \(err.localizedDescription)") } else { var connectError : NSError? do { try self.manager.connection.startVPNTunnelAndReturnError() } catch var error as NSError { connectError = error if let connectErr = connectError { debugPrint("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)") } } catch { fatalError() } } } } public func configOnDemand() { if onDemandDomainsArray.count > 0 && onDemand { let connectionRule = NEEvaluateConnectionRule( matchDomains: onDemandDomainsArray, andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded ) let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection() ruleEvaluateConnection.connectionRules = [connectionRule] manager.onDemandRules = [ruleEvaluateConnection] manager.onDemandEnabled = true } else { manager.onDemandRules = [AnyObject]() manager.onDemandEnabled = false } } public func disconnect() { manager.connection.stopVPNTunnel() } public func removeProfile() { manager.removeFromPreferencesWithCompletionHandler { (error: NSError!) -> Void in } } }
mit
masters3d/xswift
exercises/hamming/Tests/HammingTests/HammingTests.swift
3
2157
import XCTest @testable import Hamming class HammingTests: XCTestCase { func testNoDifferenceBetweenEmptyStrands() { let result = Hamming.compute("", against: "")! let expected = 0 XCTAssertEqual(expected, result) } func testNoDifferenceBetweenIdenticalStrands() { let result = Hamming.compute("GGACTGA", against:"GGACTGA")! let expected = 0 XCTAssertEqual(expected, result) } func testCompleteHammingDistanceInSmallStrand() { let result = Hamming.compute("ACT", against: "GGA")! let expected = 3 XCTAssertEqual(expected, result) } func testSmallHammingDistanceInMiddleSomewhere() { let result = Hamming.compute("GGACG", against:"GGTCG")! let expected = 1 XCTAssertEqual(expected, result) } func testLargerDistance() { let result = Hamming.compute("ACCAGGG", against:"ACTATGG")! let expected = 2 XCTAssertEqual(expected, result) } func testReturnsNilWhenOtherStrandLonger() { let result = Hamming.compute("AAACTAGGGG", against:"AGGCTAGCGGTAGGAC") XCTAssertNil(result, "Different length strands return nil") } func testReturnsNilWhenOriginalStrandLonger() { let result = Hamming.compute("GACTACGGACAGGGTAGGGAAT", against:"GACATCGCACACC") XCTAssertNil(result, "Different length strands return nil") } static var allTests: [(String, (HammingTests) -> () throws -> Void)] { return [ ("testNoDifferenceBetweenEmptyStrands", testNoDifferenceBetweenEmptyStrands), ("testNoDifferenceBetweenIdenticalStrands", testNoDifferenceBetweenIdenticalStrands), ("testCompleteHammingDistanceInSmallStrand", testCompleteHammingDistanceInSmallStrand), ("testSmallHammingDistanceInMiddleSomewhere", testSmallHammingDistanceInMiddleSomewhere), ("testLargerDistance", testLargerDistance), ("testReturnsNilWhenOtherStrandLonger", testReturnsNilWhenOtherStrandLonger), ("testReturnsNilWhenOriginalStrandLonger", testReturnsNilWhenOriginalStrandLonger), ] } }
mit
auth0/Lock.swift
Lock/DatabasePresenter.swift
1
16523
// DatabasePresenter.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import SafariServices class DatabasePresenter: Presentable, Loggable { let database: DatabaseConnection let options: Options let style: Style var authenticator: DatabaseAuthenticatable var creator: DatabaseUserCreator var navigator: Navigable var messagePresenter: MessagePresenter? { didSet { self.authPresenter?.messagePresenter = self.messagePresenter } } var authPresenter: AuthPresenter? var enterpriseInteractor: EnterpriseDomainInteractor? var initialEmail: String? { return self.authenticator.validEmail ? self.authenticator.email : nil } var initialUsername: String? { return self.authenticator.validUsername ? self.authenticator.username : nil } weak var databaseView: DatabaseOnlyView? var currentScreen: DatabaseScreen? convenience init(interactor: DatabaseInteractor, connection: DatabaseConnection, navigator: Navigable, options: Options, style: Style) { self.init(authenticator: interactor, creator: interactor, connection: connection, navigator: navigator, options: options, style: style) } init(authenticator: DatabaseAuthenticatable, creator: DatabaseUserCreator, connection: DatabaseConnection, navigator: Navigable, options: Options, style: Style) { self.authenticator = authenticator self.creator = creator self.database = connection self.navigator = navigator self.options = options self.style = style } var view: View { let initialScreen = self.options.initialScreen let allow = self.options.allow let database = DatabaseOnlyView(allowedModes: allow) database.navigator = self.navigator database.switcher?.onSelectionChange = { [unowned self, weak database] switcher in let selected = switcher.selected guard let view = database else { return } self.logger.debug("selected \(selected)") self.navigator.resetScroll(false) switch selected { case .signup: self.showSignup(inView: view, username: self.initialUsername, email: self.initialEmail) case .login: self.showLogin(inView: view, identifier: self.authenticator.identifier) } } if allow.contains(.Login) && initialScreen == .login { database.switcher?.selected = .login showLogin(inView: database, identifier: authenticator.identifier) } else if allow.contains(.Signup) && (initialScreen == .signup || !allow.contains(.Login)) { database.switcher?.selected = .signup showSignup(inView: database, username: initialUsername, email: initialEmail) } self.databaseView = database return database } private func showLogin(inView view: DatabaseView, identifier: String?) { self.messagePresenter?.hideCurrent() let authCollectionView = self.authPresenter?.newViewToEmbed(withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20), isLogin: true) let style = self.database.requiresUsername ? self.options.usernameStyle : [.Email] view.showLogin(withIdentifierStyle: style, identifier: identifier, authCollectionView: authCollectionView, showPassword: self.options.allowShowPassword) self.currentScreen = .login let form = view.form form?.onValueChange = self.handleInput form?.onSubmit = { [weak form] input in form?.onValueChange(input) guard let attribute = self.getUserAttribute(from: input.type) else { return false } do { try self.authenticator.update(attribute, value: input.text) return true } catch { return false } } let action = { [weak form] (button: PrimaryButton) in guard let isValid = form?.shouldSubmit(), isValid else { return } self.messagePresenter?.hideCurrent() self.logger.info("Perform login for email: \(self.authenticator.email.verbatim())") button.inProgress = true let errorHandler: (LocalizableError?) -> Void = { error in Queue.main.async { button.inProgress = false guard let error = error else { self.logger.debug("Logged in!") let message = "You have logged in successfully.".i18n(key: "com.auth0.lock.database.login.success.message", comment: "User logged in") if !self.options.autoClose { self.messagePresenter?.showSuccess(message) } return } if case CredentialAuthError.multifactorRequired = error { self.navigator.navigate(.multifactor) return } else if case CredentialAuthError.multifactorTokenRequired(let token) = error { self.navigator.navigate(.multifactorWithToken(token)) return } else { form?.needsToUpdateState() self.messagePresenter?.showError(error) self.logger.error("Failed with error \(error)") } } } if let connection = self.enterpriseInteractor?.connection, let domain = self.enterpriseInteractor?.domain { if self.options.enterpriseConnectionUsingActiveAuth.contains(connection.name) { self.navigator.navigate(.enterpriseActiveAuth(connection: connection, domain: domain)) } else { self.enterpriseInteractor?.login(errorHandler) } } else { self.authenticator.login(errorHandler) } } let primaryButton = view.primaryButton view.form?.onReturn = { [weak primaryButton] field in guard let button = primaryButton, field.returnKey == .done else { return } // FIXME: Log warn action(button) } view.primaryButton?.onPress = action view.secondaryButton?.title = "Don’t remember your password?".i18n(key: "com.auth0.lock.database.button.forgot_password", comment: "Forgot password") view.secondaryButton?.color = .clear view.secondaryButton?.onPress = { _ in self.navigator.navigate(.forgotPassword) } } private func showSignup(inView view: DatabaseView, username: String?, email: String?) { self.messagePresenter?.hideCurrent() let authCollectionView = self.authPresenter?.newViewToEmbed(withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20), isLogin: false) let interactor = self.authenticator as? DatabaseInteractor let passwordPolicyValidator = interactor?.passwordValidator as? PasswordPolicyValidator self.currentScreen = .signup interactor?.user.reset() view.showSignUp(withUsername: self.database.requiresUsername, username: username, email: email, authCollectionView: authCollectionView, additionalFields: self.options.customSignupFields, passwordPolicyValidator: passwordPolicyValidator, showPassword: self.options.allowShowPassword, showTerms: options.showTerms || options.mustAcceptTerms) view.allFields?.filter { $0.text != nil && !$0.text!.isEmpty }.forEach(self.handleInput) let form = view.form view.form?.onValueChange = self.handleInput form?.onSubmit = { [weak form] input in form?.onValueChange(input) guard let attribute = self.getUserAttribute(from: input.type) else { return false } do { try self.authenticator.update(attribute, value: input.text) return true } catch { return false } } let action = { [weak form, weak view] (button: PrimaryButton) in guard let isValid = form?.shouldSubmit(), isValid else { return } self.messagePresenter?.hideCurrent() self.logger.info("Perform sign up for email \(self.creator.email.verbatim())") view?.allFields?.forEach { self.handleInput($0) } let interactor = self.creator button.inProgress = true interactor.create { createError, loginError in Queue.main.async { button.inProgress = false guard createError != nil || loginError != nil else { if !self.options.loginAfterSignup { let message = "Thanks for signing up.".i18n(key: "com.auth0.lock.database.signup.success.message", comment: "User signed up") if let databaseView = self.databaseView, self.options.allow.contains(.Login) { self.databaseView?.switcher?.selected = .login self.showLogin(inView: databaseView, identifier: self.creator.identifier) } if self.options.allow.contains(.Login) || !self.options.autoClose { self.messagePresenter?.showSuccess(message) } } return } if let error = loginError, case .multifactorRequired = error { self.navigator.navigate(.multifactor) return } else if let error = loginError, case .multifactorTokenRequired(let token) = error { self.navigator.navigate(.multifactorWithToken(token)) return } let error: LocalizableError = createError ?? loginError! form?.needsToUpdateState() self.messagePresenter?.showError(error) self.logger.error("Failed with error \(error)") } } } let checkTermsAndSignup = { [weak view] (button: PrimaryButton) in if self.options.mustAcceptTerms { let validForm = view?.allFields? .filter { !$0.state.isValid } .isEmpty ?? false if validForm { self.showTermsPrompt(atButton: button) { _ in action(button) } } } else { action(button) } } view.form?.onReturn = { [weak view] field in guard let button = view?.primaryButton, field.returnKey == .done else { return } // FIXME: Log warn checkTermsAndSignup(button) } view.primaryButton?.onPress = checkTermsAndSignup view.secondaryButton?.title = "By signing up, you agree to our terms of\n service and privacy policy".i18n(key: "com.auth0.lock.database.button.tos", comment: "tos & privacy") view.secondaryButton?.color = self.style.termsButtonColor view.secondaryButton?.titleColor = self.style.termsButtonTitleColor view.secondaryButton?.onPress = { button in let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.popoverPresentationController?.sourceView = button alert.popoverPresentationController?.sourceRect = button.bounds let cancel = UIAlertAction(title: "Cancel".i18n(key: "com.auth0.lock.database.tos.sheet.cancel", comment: "Cancel"), style: .cancel, handler: nil) let tos = UIAlertAction(title: "Terms of Service".i18n(key: "com.auth0.lock.database.tos.sheet.title", comment: "ToS"), style: .default, handler: safariBuilder(forURL: self.options.termsOfServiceURL as URL, navigator: self.navigator)) let privacy = UIAlertAction(title: "Privacy Policy".i18n(key: "com.auth0.lock.database.tos.sheet.privacy", comment: "Privacy"), style: .default, handler: safariBuilder(forURL: self.options.privacyPolicyURL as URL, navigator: self.navigator)) [cancel, tos, privacy].forEach { alert.addAction($0) } self.navigator.present(alert) } } private func handleInput(_ input: InputField) { self.messagePresenter?.hideCurrent() self.logger.verbose("new value: \(input.text.verbatim()) for type: \(input.type)") guard let attribute = getUserAttribute(from: input.type) else { return } var updateHRD: Bool = false switch attribute { case .email: updateHRD = true case .emailOrUsername: updateHRD = true default: break } do { try self.authenticator.update(attribute, value: input.text) input.showValid() if self.currentScreen == .login && updateHRD { try? self.enterpriseInteractor?.updateEmail(input.text) if let connection = self.enterpriseInteractor?.connection { self.logger.verbose("Enterprise connection detected: \(connection)") if self.databaseView?.ssoBar == nil { self.databaseView?.presentEnterprise() } } else { self.databaseView?.removeEnterprise() } } } catch let error as InputValidationError { input.showError(error.localizedMessage(withConnection: self.database)) } catch { input.showError() } } private func getUserAttribute(from inputType: InputField.InputType) -> UserAttribute? { switch inputType { case .email: return .email case .emailOrUsername: return .emailOrUsername case .password: return .password(enforcePolicy: self.currentScreen == .signup) case .username: return .username case .custom(let name, _, _, let storage, _, _, _, _, _, _, _): return .custom(name: name, storage: storage) default: return nil } } func showTermsPrompt(atButton button: PrimaryButton, successHandler: @escaping (PrimaryButton) -> Void) { let terms = "Terms & Policy".i18n(key: "com.auth0.lock.database.button.tos.title", comment: "tos title") let alert = UIAlertController(title: terms, message: "By signing up, you agree to our terms of\n service and privacy policy".i18n(key: "com.auth0.lock.database.button.tos", comment: "tos & privacy"), preferredStyle: .alert) alert.popoverPresentationController?.sourceView = button alert.popoverPresentationController?.sourceRect = button.bounds let cancelAction = UIAlertAction(title: "Cancel".i18n(key: "com.auth0.lock.database.tos.sheet.cancel", comment: "Cancel"), style: .cancel, handler: nil) let okAction = UIAlertAction(title: "Accept".i18n(key: "com.auth0.lock.database.tos.sheet.accept", comment: "Accept"), style: .default) { _ in successHandler(button) } [cancelAction, okAction].forEach { alert.addAction($0) } self.navigator.present(alert) } } private func safariBuilder(forURL url: URL, navigator: Navigable) -> (UIAlertAction) -> Void { return { _ in let safari = SFSafariViewController(url: url) navigator.present(safari) } }
mit
sstanic/Shopfred
Shopfred/Shopfred/Tools/SettingsData.swift
1
917
// // SettingsData.swift // Shopfred // // Created by Sascha Stanic on 7/9/17. // Copyright © 2017 Sascha Stanic. All rights reserved. // import Foundation import CoreData /** Management struct for core data entities. # Initializer - name: The name of the entity instance - displayText: The text that is displayed in the UI for an entity - type: The type of the entity */ struct SettingsData { // MARK: - Public Attributes var name: String! var displayText: String! var type: AnyObject.Type! // MARK: - Initializer init(name: String) { self.name = name self.displayText = name } init(name: String, displayText: String) { self.init(name: name) self.displayText = displayText } init(name: String, type: AnyObject.Type) { self.init(name: name) self.type = type } }
mit
sgtsquiggs/WordSearch
WordSearch/Puzzle.swift
1
2892
// // Puzzle.swift // WordSearch // // Created by Matthew Crenshaw on 11/7/15. // Copyright © 2015 Matthew Crenshaw. All rights reserved. // import Foundation /// ASSUMPTION: `character_grid` will always be a square 2d array struct Puzzle { let sourceLanguage: String let targetLanguage: String let word: String let characterGrid: [[String]] let wordLocations: [WordLocation] let rows: Int let columns: Int /// Decodes `Puzzle` from json. static func decodeJson(json: AnyObject) -> Puzzle? { guard let dict = json as? [String:AnyObject] else { assertionFailure("json is not a dictionary") return nil } guard let sourceLanguage_field: AnyObject = dict["source_language"] else { assertionFailure("field 'source_language' is mising") return nil } guard let sourceLanguage: String = String.decodeJson(sourceLanguage_field) else { assertionFailure("field 'source_language' is not a String") return nil } guard let targetLanguage_field: AnyObject = dict["target_language"] else { assertionFailure("field 'target_language' is mising") return nil } guard let targetLanguage: String = String.decodeJson(targetLanguage_field) else { assertionFailure("field 'target_language' is not a String") return nil } guard let word_field: AnyObject = dict["word"] else { assertionFailure("field 'word_field' is mising") return nil } guard let word: String = String.decodeJson(word_field) else { assertionFailure("field 'word_field' is not a String") return nil } guard let characterGrid_field: AnyObject = dict["character_grid"] else { assertionFailure("field 'character_grid' is missing") return nil } guard let characterGrid: [[String]] = Array.decodeJson({ Array.decodeJson({ String.decodeJson($0) }, $0) }, characterGrid_field) else { assertionFailure("field 'character_grid' is not a [[String]]") return nil } guard let wordLocations_field: AnyObject = dict["word_locations"] else { assertionFailure("field 'word_locations' is missing") return nil } guard let wordLocations: [WordLocation] = WordLocation.decodeJson(wordLocations_field) else { assertionFailure("field word_locations is not word locations") return nil } let rows = characterGrid.count let columns = characterGrid.first!.count return Puzzle(sourceLanguage: sourceLanguage, targetLanguage: targetLanguage, word: word, characterGrid: characterGrid, wordLocations: wordLocations, rows: rows, columns: columns) } }
mit
LamGiauKhongKhoTeam/LGKK
ModulesTests/CryptoSwiftTests/PBKDF.swift
1
4251
// // PBKDF.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 04/04/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import XCTest @testable import CryptoSwift class PBKDF: XCTestCase { func testPBKDF1() { let password: Array<UInt8> = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64] let salt: Array<UInt8> = [0x78, 0x57, 0x8E, 0x5A, 0x5D, 0x63, 0xCB, 0x06] let value = try! PKCS5.PBKDF1(password: password, salt: salt, iterations: 1000, keyLength: 16).calculate() XCTAssertEqual(value.toHexString(), "dc19847e05c64d2faf10ebfb4a3d2a20") } func testPBKDF2() { // P = "password", S = "salt", c = 1, dkLen = 20 XCTAssertEqual([0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 0x2f, 0xe0, 0x37, 0xa6], try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 1, keyLength: 20, variant: .sha1).calculate()) // P = "password", S = "salt", c = 2, dkLen = 20 XCTAssertEqual([0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57], try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 2, keyLength: 20, variant: .sha1).calculate()) // P = "password", S = "salt", c = 4096, dkLen = 20 XCTAssertEqual([0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0, 0x65, 0xa4, 0x29, 0xc1], try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 4096, keyLength: 20, variant: .sha1).calculate()) // P = "password", S = "salt", c = 16777216, dkLen = 20 // Commented because it takes a lot of time with Debug build to finish. // XCTAssertEqual([0xee, 0xfe, 0x3d, 0x61, 0xcd, 0x4d, 0xa4, 0xe4, 0xe9, 0x94, 0x5b, 0x3d, 0x6b, 0xa2, 0x15, 0x8c, 0x26, 0x34, 0xe9, 0x84], // try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 16777216, keyLength: 20, variant: .sha1).calculate()) // P = "passwordPASSWORDpassword", S = "saltSALTsaltSALTsaltSALTsaltSALTsalt", c = 4096, dkLen = 25 XCTAssertEqual([0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38], try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4F, 0x52, 0x44, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74], iterations: 4096, keyLength: 25, variant: .sha1).calculate()) // P = "pass\0word", S = "sa\0lt", c = 4096, dkLen = 16 XCTAssertEqual([0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3], try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x00, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x00, 0x6C, 0x74], iterations: 4096, keyLength: 16, variant: .sha1).calculate()) } func testPBKDF2Length() { let password: Array<UInt8> = Array("s33krit".utf8) let salt: Array<UInt8> = Array("nacl".utf8) let value = try! PKCS5.PBKDF2(password: password, salt: salt, iterations: 2, keyLength: 8, variant: .sha1).calculate() XCTAssert(value.toHexString() == "a53cf3df485e5cd9", "PBKDF2 fail") } func testPerformance() { let password: Array<UInt8> = Array("s33krit".utf8) let salt: Array<UInt8> = Array("nacl".utf8) measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in let _ = try! PKCS5.PBKDF2(password: password, salt: salt, iterations: 65536, keyLength: 32, variant: .sha1).calculate() }) } }
mit
vknabel/Taps
Tests/TapsTests/ReadmeExamples.swift
1
837
import RxSwift @testable import Taps import Dispatch fileprivate func async(_ call: @escaping () -> Void) { DispatchQueue.global().async { call() // Todo: Really async operation } } fileprivate func someInt() -> Int { return 1 } fileprivate struct MyService { func someObservable() -> Observable<Int> { return Observable.of(3, 4, 3) } } func describeReadmeExamples(t: Taps) { t.test("asynchronous test") { t in async { t.pass() t.end() } } t.test("synchronous test", plan: 1) { t in t.equal(someInt(), 1) } t.rx.test("reactive test") { (t: Test) -> Observable<Int> in let myService = MyService() return myService.someObservable() .test( onNext: t.equal(to: 3, "should only emit 3"), onError: t.fail(with: "should not throw") ) } }
mit
carlospaelinck/pokebattle
PokéBattle/PokémonInstance.swift
1
4574
// // PokémonInstance.swift // PokéBattle // // Created by Carlos Paelinck on 4/11/16. // Copyright © 2016 Carlos Paelinck. All rights reserved. // import Foundation class PokémonInstance: NSObject, NSCoding { var basePokémon: Pokémon var level: Int var nature: Nature var IVs: Stats var EVs: Stats var attacks: [Attack] init(basePokémon: Pokémon, level: Int, nature: Nature, IVs: Stats, EVs: Stats, attacks: [Attack]) { self.basePokémon = basePokémon self.level = level self.nature = nature self.IVs = IVs self.EVs = EVs self.attacks = attacks } required init?(coder aDecoder: NSCoder) { basePokémon = aDecoder.decodeObjectForKey("basePokémon") as! Pokémon level = aDecoder.decodeObjectForKey("level") as! Int IVs = aDecoder.decodeObjectForKey("IVs") as! Stats EVs = aDecoder.decodeObjectForKey("EVs") as! Stats attacks = aDecoder.decodeObjectForKey("attacks") as! [Attack] let natureValue = aDecoder.decodeObjectForKey("nature") as! Int nature = Nature(rawValue: natureValue)! } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(basePokémon, forKey: "basePokémon") aCoder.encodeObject(level, forKey: "level") aCoder.encodeObject(IVs, forKey: "IVs") aCoder.encodeObject(EVs, forKey: "EVs") aCoder.encodeObject(attacks, forKey: "attacks") aCoder.encodeObject(nature.rawValue, forKey: "nature") } var hitPoints: Double { let base = 2 * Double(basePokémon.stats.hitPoints) + Double(IVs.hitPoints) + floor(Double(EVs.hitPoints) / 4.0) return floor((floor(base * Double(level)) / 100) + Double(level) + 10.0) } var attack: Double { let natureMultiplier: Double switch nature { case .Adamant, .Brave, .Lonely, .Naughty: natureMultiplier = 1.1 case .Bold, .Modest, .Calm, .Timid: natureMultiplier = 0.9 default: natureMultiplier = 1 } let base = 2 * Double(basePokémon.stats.attack) + Double(IVs.attack) + floor(Double(EVs.attack) / 4.0) return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier) } var defense: Double { let natureMultiplier: Double switch nature { case .Bold, .Relaxed, .Impish, .Lax: natureMultiplier = 1.1 case .Lonely, .Hasty, .Mild, .Gentle: natureMultiplier = 0.9 default: natureMultiplier = 1 } let base = 2 * Double(basePokémon.stats.defense) + Double(IVs.defense) + floor(Double(EVs.defense) / 4.0) return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier) } var specialAttack: Double { let natureMultiplier: Double switch nature { case .Modest, .Mild, .Quiet, .Rash: natureMultiplier = 1.1 case .Adamant, .Jolly, .Impish, .Careful: natureMultiplier = 0.9 default: natureMultiplier = 1 } let base = 2 * Double(basePokémon.stats.specialAttack) + Double(IVs.specialAttack) + floor(Double(EVs.specialAttack) / 4.0) return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier) } var specialDefense: Double { let natureMultiplier: Double switch nature { case .Calm, .Careful, .Sassy, .Gentle: natureMultiplier = 1.1 case .Naughty, .Naive, .Rash, .Lax: natureMultiplier = 0.9 default: natureMultiplier = 1 } let base = 2 * Double(basePokémon.stats.specialDefense) + Double(IVs.specialDefense) + floor(Double(EVs.specialDefense) / 4.0) return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier) } var speed: Double { let natureMultiplier: Double switch nature { case .Timid, .Jolly, .Hasty, .Naive: natureMultiplier = 1.1 case .Quiet, .Sassy, .Brave, .Relaxed: natureMultiplier = 0.9 default: natureMultiplier = 1 } let base = 2 * Double(basePokémon.stats.speed) + Double(IVs.speed) + floor(Double(EVs.speed) / 4.0) return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier) } override var description: String { return "\(basePokémon.name) @ Lv.\(level)\n---\nHP: \(hitPoints)\nAtk: \(attack)\nDef: \(defense)\nSpAtk: \(specialAttack)\nSpDef: \(specialDefense)\nSpd: \(speed)" } }
mit
AlvinL33/TownHunt
TownHunt-1.9/TownHunt/PinPackMapViewController.swift
1
2300
// // PinPackMapViewController.swift // TownHunt // // Created by Alvin Lee on 07/04/2017. // Copyright © 2017 LeeTech. All rights reserved. // import MapKit import CoreData import Foundation class PinPackMapViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Returns an array of Pin Location objects func getListOfPinLocations(packData: [String: Any]) -> [PinLocation] { let packDetailPinList = packData["Pins"] as! [[String:String]] var gamePins: [PinLocation] = [] if packDetailPinList.isEmpty { print(packDetailPinList) print("No Pins in pack") } else{ print("There are pins in the loaded pack") for pin in packDetailPinList{ let pinToAdd = PinLocation(title: pin["Title"]!, hint: pin["Hint"]!, codeword: pin["Codeword"]!, coordinate: CLLocationCoordinate2D(latitude: Double(pin["CoordLatitude"]!)!, longitude: Double(pin["CoordLongitude"]!)!), pointVal: Int(pin["PointValue"]!)!) gamePins.append(pinToAdd) } } return gamePins } // Returns all of the pack data loaded from local storage func loadPackFromFile(filename: String, userPackDictName: String, selectedPackKey: String, userID: String) -> [String : AnyObject]{ var packData: [String : AnyObject] = [:] let defaults = UserDefaults.standard let localStorageHandler = LocalStorageHandler(fileName: filename, subDirectory: "User-\(userID)-Packs", directory: .documentDirectory) let retrievedJSON = localStorageHandler.retrieveJSONData() packData = retrievedJSON as! [String : AnyObject] return packData } func displayAlertMessage(alertTitle: String, alertMessage: String){ let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertCon, animated: true, completion: nil) } }
apache-2.0
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Data/CandleChartDataSet.swift
19
3016
// // CandleChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class CandleChartDataSet: BarLineScatterCandleChartDataSet { /// the width of the candle-shadow-line in pixels. /// :default: 3.0 public var shadowWidth = CGFloat(1.5) /// the space between the candle entries /// :default: 0.1 (10%) private var _bodySpace = CGFloat(0.1) /// the color of the shadow line public var shadowColor: UIColor? /// use candle color for the shadow public var shadowColorSameAsCandle = false /// color for open <= close public var decreasingColor: UIColor? /// color for open > close public var increasingColor: UIColor? /// Are decreasing values drawn as filled? public var decreasingFilled = false /// Are increasing values drawn as filled? public var increasingFilled = true public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) } internal override func calcMinMax(#start: Int, end: Int) { if (yVals.count == 0) { return } var entries = yVals as! [CandleChartDataEntry] var endValue : Int if end == 0 { endValue = entries.count - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = entries[start].low _yMax = entries[start].high for (var i = start + 1; i <= endValue; i++) { var e = entries[i] if (e.low < _yMin) { _yMin = e.low } if (e.high > _yMax) { _yMax = e.high } } } /// the space that is left out on the left and right side of each candle, /// :default: 0.1 (10%), max 0.45, min 0.0 public var bodySpace: CGFloat { set { _bodySpace = newValue if (_bodySpace < 0.0) { _bodySpace = 0.0 } if (_bodySpace > 0.45) { _bodySpace = 0.45 } } get { return _bodySpace } } /// Is the shadow color same as the candle color? public var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle } /// Are increasing values drawn as filled? public var isIncreasingFilled: Bool { return increasingFilled; } /// Are decreasing values drawn as filled? public var isDecreasingFilled: Bool { return decreasingFilled; } }
mit