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
kevindelord/DKDBManager
Example/DBSwiftTest/ViewControllers/TableViewController.swift
1
631
// // UITableViewController.swift // DBSwiftTest // // Created by kevin delord on 22/01/16. // Copyright © 2016 Smart Mobile Factory. All rights reserved. // import UIKit import Foundation class TableViewController : UITableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } func didDeleteItemAtIndexPath(_ indexPath: IndexPath) { self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade) self.tableView.setEditing(false, animated: true) self.performBlock(afterDelay: 0.4, block: self.tableView.reloadData) } }
mit
whiteath/ReadFoundationSource
TestFoundation/TestHTTPCookie.swift
9
8081
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestHTTPCookie: XCTestCase { static var allTests: [(String, (TestHTTPCookie) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_RequestHeaderFields", test_RequestHeaderFields), ("test_cookiesWithResponseHeader1cookie", test_cookiesWithResponseHeader1cookie), ("test_cookiesWithResponseHeader0cookies", test_cookiesWithResponseHeader0cookies), ("test_cookiesWithResponseHeader2cookies", test_cookiesWithResponseHeader2cookies), ("test_cookiesWithResponseHeaderNoDomain", test_cookiesWithResponseHeaderNoDomain), ("test_cookiesWithResponseHeaderNoPathNoDomain", test_cookiesWithResponseHeaderNoPathNoDomain) ] } func test_BasicConstruction() { let invalidVersionZeroCookie = HTTPCookie(properties: [ .name: "TestCookie", .value: "Test value @#$%^$&*", .path: "/" ]) XCTAssertNil(invalidVersionZeroCookie) let minimalVersionZeroCookie = HTTPCookie(properties: [ .name: "TestCookie", .value: "Test value @#$%^$&*", .path: "/", .domain: "apple.com" ]) XCTAssertNotNil(minimalVersionZeroCookie) XCTAssert(minimalVersionZeroCookie?.name == "TestCookie") XCTAssert(minimalVersionZeroCookie?.value == "Test value @#$%^$&*") XCTAssert(minimalVersionZeroCookie?.path == "/") XCTAssert(minimalVersionZeroCookie?.domain == "apple.com") let versionZeroCookieWithOriginURL = HTTPCookie(properties: [ .name: "TestCookie", .value: "Test value @#$%^$&*", .path: "/", .originURL: URL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithOriginURL?.domain == "apple.com") // Domain takes precedence over originURL inference let versionZeroCookieWithDomainAndOriginURL = HTTPCookie(properties: [ .name: "TestCookie", .value: "Test value @#$%^$&*", .path: "/", .domain: "apple.com", .originURL: URL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithDomainAndOriginURL?.domain == "apple.com") // This is implicitly a v0 cookie. Properties that aren't valid for v0 should fail. let versionZeroCookieWithInvalidVersionOneProps = HTTPCookie(properties: [ .name: "TestCookie", .value: "Test value @#$%^$&*", .path: "/", .domain: "apple.com", .originURL: URL(string: "https://apple.com")!, .comment: "This comment should be nil since this is a v0 cookie.", .commentURL: URL(string: "https://apple.com")!, .discard: "TRUE", .expires: Date(timeIntervalSince1970: 1000), .maximumAge: "2000", .port: "443,8443", .secure: "YES" ]) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.comment) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.commentURL) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.isSessionOnly == true) // v0 should never use NSHTTPCookieMaximumAge XCTAssert( versionZeroCookieWithInvalidVersionOneProps?.expiresDate?.timeIntervalSince1970 == Date(timeIntervalSince1970: 1000).timeIntervalSince1970 ) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.portList) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.isSecure == true) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.version == 0) } func test_RequestHeaderFields() { let noCookies: [HTTPCookie] = [] XCTAssertEqual(HTTPCookie.requestHeaderFields(with: noCookies)["Cookie"], "") let basicCookies: [HTTPCookie] = [ HTTPCookie(properties: [ .name: "TestCookie1", .value: "testValue1", .path: "/", .originURL: URL(string: "https://apple.com")! ])!, HTTPCookie(properties: [ .name: "TestCookie2", .value: "testValue2", .path: "/", .originURL: URL(string: "https://apple.com")! ])!, ] let basicCookieString = HTTPCookie.requestHeaderFields(with: basicCookies)["Cookie"] XCTAssertEqual(basicCookieString, "TestCookie1=testValue1; TestCookie2=testValue2") } func test_cookiesWithResponseHeader1cookie() { let header = ["header1":"value1", "Set-Cookie": "fr=anjd&232; Max-Age=7776000; path=/; domain=.example.com; secure; httponly", "header2":"value2", "header3":"value3"] let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!) XCTAssertEqual(cookies.count, 1) XCTAssertEqual(cookies[0].name, "fr") XCTAssertEqual(cookies[0].value, "anjd&232") } func test_cookiesWithResponseHeader0cookies() { let header = ["header1":"value1", "header2":"value2", "header3":"value3"] let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!) XCTAssertEqual(cookies.count, 0) } func test_cookiesWithResponseHeader2cookies() { let header = ["header1":"value1", "Set-Cookie": "fr=a&2@#; Max-Age=1186000; path=/; domain=.example.com; secure, xd=plm!@#;path=/;domain=.example2.com", "header2":"value2", "header3":"value3"] let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!) XCTAssertEqual(cookies.count, 2) XCTAssertTrue(cookies[0].isSecure) XCTAssertFalse(cookies[1].isSecure) } func test_cookiesWithResponseHeaderNoDomain() { let header = ["header1":"value1", "Set-Cookie": "fr=anjd&232; expires=Wed, 21 Sep 2016 05:33:00 GMT; Max-Age=7776000; path=/; secure; httponly", "header2":"value2", "header3":"value3"] let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!) XCTAssertEqual(cookies[0].domain, "http://example.com") XCTAssertNotNil(cookies[0].expiresDate) let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O" formatter.timeZone = TimeZone(abbreviation: "GMT") if let expiresDate = formatter.date(from: "Wed, 21 Sep 2016 05:33:00 GMT") { XCTAssertTrue(expiresDate.compare(cookies[0].expiresDate!) == .orderedSame) } else { XCTFail("Unable to parse the given date from the formatter") } } func test_cookiesWithResponseHeaderNoPathNoDomain() { let header = ["header1":"value1", "Set-Cookie": "fr=tx; expires=Wed, 21-Sep-2016 05:33:00 GMT; Max-Age=7776000; secure; httponly", "header2":"value2", "header3":"value3"] let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!) XCTAssertEqual(cookies[0].domain, "http://example.com") XCTAssertEqual(cookies[0].path, "/") } }
apache-2.0
yonaskolb/XcodeGen
Sources/ProjectSpec/Target.swift
1
14555
import Foundation import JSONUtilities import XcodeProj import Version public struct LegacyTarget: Equatable { public static let passSettingsDefault = false public var toolPath: String public var arguments: String? public var passSettings: Bool public var workingDirectory: String? public init( toolPath: String, passSettings: Bool = passSettingsDefault, arguments: String? = nil, workingDirectory: String? = nil ) { self.toolPath = toolPath self.arguments = arguments self.passSettings = passSettings self.workingDirectory = workingDirectory } } extension LegacyTarget: PathContainer { static var pathProperties: [PathProperty] { [ .string("workingDirectory"), ] } } public struct Target: ProjectTarget { public var name: String public var type: PBXProductType public var platform: Platform public var settings: Settings public var sources: [TargetSource] public var dependencies: [Dependency] public var info: Plist? public var entitlements: Plist? public var transitivelyLinkDependencies: Bool? public var directlyEmbedCarthageDependencies: Bool? public var requiresObjCLinking: Bool? public var preBuildScripts: [BuildScript] public var postCompileScripts: [BuildScript] public var postBuildScripts: [BuildScript] public var buildRules: [BuildRule] public var configFiles: [String: String] public var scheme: TargetScheme? public var legacy: LegacyTarget? public var deploymentTarget: Version? public var attributes: [String: Any] public var productName: String public var onlyCopyFilesOnInstall: Bool public var isLegacy: Bool { legacy != nil } public var filename: String { var filename = productName if let fileExtension = type.fileExtension { filename += ".\(fileExtension)" } if type == .staticLibrary { filename = "lib\(filename)" } return filename } public init( name: String, type: PBXProductType, platform: Platform, productName: String? = nil, deploymentTarget: Version? = nil, settings: Settings = .empty, configFiles: [String: String] = [:], sources: [TargetSource] = [], dependencies: [Dependency] = [], info: Plist? = nil, entitlements: Plist? = nil, transitivelyLinkDependencies: Bool? = nil, directlyEmbedCarthageDependencies: Bool? = nil, requiresObjCLinking: Bool? = nil, preBuildScripts: [BuildScript] = [], postCompileScripts: [BuildScript] = [], postBuildScripts: [BuildScript] = [], buildRules: [BuildRule] = [], scheme: TargetScheme? = nil, legacy: LegacyTarget? = nil, attributes: [String: Any] = [:], onlyCopyFilesOnInstall: Bool = false ) { self.name = name self.type = type self.platform = platform self.deploymentTarget = deploymentTarget self.productName = productName ?? name self.settings = settings self.configFiles = configFiles self.sources = sources self.dependencies = dependencies self.info = info self.entitlements = entitlements self.transitivelyLinkDependencies = transitivelyLinkDependencies self.directlyEmbedCarthageDependencies = directlyEmbedCarthageDependencies self.requiresObjCLinking = requiresObjCLinking self.preBuildScripts = preBuildScripts self.postCompileScripts = postCompileScripts self.postBuildScripts = postBuildScripts self.buildRules = buildRules self.scheme = scheme self.legacy = legacy self.attributes = attributes self.onlyCopyFilesOnInstall = onlyCopyFilesOnInstall } } extension Target: CustomStringConvertible { public var description: String { "\(name): \(platform.rawValue) \(type)" } } extension Target: PathContainer { static var pathProperties: [PathProperty] { [ .dictionary([ .string("sources"), .object("sources", TargetSource.pathProperties), .string("configFiles"), .object("dependencies", Dependency.pathProperties), .object("info", Plist.pathProperties), .object("entitlements", Plist.pathProperties), .object("preBuildScripts", BuildScript.pathProperties), .object("prebuildScripts", BuildScript.pathProperties), .object("postCompileScripts", BuildScript.pathProperties), .object("postBuildScripts", BuildScript.pathProperties), .object("legacy", LegacyTarget.pathProperties), .object("scheme", TargetScheme.pathProperties), ]), ] } } extension Target { static func resolveMultiplatformTargets(jsonDictionary: JSONDictionary) -> JSONDictionary { guard let targetsDictionary: [String: JSONDictionary] = jsonDictionary["targets"] as? [String: JSONDictionary] else { return jsonDictionary } var crossPlatformTargets: [String: JSONDictionary] = [:] for (targetName, target) in targetsDictionary { if let platforms = target["platform"] as? [String] { for platform in platforms { var platformTarget = target platformTarget = platformTarget.expand(variables: ["platform": platform]) platformTarget["platform"] = platform let platformSuffix = platformTarget["platformSuffix"] as? String ?? "_\(platform)" let platformPrefix = platformTarget["platformPrefix"] as? String ?? "" let newTargetName = platformPrefix + targetName + platformSuffix var settings = platformTarget["settings"] as? JSONDictionary ?? [:] if settings["configs"] != nil || settings["groups"] != nil || settings["base"] != nil { var base = settings["base"] as? JSONDictionary ?? [:] if base["PRODUCT_NAME"] == nil { base["PRODUCT_NAME"] = targetName } settings["base"] = base } else { if settings["PRODUCT_NAME"] == nil { settings["PRODUCT_NAME"] = targetName } } platformTarget["productName"] = targetName platformTarget["settings"] = settings if let deploymentTargets = target["deploymentTarget"] as? [String: Any] { platformTarget["deploymentTarget"] = deploymentTargets[platform] } crossPlatformTargets[newTargetName] = platformTarget } } else { crossPlatformTargets[targetName] = target } } var merged = jsonDictionary merged["targets"] = crossPlatformTargets return merged } } extension Target: Equatable { public static func == (lhs: Target, rhs: Target) -> Bool { lhs.name == rhs.name && lhs.type == rhs.type && lhs.platform == rhs.platform && lhs.deploymentTarget == rhs.deploymentTarget && lhs.transitivelyLinkDependencies == rhs.transitivelyLinkDependencies && lhs.requiresObjCLinking == rhs.requiresObjCLinking && lhs.directlyEmbedCarthageDependencies == rhs.directlyEmbedCarthageDependencies && lhs.settings == rhs.settings && lhs.configFiles == rhs.configFiles && lhs.sources == rhs.sources && lhs.info == rhs.info && lhs.entitlements == rhs.entitlements && lhs.dependencies == rhs.dependencies && lhs.preBuildScripts == rhs.preBuildScripts && lhs.postCompileScripts == rhs.postCompileScripts && lhs.postBuildScripts == rhs.postBuildScripts && lhs.buildRules == rhs.buildRules && lhs.scheme == rhs.scheme && lhs.legacy == rhs.legacy && NSDictionary(dictionary: lhs.attributes).isEqual(to: rhs.attributes) } } extension LegacyTarget: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { toolPath = try jsonDictionary.json(atKeyPath: "toolPath") arguments = jsonDictionary.json(atKeyPath: "arguments") passSettings = jsonDictionary.json(atKeyPath: "passSettings") ?? LegacyTarget.passSettingsDefault workingDirectory = jsonDictionary.json(atKeyPath: "workingDirectory") } } extension LegacyTarget: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "toolPath": toolPath, "arguments": arguments, "workingDirectory": workingDirectory, ] if passSettings != LegacyTarget.passSettingsDefault { dict["passSettings"] = passSettings } return dict } } extension Target: NamedJSONDictionaryConvertible { public init(name: String, jsonDictionary: JSONDictionary) throws { let resolvedName: String = jsonDictionary.json(atKeyPath: "name") ?? name self.name = resolvedName productName = jsonDictionary.json(atKeyPath: "productName") ?? resolvedName let typeString: String = try jsonDictionary.json(atKeyPath: "type") if let type = PBXProductType(string: typeString) { self.type = type } else { throw SpecParsingError.unknownTargetType(typeString) } let platformString: String = try jsonDictionary.json(atKeyPath: "platform") if let platform = Platform(rawValue: platformString) { self.platform = platform } else { throw SpecParsingError.unknownTargetPlatform(platformString) } if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version.parse(string) } else if let double: Double = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version.parse(String(double)) } else { deploymentTarget = nil } settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:] if let source: String = jsonDictionary.json(atKeyPath: "sources") { sources = [TargetSource(path: source)] } else if let array = jsonDictionary["sources"] as? [Any] { sources = try array.compactMap { source in if let string = source as? String { return TargetSource(path: string) } else if let dictionary = source as? [String: Any] { return try TargetSource(jsonDictionary: dictionary) } else { return nil } } } else { sources = [] } if jsonDictionary["dependencies"] == nil { dependencies = [] } else { let dependencies: [Dependency] = try jsonDictionary.json(atKeyPath: "dependencies", invalidItemBehaviour: .fail) self.dependencies = dependencies.filter { [platform] dependency -> Bool in // If unspecified, all platforms are supported guard let platforms = dependency.platforms else { return true } return platforms.contains(platform) } } if jsonDictionary["info"] != nil { info = try jsonDictionary.json(atKeyPath: "info") as Plist } if jsonDictionary["entitlements"] != nil { entitlements = try jsonDictionary.json(atKeyPath: "entitlements") as Plist } transitivelyLinkDependencies = jsonDictionary.json(atKeyPath: "transitivelyLinkDependencies") directlyEmbedCarthageDependencies = jsonDictionary.json(atKeyPath: "directlyEmbedCarthageDependencies") requiresObjCLinking = jsonDictionary.json(atKeyPath: "requiresObjCLinking") preBuildScripts = jsonDictionary.json(atKeyPath: "preBuildScripts") ?? jsonDictionary.json(atKeyPath: "prebuildScripts") ?? [] postCompileScripts = jsonDictionary.json(atKeyPath: "postCompileScripts") ?? [] postBuildScripts = jsonDictionary.json(atKeyPath: "postBuildScripts") ?? jsonDictionary.json(atKeyPath: "postbuildScripts") ?? [] buildRules = jsonDictionary.json(atKeyPath: "buildRules") ?? [] scheme = jsonDictionary.json(atKeyPath: "scheme") legacy = jsonDictionary.json(atKeyPath: "legacy") attributes = jsonDictionary.json(atKeyPath: "attributes") ?? [:] onlyCopyFilesOnInstall = jsonDictionary.json(atKeyPath: "onlyCopyFilesOnInstall") ?? false } } extension Target: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "type": type.name, "platform": platform.rawValue, "settings": settings.toJSONValue(), "configFiles": configFiles, "attributes": attributes, "sources": sources.map { $0.toJSONValue() }, "dependencies": dependencies.map { $0.toJSONValue() }, "postCompileScripts": postCompileScripts.map { $0.toJSONValue() }, "prebuildScripts": preBuildScripts.map { $0.toJSONValue() }, "postbuildScripts": postBuildScripts.map { $0.toJSONValue() }, "buildRules": buildRules.map { $0.toJSONValue() }, "deploymentTarget": deploymentTarget?.deploymentTarget, "info": info?.toJSONValue(), "entitlements": entitlements?.toJSONValue(), "transitivelyLinkDependencies": transitivelyLinkDependencies, "directlyEmbedCarthageDependencies": directlyEmbedCarthageDependencies, "requiresObjCLinking": requiresObjCLinking, "scheme": scheme?.toJSONValue(), "legacy": legacy?.toJSONValue(), ] if productName != name { dict["productName"] = productName } if onlyCopyFilesOnInstall { dict["onlyCopyFilesOnInstall"] = true } return dict } }
mit
gameontext/sample-room-swift
Sources/SwiftRoom/Message.swift
1
14324
/** * Copyright IBM Corporation 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import SwiftyJSON import LoggerAPI public class Message { // The first segment in the WebSocket protocol for Game On! // This is used as a primitive routing filter as messages flow through the system public enum Target: String { case // Protocol acknowledgement, sent on RoomEndpoint.connected ack, // Message sent to player(s) player, // Message sent to a specific player to trigger a location change (they are allowed to exit the room) playerLocation, // Message sent to the room room, // A player enters the room roomHello, // A player reconnects to the room (e.g. reconnected session) roomJoin, // A player's has disconnected from the room without leaving it roomPart, // A player leaves the room roomGoodbye } let target: Target // Target id for the message (This room, specific player, or '*') let targetId: String // Stringified JSON payload let payload: String // userId and username will be present in JSON payload let userId: String? let username: String? // Parse a string read from the WebSocket public init(message: String) throws { // Expected format: // target,targetId,{"json": "payload"} guard let targetIndex = message.characters.index(of: ",") else { throw SwiftRoomError.invalidMessageFormat } let targetStr = message.substring(to: targetIndex) guard let targetVal = Target.init(rawValue: targetStr) else { throw SwiftRoomError.invalidMessageFormat } self.target = targetVal var remaining = message.substring(from: targetIndex).trimmingCharacters(in: .whitespacesAndNewlines) // remaining = `,targetId,{"json": "payload"}`. Now remove the ',' remaining.remove(at: remaining.startIndex) // Extract targetId guard let targetIdIndex = remaining.characters.index(of: ",") else { throw SwiftRoomError.invalidMessageFormat } self.targetId = remaining.substring(to: targetIdIndex) // Extract JSON guard let jsonIndex = remaining.characters.index(of: "{") else { throw SwiftRoomError.invalidMessageFormat } self.payload = remaining.substring(from: jsonIndex) guard let payloadJSON = payload.data(using: String.Encoding.utf8) else { throw SwiftRoomError.errorInJSONProcessing } let json = JSON(data: payloadJSON) self.userId = json["userId"].stringValue self.username = json["username"].stringValue } public init(target: Target, targetId: String? = "", payload: String) throws { self.target = target self.targetId = targetId! self.payload = payload guard let payloadJSON = payload.data(using: String.Encoding.utf8) else { throw SwiftRoomError.errorInJSONProcessing } let json = JSON(data: payloadJSON) self.userId = json["userId"].stringValue self.username = json["username"].stringValue } public static func createAckMessage() -> String { return Target.ack.rawValue + "," + "{\"version\":[1,2]}" } // Create an event targeted at a specific player (use broadcast to send to all connections) public static func createSpecificEvent(userId: String, messageForUser: String) throws -> Message { // player,<userId>,{ // "type": "event", // "content": { // "<userId>": "specific to player" // }, // "bookmark": "String representing last message seen" // } let payload: JSON = [ Constants.Message.type: Constants.Message.event, Constants.Message.content: [ userId: messageForUser ], Constants.Message.bookmark: Constants.Message.prefix + uniqueStr() ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.player, targetId: userId, payload: payloadStr) } // Construct an event that broadcasts to all players. The first string will // be the message sent to all players. Additional messages should be specified // in pairs afterwards, "userId1", "player message 1", "userId2", "player message 2". //If the optional specified messages are uneven, only the general message will be sent. public static func createBroadcastEvent(allContent: String? = "", pairs: [String]?) throws -> Message { // player,*,{ // "type": "event", // "content": { // "*": "general text for everyone", // "<userId>": "specific to player" // }, // "bookmark": "String representing last message seen" // } let payload: String = buildBroadcastContent(content: allContent, pairs: pairs) Log.info("creating broadcast event with payload: \(payload)") return try Message(target: Target.player, targetId: Constants.Message.all, payload: payload) } public static func createChatMessage(username: String, message: String) throws -> Message { // player,*,{...} // { // "type": "chat", // "username": "username", // "content": "<message>", // "bookmark": "String representing last message seen" // } let payload: JSON = [ Constants.Message.type: Constants.Message.chat, Constants.Message.username: username, Constants.Message.content: message, Constants.Message.bookmark: Constants.Message.prefix + uniqueStr() ] let payloadStr = try jsonToString(json: payload) Log.info("creating chat message with payload: \(payloadStr)") return try Message(target: Target.player, targetId: Constants.Message.all, payload: payloadStr) } // Send information about the room to the client. This message is sent after receiving a `roomHello`. public static func createLocationMessage(userId: String, roomDescription: RoomDescription) throws -> Message { // player,<userId>,{ // "type": "location", // "name": "Room name", // "fullName": "Room's descriptive full name", // "description", "Lots of text about what the room looks like", // "exits": { // "shortDirection" : "currentDescription for Player", // "N" : "a dark entranceway" // }, // "commands": { // "/custom" : "Description of what command does" // }, // "roomInventory": ["itemA","itemB"] // } let commands: JSON = JSON(roomDescription.commands) let inventory: JSON = JSON(roomDescription.inventory) let payload: JSON = [ Constants.Message.type: "location", "name": roomDescription.name, "fullName": roomDescription.fullName, "description": roomDescription.description, "commands": commands.object, "roomInventory": inventory.object ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.player, targetId: userId, payload: payloadStr) } // Indicates that a player can leave by the requested exit (`exitId`). public static func createExitMessage(userId: String, exitId: String?, message: String?) throws -> Message { guard let exitId = exitId else { throw SwiftRoomError.missingExitId } // playerLocation,<userId>,{ // "type": "exit", // "content": "You exit through door xyz... ", // "exitId": "N" // "exit": { ... } // } // The exit attribute describes an exit the map service wouldn't know about.. // This would have to be customized.. let payload: JSON = [ Constants.Message.type: "exit", "exitId": exitId, Constants.Message.content: message ?? "Fare thee well" ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.playerLocation, targetId: userId, payload: payloadStr) } // Used for test purposes, create a message targeted for the room public static func createRoomMessage(roomId: String, userId: String, username: String, content: String) throws -> Message { // room,<roomId>,{ // "username": "<username>", // "userId": "<userId>" // "content": "<message>" // } let payload: JSON = [ Constants.Message.userId: userId, Constants.Message.username: username, Constants.Message.content: content ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.room, targetId: roomId, payload: payloadStr) } // Used for test purposes, create a room hello message public static func createRoomHello(roomId: String, userId: String, username: String, version: Int) throws -> Message { // roomHello,<roomId>,{ // "username": "<username>", // "userId": "<userId>", // "version": 1|2 // } let payload: JSON = [ Constants.Message.userId: userId, Constants.Message.username: username, "version": version ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.roomHello, targetId: roomId, payload: payloadStr) } // Used for test purposes, create a room goodbye message public static func createRoomGoodbye(roomId: String, userId: String, username: String) throws -> Message { // roomGoodbye,<roomId>,{ // "username": "<username>", // "userId": "<userId>" // } let payload: JSON = [ Constants.Message.userId: userId, Constants.Message.username: username, ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.roomGoodbye, targetId: roomId, payload: payloadStr) } // Used for test purposes, create a room join message public static func createRoomJoin(roomId: String, userId: String, username: String, version: Int) throws -> Message { // roomJoin,<roomId>,{ // "username": "<username>", // "userId": "<userId>", // "version": 2 // } let payload: JSON = [ Constants.Message.userId: userId, Constants.Message.username: username, "version": version ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.roomJoin, targetId: roomId, payload: payloadStr) } // Used for test purposes, create a room part message public static func createRoomPart(roomId: String, userId: String, username: String) throws -> Message { // roomPart,<roomId>,{ // "username": "<username>", // "userId": "<userId>" // } let payload: JSON = [ Constants.Message.userId: userId, Constants.Message.username: username, ] let payloadStr = try jsonToString(json: payload) return try Message(target: Target.roomPart, targetId: roomId, payload: payloadStr) } public func toString() -> String { return self.target.rawValue + "," + targetId + "," + payload } private static func uniqueStr() -> String { return UUID().uuidString } private static func jsonToString(json: JSON) throws -> String { let data = try json.rawData() guard let jsonString: String = String(bytes: data, encoding: String.Encoding.utf8) else { throw SwiftRoomError.errorInJSONProcessing } return jsonString } public static func buildBroadcastContent(content: String?, pairs: [String]?) -> String { var dict: [String: Any] = [:] dict[Constants.Message.type] = Constants.Message.event dict[Constants.Message.bookmark] = Constants.Message.prefix + uniqueStr() var message: [String: String] = [:] if let content = content { message[Constants.Message.all] = content } // only add additional messages if there is an even number if let pairs = pairs, (pairs.count % 2) == 0 { for i in stride(from:0, through: pairs.count-1, by: 2) { message[pairs[i]] = pairs[i+1] } } dict[Constants.Message.content] = message return dict.description.replacingOccurrences(of: "[", with: "{").replacingOccurrences(of: "]", with: "}") } }
apache-2.0
OscarSwanros/swift
validation-test/stdlib/ValidationNSNumberBridging.swift
10
32825
//===--- NSNumberBridging.swift - Test bridging through NSNumber ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import StdlibUnittest import Foundation import CoreGraphics extension Float { init?(reasonably value: Float) { self = value } init?(reasonably value: Double) { guard !value.isNaN else { self = Float.nan return } guard !value.isInfinite else { if value.sign == .minus { self = -Float.infinity } else { self = Float.infinity } return } guard abs(value) <= Double(Float.greatestFiniteMagnitude) else { return nil } self = Float(value) } } extension Double { init?(reasonably value: Float) { guard !value.isNaN else { self = Double.nan return } guard !value.isInfinite else { if value.sign == .minus { self = -Double.infinity } else { self = Double.infinity } return } self = Double(value) } init?(reasonably value: Double) { self = value } } var nsNumberBridging = TestSuite("NSNumberBridgingValidation") func testFloat(_ lhs: Float?, _ rhs: Float?, file: String = #file, line: UInt = #line) { let message = "\(String(describing: lhs)) != \(String(describing: rhs)) Float" if let lhsValue = lhs { if let rhsValue = rhs { if lhsValue.isNaN != rhsValue.isNaN { expectUnreachable(message, file: file, line: line) } else if lhsValue != rhsValue && !lhsValue.isNaN { expectUnreachable(message, file: file, line: line) } } else { expectUnreachable(message, file: file, line: line) } } else { if rhs != nil { expectUnreachable(message, file: file, line: line) } } } func testDouble(_ lhs: Double?, _ rhs: Double?, file: String = #file, line: UInt = #line) { let message = "\(String(describing: lhs)) != \(String(describing: rhs)) Double" if let lhsValue = lhs { if let rhsValue = rhs { if lhsValue.isNaN != rhsValue.isNaN { expectUnreachable(message, file: file, line: line) } else if lhsValue != rhsValue && !lhsValue.isNaN { expectUnreachable(message, file: file, line: line) } } else { expectUnreachable(message, file: file, line: line) } } else { if rhs != nil { expectUnreachable(message, file: file, line: line) } } } extension Int8 { static var _interestingValues: [Int8] { return [ Int8.min, Int8.min + 1, Int8.max, Int8.max - 1, 0, -1, 1, -42, 42, ] } } extension UInt8 { static var _interestingValues: [UInt8] { return [ UInt8.min, UInt8.min + 1, UInt8.max, UInt8.max - 1, 42, ] } } extension Int16 { static var _interestingValues: [Int16] { return [ Int16.min, Int16.min + 1, Int16.max, Int16.max - 1, 0, -1, 1, -42, 42, ] } } extension UInt16 { static var _interestingValues: [UInt16] { return [ UInt16.min, UInt16.min + 1, UInt16.max, UInt16.max - 1, 42, ] } } extension Int32 { static var _interestingValues: [Int32] { return [ Int32.min, Int32.min + 1, Int32.max, Int32.max - 1, 0, -1, 1, -42, 42, ] } } extension UInt32 { static var _interestingValues: [UInt32] { return [ UInt32.min, UInt32.min + 1, UInt32.max, UInt32.max - 1, 42, ] } } extension Int64 { static var _interestingValues: [Int64] { return [ Int64.min, Int64.min + 1, Int64.max, Int64.max - 1, 0, -1, 1, -42, 42, ] } } extension UInt64 { static var _interestingValues: [UInt64] { return [ UInt64.min, UInt64.min + 1, UInt64.max, UInt64.max - 1, 42, ] } } extension Int { static var _interestingValues: [Int] { return [ Int.min, Int.min + 1, Int.max, Int.max - 1, 0, -1, 1, -42, 42, ] } } extension UInt { static var _interestingValues: [UInt] { return [ UInt.min, UInt.min + 1, UInt.max, UInt.max - 1, 42, ] } } extension Float { static var _interestingValues: [Float] { return [ -Float.infinity, -Float.greatestFiniteMagnitude, -1.0, -Float.ulpOfOne, -Float.leastNormalMagnitude, -0.0, 0.0, Float.leastNormalMagnitude, Float.ulpOfOne, 1.0, Float.greatestFiniteMagnitude, Float.infinity, Float.nan, ] } } extension Double { static var _interestingValues: [Double] { return [ -Double.infinity, -Double.greatestFiniteMagnitude, -1.0, -Double.ulpOfOne, -Double.leastNormalMagnitude, -0.0, 0.0, Double.leastNormalMagnitude, Double.ulpOfOne, 1.0, Double.greatestFiniteMagnitude, Double.infinity, Double.nan, ] } } extension CGFloat { static var _interestingValues: [CGFloat] { return [ -CGFloat.infinity, -CGFloat.greatestFiniteMagnitude, -1.0, -CGFloat.ulpOfOne, -CGFloat.leastNormalMagnitude, -0.0, 0.0, CGFloat.leastNormalMagnitude, CGFloat.ulpOfOne, 1.0, CGFloat.greatestFiniteMagnitude, CGFloat.infinity, CGFloat.nan, ] } } extension Bool { static var _interestingValues: [Bool] { return [false, true] } } func testNSNumberBridgeFromInt8() { for interestingValue in Int8._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float expectEqual(Float(interestingValue), float) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromUInt8() { for interestingValue in UInt8._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float expectEqual(Float(interestingValue), float) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromInt16() { for interestingValue in Int16._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float expectEqual(Float(interestingValue), float) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromUInt16() { for interestingValue in UInt8._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float expectEqual(Float(interestingValue), float) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromInt32() { for interestingValue in Int32._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float let expectedFloat = Float(exactly: int32!) // these are disabled because of https://bugs.swift.org/browse/SR-4634 if (int32! != Int32.min && int32! != Int32.max && int32! != Int32.min + 1 && int32! != Int32.max - 1) { testFloat(expectedFloat, float) } let double = (number!) as? Double let expectedDouble = Double(int32!) testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromUInt32() { for interestingValue in UInt32._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float let expectedFloat = Float(uint32!) // these are disabled because of https://bugs.swift.org/browse/SR-4634 if (uint32! != UInt32.max && uint32! != UInt32.max - 1) { testFloat(expectedFloat, float) } let double = (number!) as? Double let expectedDouble = Double(uint32!) testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromInt64() { for interestingValue in Int64._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromUInt64() { for interestingValue in UInt64._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromInt() { for interestingValue in Int._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromUInt() { for interestingValue in UInt._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) // these are disabled because of https://bugs.swift.org/browse/SR-4634 if uint! != UInt(UInt32.max) && uint! != UInt(UInt32.max - 1) { let float = (number!) as? Float let expectedFloat = Float(uint!) testFloat(expectedFloat, float) } let double = (number!) as? Double let expectedDouble = Double(uint!) testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromFloat() { for interestingValue in Float._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float let expectedFloat = Float(reasonably: interestingValue) testFloat(expectedFloat, float) let double = (number!) as? Double let expectedDouble = Double(interestingValue) testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromDouble() { for interestingValue in Double._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue), uint) let float = (number!) as? Float let expectedFloat = Float(reasonably: interestingValue) testFloat(expectedFloat, float) let double = (number!) as? Double let expectedDouble = interestingValue testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue) testNumber(created) } } func testNSNumberBridgeFromCGFloat() { for interestingValue in CGFloat._interestingValues { func testNumber(_ number: NSNumber?) { expectNotNil(number) let int8 = (number!) as? Int8 expectEqual(Int8(exactly: interestingValue.native), int8) let uint8 = (number!) as? UInt8 expectEqual(UInt8(exactly: interestingValue.native), uint8) let int16 = (number!) as? Int16 expectEqual(Int16(exactly: interestingValue.native), int16) let uint16 = (number!) as? UInt16 expectEqual(UInt16(exactly: interestingValue.native), uint16) let int32 = (number!) as? Int32 expectEqual(Int32(exactly: interestingValue.native), int32) let uint32 = (number!) as? UInt32 expectEqual(UInt32(exactly: interestingValue.native), uint32) let int64 = (number!) as? Int64 expectEqual(Int64(exactly: interestingValue.native), int64) let uint64 = (number!) as? UInt64 expectEqual(UInt64(exactly: interestingValue.native), uint64) let int = (number!) as? Int expectEqual(Int(exactly: interestingValue.native), int) let uint = (number!) as? UInt expectEqual(UInt(exactly: interestingValue.native), uint) let float = (number!) as? Float let expectedFloat = Float(reasonably: interestingValue.native) testFloat(expectedFloat, float) let double = (number!) as? Double let expectedDouble = Double(interestingValue) testDouble(expectedDouble, double) } let bridged = interestingValue as NSNumber testNumber(bridged) let created = NSNumber(value: interestingValue.native) testNumber(created) } } func test_numericBitPatterns_to_floatingPointTypes() { let signed_numbers: [NSNumber] = [ NSNumber(value: Int64(6)), NSNumber(value: Int64(bitPattern: 1 << 56)), NSNumber(value: Int64(bitPattern: 1 << 53)), NSNumber(value: Int64(bitPattern: 1 << 52)), NSNumber(value: Int64(bitPattern: 1 << 25)), NSNumber(value: Int64(bitPattern: 1 << 24)), NSNumber(value: Int64(bitPattern: 1 << 23)), NSNumber(value: -Int64(bitPattern: 1 << 53)), NSNumber(value: -Int64(bitPattern: 1 << 52)), NSNumber(value: -Int64(6)), NSNumber(value: -Int64(bitPattern: 1 << 56)), NSNumber(value: -Int64(bitPattern: 1 << 25)), NSNumber(value: -Int64(bitPattern: 1 << 24)), NSNumber(value: -Int64(bitPattern: 1 << 23)), ] let signed_values: [Int64] = [ Int64(6), Int64(bitPattern: 1 << 56), Int64(bitPattern: 1 << 53), Int64(bitPattern: 1 << 52), Int64(bitPattern: 1 << 25), Int64(bitPattern: 1 << 24), Int64(bitPattern: 1 << 23), -Int64(bitPattern: 1 << 53), -Int64(bitPattern: 1 << 52), -Int64(6), -Int64(bitPattern: 1 << 56), -Int64(bitPattern: 1 << 25), -Int64(bitPattern: 1 << 24), -Int64(bitPattern: 1 << 23), ] let unsigned_numbers: [NSNumber] = [ NSNumber(value: UInt64(bitPattern: 6)), NSNumber(value: UInt64(bitPattern: 1 << 56)), NSNumber(value: UInt64(bitPattern: 1 << 63)), NSNumber(value: UInt64(bitPattern: 1 << 53)), NSNumber(value: UInt64(bitPattern: 1 << 52)), NSNumber(value: UInt64(bitPattern: 1 << 25)), NSNumber(value: UInt64(bitPattern: 1 << 24)), NSNumber(value: UInt64(bitPattern: 1 << 23)), ] let unsigned_values: [UInt64] = [ UInt64(bitPattern: 6), UInt64(bitPattern: 1 << 56), UInt64(bitPattern: 1 << 63), UInt64(bitPattern: 1 << 53), UInt64(bitPattern: 1 << 52), UInt64(bitPattern: 1 << 25), UInt64(bitPattern: 1 << 24), UInt64(bitPattern: 1 << 23) ] for (number, value) in zip(signed_numbers, signed_values) { let numberCast = Double(exactly: number) let valueCast = Double(exactly: value) expectEqual(numberCast, valueCast) } for (number, value) in zip(unsigned_numbers, unsigned_values) { let numberCast = Double(exactly: number) let valueCast = Double(exactly: value) expectEqual(numberCast, valueCast) } for (number, value) in zip(signed_numbers, signed_values) { let numberCast = Float(exactly: number) let valueCast = Float(exactly: value) expectEqual(numberCast, valueCast) } for (number, value) in zip(unsigned_numbers, unsigned_values) { let numberCast = Float(exactly: number) let valueCast = Float(exactly: value) expectEqual(numberCast, valueCast) } } nsNumberBridging.test("Bridge Int8") { testNSNumberBridgeFromInt8() } nsNumberBridging.test("Bridge UInt8") { testNSNumberBridgeFromUInt8() } nsNumberBridging.test("Bridge Int16") { testNSNumberBridgeFromInt16() } nsNumberBridging.test("Bridge UInt16") { testNSNumberBridgeFromUInt16() } nsNumberBridging.test("Bridge Int32") { testNSNumberBridgeFromInt32() } nsNumberBridging.test("Bridge UInt32") { testNSNumberBridgeFromUInt32() } nsNumberBridging.test("Bridge Int64") { testNSNumberBridgeFromInt64() } nsNumberBridging.test("Bridge UInt64") { testNSNumberBridgeFromUInt64() } nsNumberBridging.test("Bridge Int") { testNSNumberBridgeFromInt() } nsNumberBridging.test("Bridge UInt") { testNSNumberBridgeFromUInt() } nsNumberBridging.test("Bridge Float") { testNSNumberBridgeFromFloat() } nsNumberBridging.test("Bridge Double") { testNSNumberBridgeFromDouble() } nsNumberBridging.test("Bridge CGFloat") { testNSNumberBridgeFromCGFloat() } nsNumberBridging.test("bitPattern to exactly") { test_numericBitPatterns_to_floatingPointTypes() } runAllTests()
apache-2.0
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift
19
840
// // RxCollectionViewDataSourceType.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif /** Marks data source as `UICollectionView` reactive data source enabling it to be used with one of the `bindTo` methods. */ public protocol RxCollectionViewDataSourceType /*: UICollectionViewDataSource*/ { /** Type of elements that can be bound to collection view. */ typealias Element /** New observable sequence event observed. - parameter collectionView: Bound collection view. - parameter observedEvent: Event */ func collectionView(collectionView: UICollectionView, observedEvent: Event<Element>) -> Void } #endif
mit
jozsef-vesza/MVVMExample
MVVMExample/Menu/ViewModels/MenuViewModel.swift
1
665
// // MenuViewModel.swift // MVVMExample // // Created by József Vesza on 15/12/14. // Copyright (c) 2014 Jozsef Vesza. All rights reserved. // import UIKit public class MenuViewModel: MenuViewModelType { public var mealDownloadService: MealDownloadServiceType public var items: Bindable<[Meal]> public init(mealDownloadService: MealDownloadServiceType) { self.mealDownloadService = mealDownloadService items = Bindable([]) loadData() } private func loadData() { mealDownloadService.downloadMeals { [unowned self] meals in self.items.value = meals } } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/16899-foldsequence.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 class B<T.h> { func g func f<l { struct Q<T: where g: AnyObject, { var b { var f : T)
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01570-llvm-foldingsetnodeid-operator.swift
12
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 protocol d { protocol c : f { func f } } Range<d>
mit
jwfriese/FrequentFlyer
FrequentFlyerTests/Jobs/JobsDataDeserializerSpec.swift
1
14260
import XCTest import Quick import Nimble import RxSwift import SwiftyJSON import Result @testable import FrequentFlyer class JobsDataDeserializerSpec: QuickSpec { class MockBuildDataDeserializer: BuildDataDeserializer { private var toReturnBuild: [Data : Build] = [:] private var toReturnError: [Data : DeserializationError] = [:] fileprivate func when(_ data: JSON, thenReturn build: Build) { let jsonData = try! data.rawData(options: .prettyPrinted) toReturnBuild[jsonData] = build } fileprivate func when(_ data: JSON, thenErrorWith error: DeserializationError) { let jsonData = try! data.rawData(options: .prettyPrinted) toReturnError[jsonData] = error } override func deserialize(_ data: Data) -> Result<Build, DeserializationError> { let inputAsJSON = JSON(data: data) for (keyData, build) in toReturnBuild { let keyAsJSON = JSON(data: keyData) if keyAsJSON == inputAsJSON { return Result.success(build) } } for (keyData, error) in toReturnError { let keyAsJSON = JSON(data: keyData) if keyAsJSON == inputAsJSON { return Result.failure(error) } } return Result.failure(DeserializationError(details: "fatal error in test", type: .missingRequiredData)) } } override func spec() { describe("JobsDataDeserializer") { var subject: JobsDataDeserializer! var mockBuildDataDeserializer: MockBuildDataDeserializer! var validNextBuildJSONOne: JSON! var validFinishedBuildJSONOne: JSON! var validNextBuildJSONTwo: JSON! var validFinishedBuildJSONTwo: JSON! var validFinishedBuildResultOne: Build! var validNextBuildResultOne: Build! var validFinishedBuildResultTwo: Build! var validNextBuildResultTwo: Build! var validJobJSONOne: JSON! var validJobJSONTwo: JSON! let publishSubject = PublishSubject<[Job]>() var result: StreamResult<[Job]>! var jobs: [Job] { get { return result.elements.flatMap { $0 } } } beforeEach { subject = JobsDataDeserializer() mockBuildDataDeserializer = MockBuildDataDeserializer() subject.buildDataDeserializer = mockBuildDataDeserializer validFinishedBuildJSONOne = JSON(dictionaryLiteral: [ ("name", "finished one") ]) validNextBuildJSONOne = JSON(dictionaryLiteral: [ ("name", "next one") ]) validJobJSONOne = JSON(dictionaryLiteral :[ ("name", "turtle job"), ("finished_build", validFinishedBuildJSONOne), ("next_build", validNextBuildJSONOne), ("groups", ["group_one", "group_two"]) ]) validFinishedBuildJSONTwo = JSON(dictionaryLiteral: [ ("name", "finished two"), ]) validNextBuildJSONTwo = JSON(dictionaryLiteral: [ ("name", "next two") ]) validJobJSONTwo = JSON(dictionaryLiteral :[ ("name", "crab job"), ("finished_build", validFinishedBuildJSONTwo), ("next_build", validNextBuildJSONTwo), ("groups", ["group_one", "group_three"]) ]) validFinishedBuildResultOne = BuildBuilder().withName("finished one").build() validNextBuildResultOne = BuildBuilder().withName("next one").build() validFinishedBuildResultTwo = BuildBuilder().withName("finished two").build() validNextBuildResultTwo = BuildBuilder().withName("next two").build() mockBuildDataDeserializer.when(validFinishedBuildJSONOne, thenReturn: validFinishedBuildResultOne) mockBuildDataDeserializer.when(validFinishedBuildJSONTwo, thenReturn: validFinishedBuildResultTwo) mockBuildDataDeserializer.when(validNextBuildJSONOne, thenReturn: validNextBuildResultOne) mockBuildDataDeserializer.when(validNextBuildJSONTwo, thenReturn: validNextBuildResultTwo) } describe("Deserializing jobs data that is all valid") { beforeEach { let validInputJSON = JSON([ validJobJSONOne, validJobJSONTwo ]) let validData = try! validInputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(validData)) } it("returns a job for each JSON job entry") { if jobs.count != 2 { fail("Expected to return 2 jobs, returned \(jobs.count)") return } let expectedJobOne = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) let expectedJobTwo = Job( name: "crab job", nextBuild: validNextBuildResultTwo, finishedBuild: validFinishedBuildResultTwo, groups: ["group_one", "group_three"] ) expect(jobs[0]).to(equal(expectedJobOne)) expect(jobs[1]).to(equal(expectedJobTwo)) } it("returns no error") { expect(result.error).to(beNil()) } } describe("Deserializing job data where some of the data is invalid") { context("Missing required 'name' field") { beforeEach { var invalidJobJSON: JSON! = validJobJSONTwo _ = invalidJobJSON.dictionaryObject?.removeValue(forKey: "name") let inputJSON = JSON([ validJobJSONOne, invalidJobJSON ]) let invalidData = try! inputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(invalidData)) } it("emits a job only for each valid JSON job entry") { let expectedJob = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) expect(jobs).to(equal([expectedJob])) } it("emits completed") { expect(result.completed).to(beTrue()) } } context("'name' field is not a string") { beforeEach { var invalidJobJSON: JSON! = validJobJSONTwo _ = invalidJobJSON.dictionaryObject?.updateValue(1, forKey: "name") let inputJSON = JSON([ validJobJSONOne, invalidJobJSON ]) let invalidData = try! inputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(invalidData)) } it("emits a job only for each valid JSON job entry") { let expectedJob = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) expect(jobs).to(equal([expectedJob])) } it("emits completed") { expect(result.completed).to(beTrue()) } } context("Missing just 'next_build'") { beforeEach { var stillValidJobJSON: JSON! = validJobJSONTwo _ = stillValidJobJSON.dictionaryObject?.removeValue(forKey: "next_build") let inputJSON = JSON([ validJobJSONOne, stillValidJobJSON ]) let invalidData = try! inputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(invalidData)) } it("emits a job for each valid JSON job entry") { let expectedJobOne = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) let expectedJobTwo = Job( name: "crab job", nextBuild: nil, finishedBuild: validFinishedBuildResultTwo, groups: ["group_one", "group_three"] ) expect(jobs).to(equal([expectedJobOne, expectedJobTwo])) } it("emits completed") { expect(result.completed).to(beTrue()) } } context("Missing just 'finished_build'") { beforeEach { var stillValidJobJSON: JSON! = validJobJSONTwo _ = stillValidJobJSON.dictionaryObject?.removeValue(forKey: "finished_build") let inputJSON = JSON([ validJobJSONOne, stillValidJobJSON ]) let invalidData = try! inputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(invalidData)) } it("emits a job for each valid JSON job entry") { let expectedJobOne = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) let expectedJobTwo = Job( name: "crab job", nextBuild: validNextBuildResultTwo, finishedBuild: nil, groups: ["group_one", "group_three"] ) expect(jobs).to(equal([expectedJobOne, expectedJobTwo])) } it("emits completed") { expect(result.completed).to(beTrue()) } } context("Missing both 'next_build' and 'finished_build' fields simulataneously") { beforeEach { var bothBuildsMissingJSON: JSON! = validJobJSONTwo _ = bothBuildsMissingJSON.dictionaryObject?.removeValue(forKey: "next_build") _ = bothBuildsMissingJSON.dictionaryObject?.removeValue(forKey: "finished_build") let inputJSON = JSON([ validJobJSONOne, bothBuildsMissingJSON ]) let invalidData = try! inputJSON.rawData(options: .prettyPrinted) result = StreamResult(subject.deserialize(invalidData)) } it("emits a job for each valid JSON job entry") { let expectedJobOne = Job( name: "turtle job", nextBuild: validNextBuildResultOne, finishedBuild: validFinishedBuildResultOne, groups: ["group_one", "group_two"] ) let expectedJobTwo = Job( name: "crab job", nextBuild: nil, finishedBuild: nil, groups: ["group_one", "group_three"] ) expect(jobs).to(equal([expectedJobOne, expectedJobTwo])) } it("emits completed") { expect(result.completed).to(beTrue()) } } } describe("Given data cannot be interpreted as JSON") { beforeEach { let jobsDataString = "some string" let invalidJobsData = jobsDataString.data(using: String.Encoding.utf8) result = StreamResult(subject.deserialize(invalidJobsData!)) } it("emits no methods") { expect(jobs).to(haveCount(0)) } it("emits an error") { expect(result.error as? DeserializationError).to(equal(DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat))) } } } } }
apache-2.0
qvik/HelsinkiOS-IBD-Demo
HelsinkiOS-Demo/Views/Base/BaseNavigationView.swift
1
1838
// // BaseNavigationView.swift // HelsinkiOS-Demo // // Created by Jerry Jalava on 28/09/15. // Copyright © 2015 Qvik. All rights reserved. // import UIKit @IBDesignable public class BaseNavigationView: UIView { @IBOutlet weak var backButton: UIButton! @IBInspectable public var showBackButton: Bool = false { didSet { backButton.hidden = !showBackButton } } public var view: UIView! // MARK: Private methods private func getXibName() -> String { let className = NSStringFromClass(self.dynamicType) as String let nameParts = className.characters.split {$0 == "."}.map { String($0) } return nameParts[1] as String } private func loadViewFromNib(name: String) -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: name, bundle: bundle) // Assumes UIView is top level and only object in CustomView.xib file let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView return view } // MARK: Overridable methods func viewInited() { } // MARK: Lifecycle required override public init(frame: CGRect) { super.init(frame: frame) self.initView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initView() } func initView() { let xibName = getXibName() view = loadViewFromNib(xibName) view.frame = bounds // Make the view stretch with containing view view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] addSubview(view) viewInited() } }
mit
askken/SwiftWeather
SwiftWeather/Temperature.swift
2
597
// // Temperature.swift // SwiftWeather // // Created by Jake Lin on 9/9/15. // Copyright © 2015 Jake Lin. All rights reserved. // import Foundation struct Temperature { let degrees: String init(country: String, openWeatherMapDegrees: Double) { if country == "US" { // Convert temperature to Fahrenheit if user is within the US degrees = String(round(((openWeatherMapDegrees - 273.15) * 1.8) + 32)) + "\u{f045}" } else { // Otherwise, convert temperature to Celsius degrees = String(round(openWeatherMapDegrees - 273.15)) + "\u{f03c}" } } }
mit
abaca100/Nest
iOS-NestDK/UIAlertController+Convenience.swift
1
2854
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `UIAlertController+Convenience` methods allow for quick construction of `UIAlertController`s with common structures. */ import UIKit extension UIAlertController { /** A simple `UIAlertController` that prompts for a name, then runs a completion block passing in the name. - parameter attributeType: The type of object that will be named. - parameter completion: A block to call, passing in the provided text. - returns: A `UIAlertController` instance with a UITextField, cancel button, and add button. */ convenience init(attributeType: String, completionHandler: (name: String) -> Void, var placeholder: String? = nil, var shortType: String? = nil) { if placeholder == nil { placeholder = attributeType } if shortType == nil { shortType = attributeType } let title = NSLocalizedString("New", comment: "New") + " \(attributeType)" let message = NSLocalizedString("Enter a name.", comment: "Enter a name.") self.init(title: title, message: message, preferredStyle: .Alert) self.addTextFieldWithConfigurationHandler { textField in textField.placeholder = placeholder textField.autocapitalizationType = .Words } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: .Cancel) { action in self.dismissViewControllerAnimated(true, completion: nil) } let add = NSLocalizedString("Add", comment: "Add") let addString = "\(add) \(shortType!)" let addNewObject = UIAlertAction(title: addString, style: .Default) { action in if let name = self.textFields!.first!.text { let trimmedName = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) completionHandler(name: trimmedName) } self.dismissViewControllerAnimated(true, completion: nil) } self.addAction(cancelAction) self.addAction(addNewObject) } /** A simple `UIAlertController` made to show an error message that's passed in. - parameter body: The body of the alert. - returns: A `UIAlertController` with an 'Okay' button. */ convenience init(title: String, body: String) { self.init(title: title, message: body, preferredStyle: .Alert) let okayAction = UIAlertAction(title: NSLocalizedString("Okay", comment: "Okay"), style: .Default) { action in self.dismissViewControllerAnimated(true, completion: nil) } self.addAction(okayAction) } }
apache-2.0
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Private/Domain Events/FavouriteEvent.swift
1
123
import Foundation extension DomainEvent { struct FavouriteEvent { var identifier: EventIdentifier } }
mit
victorchee/CustomTransition
CustomTransition/CustomTransition/FirstViewController.swift
1
2937
// // FirstViewController.swift // CustomTransition // // Created by qihaijun on 11/4/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class FirstViewController: UIViewController, UIViewControllerTransitioningDelegate { private var percentDrivenTransition: UIPercentDrivenInteractiveTransition? override func viewDidLoad() { super.viewDidLoad() transitioningDelegate = self let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(edgePan(_:))) edgePanGesture.edges = UIRectEdge.right view.addGestureRecognizer(edgePanGesture) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? SecondViewController { let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(edgePan(_:))) edgePanGesture.edges = UIRectEdge.left destination.view.addGestureRecognizer(edgePanGesture) destination.transitioningDelegate = self } super.prepare(for: segue, sender: sender) } @objc func edgePan(_ sender: UIScreenEdgePanGestureRecognizer) { let window = UIApplication.shared.keyWindow! let progress = abs(sender.translation(in: window).x / window.bounds.width) if sender.state == .began { percentDrivenTransition = UIPercentDrivenInteractiveTransition() if sender.edges == .right { performSegue(withIdentifier: "Modal", sender: sender) } else { dismiss(animated: true, completion: nil) } } else if sender.state == .changed { percentDrivenTransition?.update(progress) } else if sender.state == .cancelled || sender.state == .ended { if progress > 0.5 { percentDrivenTransition?.finish() } else { percentDrivenTransition?.cancel() } percentDrivenTransition = nil } } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CustomModalTransition() } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CustomDismissTransition() } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return percentDrivenTransition } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return percentDrivenTransition } }
mit
sunilsharma08/CustomTextView
CustomTextViewExampleUITests/CustomTextViewExampleUITests.swift
1
1289
// // CustomTextViewExampleUITests.swift // CustomTextViewExampleUITests // // Created by Sunil Sharma on 08/06/16. // Copyright © 2016 Sunil Sharma. All rights reserved. // import XCTest class CustomTextViewExampleUITests: 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
strawberrycode/SafariOauthLogin
SafariOauthLoginTests/SafariOauthLoginTests.swift
1
1653
// // SafariOauthLoginTests.swift // SafariOauthLoginTests // // Created by Catherine Schwartz on 27/07/2015. // Copyright © 2015 StrawberryCode. All rights reserved. // import XCTest import SwiftyJSON @testable import SafariOauthLogin class SafariOauthLoginTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testJsonName() { let json = JSON(["access_token": "", "user":[ "username" : "", "full_name" : "", "profile_picture" : "", "website" : "", "id" : "", "bio" : "" ]]) let user = User(json: json) XCTAssertEqual(user.firstName, "", "First name") XCTAssertEqual(user.userName, "", "Username") XCTAssertNotEqual(user.instagramId, "", "id") } }
mit
MakeSchool/Swift-Playgrounds
More-P0-Closures.playground/Contents.swift
2
7756
import UIKit //: ## Closures //: //: Closures are like functions with a twist. They can refer to variables in their containing scope, which makes them way more powerful than normal functions. In Swift, closures pop up everywhere, so it will help to play with some examples to get familiar with them. //: ### A Simple Example //: //: Let's look at a simple closure: func addOne(value: Int) -> Int { return value + 1 } addOne(1) //: "Wait!" you say. "That's just a plain old function!" And you're right. A global function is a named closure. The trivial closure above takes a value and adds one to it, returning the result. //: ### Capture //: //: What distinguishes closures from functions is that closures **capture** variables from their surrounding environment. This means that you can refer to local variables from within a closure, and even if they have later gone out of scope, the closure still has access to them. Value types get copied when they are captured, while reference types are strongly referenced, meaning the closure prevents them from being deallocated until the closure itself is deallocated. //: ### Nested Functions //: //: Let's look at a more sophisticated example of closures, one that actually takes advantage of a closure's ability to refer to variables in its containing scope. **Nested functions** are another instance of closures in Swift: func fibonacciSequence(length: Int) -> [Int] { let initialElements = [0, 1] func sequence() -> [Int] { var elements = initialElements for (var i = elements.count; i < length; ++i) { elements.append(elements[i - 2] + elements[i - 1]) } return elements } // This calls the closure, which has captured the initial sequence elements // and will complete the sequence to the desired length return sequence() } //: The nested function (`sequence`) builds up a sequence by adding the last two elements in the sequence together and appending this new value to the elements array. The important thing to note here is that the nested function _captures_ both the local variable `initialElements` and the `length` parameter. The values of these two captured variables determine the values that wind up in the array returned by `sequence`, even though they aren't expressly passed as parameters to the closure. //: Calling the `fibonacciSequence` outer function with the desired length of the sequence returns an array containing that many Fibonacci numbers: fibonacciSequence(12) //: Closure Expressions //: //: It's not necessary to name a closure if you return it or call it immediately. This allows us to write functions that return anonymous functions. Consider this function, which builds functions that extend a `String` by repeating its final character: func extender(base: String) -> (Int) -> String { return { count in let lastCharacter = base[advance(base.endIndex, -1)] var extendedString = base for (var i = 1; i < count; ++i) { extendedString.append(lastCharacter) } return extendedString } } //: If those double arrows (`->`) are tripping you up, that's understandable. You may not have seen a function return a function before, and it's hard to read at first. Let's break it down a little further. //: The function `extender` takes a `String` and returns a closure that captures that string and also takes an `Int` and returns a `String`. That's a mouthful, but it demonstrates the fact that closures in Swift can be created, passed around, and returned just like other types. //: Let's make an extender that will add extra "y"s to the end of the string "Hey": let heyExtender = extender("Hey") //: Notice that the thing we get back is described as "(Function)". That's our closure. Let's call it with 5 as the total number of "y"s: let extendedHey = heyExtender(5) //: What's the advantage of returning a closure instead of just building the extended string directly in the `extender` function? Well, we can invoke the closure we get back multiple times with different parameters to build all the extended "hey"s we want: heyExtender(8) heyExtender(16) heyExtender(32) //: ### Trailing Closure Syntax //: //: Many functions in the Swift standard library take closures as parameters. These closures may be used to help the function do its job, or they may be used as a callback to notify another object when the function has completed. Swift has special syntax for the rather common case that a closure is the final parameter in a function's parameter list. Let's take a look at an example. let scores = [ 70, 93, 81, 55, 99, 77, 62 ] sorted(scores, { (a, b) -> Bool in a < b // Sort ascending }) //: The standard function `sorted` takes an array and returns a sorted array of the same type. It also takes a second parameter: a closure you can use to customize which object is ordered as the lesser of the pair of its parameters. Above, we wrote the closure in-line using closure expression syntax. But we can also move it outside the function call entirely, using **trailing closure syntax**: sorted(scores) { (a, b) -> Bool in b < a // Sort descending this time } //: Note in the above case that the parentheses containing the parameter list are closed, and the opening brace for the closure comes afterward. This looks a little unusual at first, but you are likely to see this syntax often, so you will quickly grow accustomed to it. //: ### Avoiding Retain Cycles //: //: So far, we've mostly been capturing value types in our closures. There is a pitfall to be aware of when capturing reference types: if an object has a reference to a closure, which in turn refers to the object itself (even just by accessing one of the object's properties), the object will never be released, leading to a memory leak. This type of circular reference is called a **strong reference cycle** (or "retain cycle"). //: The class below generates random numbers and keeps a running tally of the generated values. Inside the callback, notice that we have commented out the line `[unowned self] in`. The part in square brackets is called the **capture list**, and it tells the closure _not_ to hold onto a strong reference to `self`. With this line commented out, self will be strongly referenced by the closure, and the object itself will hold a strong reference to the closure, creating a strong reference cycle. class RandomNumberAccumulator { typealias RandomNumberCallback = () -> () var sum: UInt32 var callback: RandomNumberCallback! init() { sum = 0 self.callback = { // [unowned self] in // Omitting this causes self to be captured strongly by this block println("\(self.sum)") } } func generate() { self.sum += arc4random_uniform(100) callback() } } var rna = RandomNumberAccumulator() rna.generate() rna.generate() rna.generate() rna.generate() //: Whenever a class holds a reference to a closure that refers back to the object, you should include a capture list that explicitly makes the reference to `self` an **unowned** reference. Otherwise, your app will leak memory. //: ### Recap //: //: In this Playground, we've seen a few examples of closures, some trivial and some fairly advanced. You learned that closures have the special ability to "capture" variables from their surrounding scope, which allows them to operate on these values even after they leave their original scope. You learned that functions can have nested functions and that functions can return functions. Finally, you learned how to avoid strong reference cycles when an object needs to hold onto a reference to a closure that references the object.
mit
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/MapService.swift
1
3721
// // Map.swift // UberGoCore // // Created by Nghia Tran on 6/4/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Foundation import MapKit import RxCocoa import RxSwift protocol MapServiceViewModel { var input: MapServiceInput { get } var output: MapServiceOutput { get } } protocol MapServiceInput { } protocol MapServiceOutput { var currentLocationVar: Variable<CLLocation?> { get } var currentPlaceObs: Observable<PlaceObj> { get } var authorizedDriver: Driver<Bool>! { get } } // MARK: - MapService public final class MapService: NSObject, MapServiceViewModel, MapServiceInput, MapServiceOutput { // MARK: - Input Output var input: MapServiceInput { return self } var output: MapServiceOutput { return self } // MARK: - Output public var currentLocationVar = Variable<CLLocation?>(nil) public var currentPlaceObs: Observable<PlaceObj> public var authorizedDriver: Driver<Bool>! // Private fileprivate lazy var locationManager: CLLocationManager = self.lazyLocationManager() // MARK: - Init public override init() { // Current Place self.currentPlaceObs = self.currentLocationVar .asObservable() .filterNil() .take(1) .throttle(5.0, scheduler: MainScheduler.instance) .distinctUntilChanged() .flatMapLatest({ MapService.currentPlaceObverser($0) }) super.init() // Authorize self.authorizedDriver = Observable .deferred { [weak self] in let status = CLLocationManager.authorizationStatus() guard let `self` = self else { return Observable.empty() } return self.locationManager .rx.didChangeAuthorizationStatus .startWith(status) } .asDriver(onErrorJustReturn: CLAuthorizationStatus.notDetermined) .map { switch $0 { case .authorizedAlways: return true default: return false } } } // MARK: - Public public func startUpdatingLocation() { self.locationManager.startUpdatingLocation() } public func stopUpdatingLocation() { self.locationManager.stopUpdatingLocation() } fileprivate class func currentPlaceObverser(_ location: CLLocation) -> Observable<PlaceObj> { let param = PlaceSearchRequestParam(location: location.coordinate) return PlaceSearchRequest(param) .toObservable() .map({ return $0.first }) .filterNil() } } extension MapService { fileprivate func lazyLocationManager() -> CLLocationManager { let locationManager = CLLocationManager() locationManager.delegate = self locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation return locationManager } } // MARK: - CLLocationManagerDelegate extension MapService: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { Logger.info("Error \(error)") } public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { Logger.info("didChangeAuthorization \(status)") } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let lastLocation = locations.last else { return } // Notify self.currentLocationVar.value = lastLocation } }
mit
ta2yak/loqui
loqui/AppDelegate.swift
1
4599
// // AppDelegate.swift // loqui // // Created by Kawasaki Tatsuya on 2017/07/01. // Copyright © 2017年 Kawasaki Tatsuya. All rights reserved. // import UIKit import Firebase import SimpleTab import MaterialComponents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var simpleTBC:SimpleTabBarController? var mainColorScheme:MDCBasicColorScheme? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Setup Firebase FirebaseApp.configure() mainColorScheme = MDCBasicColorScheme(primaryColor: UIColor.mainColor(), primaryLightColor: UIColor.mainLightColor(), primaryDarkColor: UIColor.mainDarkColor()) //# Setup Simple Tab Bar Controller setupSimpleTab() return true } func setupSimpleTab() { //# Get Handle of Tab Bar Control /* In storyboard, ensure : - Tab Bar Controller is set as SimpleTabBarController - Tab Bar is set as SimpleTabBar - Tab Bar Item is set as SimpleTabBarItem */ simpleTBC = self.window!.rootViewController as? SimpleTabBarController //# Set the View Transition simpleTBC?.viewTransition = PopViewTransition() //simpleTBC?.viewTransition = CrossFadeViewTransition() //# Set Tab Bar Style ( tab bar , tab item animation style etc ) let style:SimpleTabBarStyle = PopTabBarStyle(tabBar: simpleTBC!.tabBar) //let style:SimpleTabBarStyle = ElegantTabBarStyle(tabBar: simpleTBC!.tabBar) //# Optional - Set Tab Title attributes for selected and unselected (normal) states. // Or use the App tint color to set the states style.setTitleTextAttributes(attributes: [NSFontAttributeName as NSObject : UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName as NSObject: UIColor.lightGray], forState: .normal) style.setTitleTextAttributes(attributes: [NSFontAttributeName as NSObject : UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName as NSObject: UIColor.mainColor()], forState: .selected) //# Optional - Set Tab Icon colors for selected and unselected (normal) states. // Or use the App tint color to set the states style.setIconColor(color: UIColor.lightGray, forState: UIControlState.normal) style.setIconColor(color: UIColor.mainColor(), forState: UIControlState.selected) //# Let the tab bar control know of the style // Note: All style settings must be done prior to this. simpleTBC?.tabBarStyle = style } 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
shujincai/DouYu
DouYu/DouYu/Classes/Home/View/CollectionGameCell.swift
1
677
// // CollectionGameCell.swift // DouYu // // Created by pingtong on 2017/6/23. // Copyright © 2017年 PTDriver. All rights reserved. // import UIKit import Kingfisher class CollectionGameCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! var group: AnchorGroup? { didSet { titleLabel.text = group?.tag_name iconImageView.kf.setImage(with: URL(string: group?.icon_url ?? "")) } } override func awakeFromNib() { // MARK:- 定义模型属性 super.awakeFromNib() // Initialization code } }
mit
TomasVanRoose/SportsCalendarPlanner
SportsCalendarPlanner/TeamMO+CoreDataProperties.swift
1
503
// // TeamMO+CoreDataProperties.swift // SportsCalendarPlanner // // Created by Tomas Van Roose on 04/09/16. // Copyright © 2016 Tomas Van Roose. All rights reserved. // // 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 TeamMO { @NSManaged var name: String? @NSManaged var playableDates: NSSet? @NSManaged var season: SeasonMO? }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/01970-void.swift
1
553
// 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 struct Q<h.d() { enum B : T : l.advance(n: Array) -> { protocol A = compose(" } class a : AnyObject, A { protocol P { protocol a : P> { } } class A : A, b
apache-2.0
billyburton/SwiftMySql
Package.swift
1
191
import PackageDescription let package = Package( name: "SwiftMySql", dependencies: [ .Package(url: "https://github.com/billyburton/SwiftCMySql.git", majorVersion: 0) ] )
apache-2.0
raginmari/RAGTextField
Example/RAGTextField/PlaceholderViewController.swift
1
2902
import UIKit import RAGTextField final class PlaceholderViewController: UIViewController, UITextFieldDelegate { @IBOutlet private weak var simpleTextField: RAGTextField! { didSet { simpleTextField.placeholderMode = .simple setUp(simpleTextField) } } @IBOutlet private weak var whenNotEmptyTextField: RAGTextField! { didSet { whenNotEmptyTextField.placeholderMode = .scalesWhenNotEmpty setUp(whenNotEmptyTextField) } } @IBOutlet private weak var whenEditingTextField: RAGTextField! { didSet { whenEditingTextField.placeholderMode = .scalesWhenEditing setUp(whenEditingTextField) } } @IBOutlet private weak var offsetTextField: RAGTextField! { didSet { offsetTextField.placeholderMode = .scalesWhenEditing setUp(offsetTextField, color: ColorPalette.savanna.withAlphaComponent(0.1)) } } @IBOutlet weak var placeholderOffsetControl: UISegmentedControl! { didSet { placeholderOffsetControl.tintColor = ColorPalette.savanna } } private func setUp(_ textField: RAGTextField, color: UIColor = ColorPalette.chalk) { textField.delegate = self textField.textColor = ColorPalette.midnight textField.tintColor = ColorPalette.midnight textField.textBackgroundView = makeTextBackgroundView(color: color) textField.textPadding = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0) textField.textPaddingMode = .textAndPlaceholderAndHint textField.scaledPlaceholderOffset = 2.0 textField.placeholderScaleWhenEditing = 0.8 textField.placeholderColor = ColorPalette.stone } private func makeTextBackgroundView(color: UIColor) -> UIView { let view = UIView() view.layer.cornerRadius = 4.0 view.backgroundColor = color return view } override func viewDidLoad() { title = "Placeholder" setPlaceholderOffset(at: placeholderOffsetControl.selectedSegmentIndex) super.viewDidLoad() } @IBAction func onPlaceholderOffsetChanged(_ control: UISegmentedControl) { setPlaceholderOffset(at: control.selectedSegmentIndex) } private func setPlaceholderOffset(at index: Int) { _ = offsetTextField.resignFirstResponder() let offset: CGFloat = [0.0, 8.0, 16.0][index] offsetTextField.scaledPlaceholderOffset = offset let value = "Offset by \(Int(offset))pt" offsetTextField.text = value } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
mit
Bajocode/ExploringModerniOSArchitectures
Architectures/Shared/Utility/TmdbParser.swift
1
3256
// // TmdbParser.swift // Architectures // // Created by Fabijan Bajo on 20/05/2017. // // /* Tmdb object parsing utility methods */ import Foundation struct TmdbParser { // DataManager's access to the parsing utilities public static func parsedResult(withJSONData data: Data, type: ModelType) -> DataResult { do{ // Serialize raw json into foundation json and retrieve movie array let jsonFoundationObject = try JSONSerialization.jsonObject(with: data, options: []) guard let jsonDict = jsonFoundationObject as? [AnyHashable:Any], let jsonObjectsArray = jsonDict["results"] as? [[String:Any]] else { return .failure(TmdbError.invalidJSONData(key: "results", dictionary: jsonFoundationObject)) } return .success(parsedObjects(withJSONArray: jsonObjectsArray, type: type)) } catch let serializationError { return .failure(serializationError) } } // Caller of individual object parsers based on object type private static func parsedObjects(withJSONArray array: [[String: Any]], type: ModelType) -> [Transportable] { switch type { case .movie: return array.flatMap { parsedMovie(forMovieJSON: $0) } case .actor: return array.flatMap { parsedActor(forActorJSON: $0) } } } // Parse individual movie dictionaries, extracted from json response private static func parsedMovie(forMovieJSON json: [String:Any]) -> Movie? { guard let movieID = json["id"] as? Int, let title = json["title"] as? String, let posterPath = json["poster_path"] as? String, let averageRating = json["vote_average"] as? Double, let releaseDate = json["release_date"] as? String else { // Do not have enough information to construct the object return nil } return Movie(title: title, posterPath: posterPath, movieID: movieID, releaseDate: releaseDate, averageRating: averageRating) } // Parse individual actor dictionaries, extracted from json response private static func parsedActor(forActorJSON json: [String:Any]) -> Actor? { guard let actorID = json["id"] as? Int, let name = json["name"] as? String, let profilePath = json["profile_path"] as? String else { // Do not have enough information to construct the object return nil } return Actor(name: name, profilePath: profilePath, actorID: actorID) } } // MARK: - Tmdb parsing related helper types fileprivate enum TmdbError: CustomStringConvertible, Error { case invalidJSONData(key: String, dictionary: Any) case serializationError(error: Error) case other(string: String) var description: String { switch self { case .invalidJSONData(let key, let dict): return "Could not find key '\(key)' in JSON dictionary:\n \(dict)" case .serializationError(let error): return "JSON serialization failed with error:\n \(error)" case .other(let string): return string } } }
mit
juanm95/Soundwich
Quaggify/LoginViewController.swift
1
2466
// // LoginViewController.swift // Quaggify // // Created by Jonathan Bijos on 02/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class LoginViewController: ViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } let titleLabel: UILabel = { let label = UILabel() label.text = "Soundwich" label.textColor = ColorPalette.white label.font = Font.montSerratRegular(size: 36) label.textAlignment = .center return label }() lazy var loginButton: UIButton = { let button = UIButton(type: .system) button.tintColor = .white button.setTitle("Login with Spotify", for: .normal) button.titleLabel?.font = Font.montSerratBold(size: 16) button.addTarget(self, action: #selector(login), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() setupViews() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let alertController = UIAlertController(title: "Soundwich", message: "Enter your username", preferredStyle: UIAlertControllerStyle.alert) alertController.addTextField{ (textField : UITextField!) -> Void in textField.placeholder = "Enter username" } alertController.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in let username = alertController.textFields![0].text! print(username) UserDefaults.standard.set(username, forKey: "username") API.registerUser(username: username) })) self.present(alertController, animated: true, completion: nil) } func login () { SpotifyService.shared.login() } override func setupViews() { super.setupViews() view.backgroundColor = ColorPalette.black view.addSubview(titleLabel) view.addSubview(loginButton) titleLabel.anchorCenterYToSuperview() titleLabel.anchor(nil, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 40) loginButton.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 32) } }
mit
khizkhiz/swift
benchmark/single-source/Chars.swift
2
1262
//===--- Chars.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test tests the performance of ASCII Character comparison. import TestsUtils @inline(never) public func run_Chars(N: Int) { // Permute some characters. let alphabet: [Character] = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "/", "f", "Z", "z", "6", "7", "C", "j", "f", "9", "g", "g", "I", "J", "K", "c", "x", "i", ".", "2", "a", "t", "i", "o", "e", "q", "n", "X", "Y", "Z", "?", "m", "Z", "," ] for _ in 0...N { for firstChar in alphabet { for middleChar in alphabet { for lastChar in alphabet { _ = ((firstChar == middleChar) != (middleChar < lastChar)) } } } } }
apache-2.0
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Home/Source/LBXScanViewStyle.swift
2
2705
// // LBXScanViewStyle.swift // swiftScan https://github.com/MxABC/swiftScan // // Created by xialibing on 15/12/8. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit ///扫码区域动画效果 public enum LBXScanViewAnimationStyle { case LineMove //线条上下移动 case NetGrid//网格 case LineStill//线条停止在扫码区域中央 case None //无动画 } ///扫码区域4个角位置类型 public enum LBXScanViewPhotoframeAngleStyle { case Inner//内嵌,一般不显示矩形框情况下 case Outer//外嵌,包围在矩形框的4个角 case On //在矩形框的4个角上,覆盖 } public struct LBXScanViewStyle { // MARK: - -中心位置矩形框 /// 是否需要绘制扫码矩形框,默认YES public var isNeedShowRetangle:Bool = true /** * 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比 */ public var whRatio:CGFloat = 1.0 /** @brief 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移 */ public var centerUpOffset:CGFloat = 44 /** * 矩形框(视频显示透明区)域离界面左边及右边距离,默认60 */ public var xScanRetangleOffset:CGFloat = 60 /** @brief 矩形框线条颜色,默认白色 */ public var colorRetangleLine = UIColor.white //MARK -矩形框(扫码区域)周围4个角 /** @brief 扫码区域的4个角类型 */ public var photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Outer //4个角的颜色 public var colorAngle = UIColor(red: 0.0, green: 167.0/255.0, blue: 231.0/255.0, alpha: 1.0) //扫码区域4个角的宽度和高度 public var photoframeAngleW:CGFloat = 24.0 public var photoframeAngleH:CGFloat = 24.0 /** @brief 扫码区域4个角的线条宽度,默认6,建议8到4之间 */ public var photoframeLineW:CGFloat = 6 //MARK: ----动画效果 /** @brief 扫码动画效果:线条或网格 */ public var anmiationStyle = LBXScanViewAnimationStyle.LineMove /** * 动画效果的图像,如线条或网格的图像 */ public var animationImage:UIImage? // MARK: -非识别区域颜色,默认 RGBA (0,0,0,0.5),范围(0--1) public var color_NotRecoginitonArea:UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5); public init() { animationImage = UIImage(named: "MGCodeScan.bundle/qrcode_Scan_weixin_Line.png") } }
mit
shiratsu/RxSwift
RxExample/RxExample/Examples/Numbers/NumbersViewController.swift
8
918
// // NumbersViewController.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class NumbersViewController: ViewController { @IBOutlet weak var number1: UITextField! @IBOutlet weak var number2: UITextField! @IBOutlet weak var number3: UITextField! @IBOutlet weak var result: UILabel! override func viewDidLoad() { super.viewDidLoad() Observable.combineLatest(number1.rx.text.orEmpty, number2.rx.text.orEmpty, number3.rx.text.orEmpty) { textValue1, textValue2, textValue3 -> Int in return (Int(textValue1) ?? 0) + (Int(textValue2) ?? 0) + (Int(textValue3) ?? 0) } .map { $0.description } .bindTo(result.rx.text) .addDisposableTo(disposeBag) } }
mit
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/TokenStream.swift
9
5509
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// An _org.antlr.v4.runtime.IntStream_ whose symbols are _org.antlr.v4.runtime.Token_ instances. /// public protocol TokenStream: IntStream { /// /// Get the _org.antlr.v4.runtime.Token_ instance associated with the value returned by /// _#LA LA(k)_. This method has the same pre- and post-conditions as /// _org.antlr.v4.runtime.IntStream#LA_. In addition, when the preconditions of this method /// are met, the return value is non-null and the value of /// `LT(k).getType()==LA(k)`. /// /// - SeeAlso: org.antlr.v4.runtime.IntStream#LA /// func LT(_ k: Int) throws -> Token? /// /// Gets the _org.antlr.v4.runtime.Token_ at the specified `index` in the stream. When /// the preconditions of this method are met, the return value is non-null. /// /// The preconditions for this method are the same as the preconditions of /// _org.antlr.v4.runtime.IntStream#seek_. If the behavior of `seek(index)` is /// unspecified for the current state and given `index`, then the /// behavior of this method is also unspecified. /// /// The symbol referred to by `index` differs from `seek()` only /// in the case of filtering streams where `index` lies before the end /// of the stream. Unlike `seek()`, this method does not adjust /// `index` to point to a non-ignored symbol. /// /// - Throws: ANTLRError.illegalArgument if {code index} is less than 0 /// - Throws: ANTLRError.unsupportedOperation if the stream does not support /// retrieving the token at the specified index /// func get(_ index: Int) throws -> Token /// /// Gets the underlying _org.antlr.v4.runtime.TokenSource_ which provides tokens for this /// stream. /// func getTokenSource() -> TokenSource /// /// Return the text of all tokens within the specified `interval`. This /// method behaves like the following code (including potential exceptions /// for violating preconditions of _#get_, but may be optimized by the /// specific implementation. /// /// /// TokenStream stream = ...; /// String text = ""; /// for (int i = interval.a; i &lt;= interval.b; i++) { /// text += stream.get(i).getText(); /// } /// /// /// - Parameter interval: The interval of tokens within this stream to get text /// for. /// - Returns: The text of all tokens within the specified interval in this /// stream. /// /// func getText(_ interval: Interval) throws -> String /// /// Return the text of all tokens in the stream. This method behaves like the /// following code, including potential exceptions from the calls to /// _org.antlr.v4.runtime.IntStream#size_ and _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be /// optimized by the specific implementation. /// /// /// TokenStream stream = ...; /// String text = stream.getText(new Interval(0, stream.size())); /// /// /// - Returns: The text of all tokens in the stream. /// func getText() throws -> String /// /// Return the text of all tokens in the source interval of the specified /// context. This method behaves like the following code, including potential /// exceptions from the call to _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be /// optimized by the specific implementation. /// /// If `ctx.getSourceInterval()` does not return a valid interval of /// tokens provided by this stream, the behavior is unspecified. /// /// /// TokenStream stream = ...; /// String text = stream.getText(ctx.getSourceInterval()); /// /// /// - Parameter ctx: The context providing the source interval of tokens to get /// text for. /// - Returns: The text of all tokens within the source interval of `ctx`. /// func getText(_ ctx: RuleContext) throws -> String /// /// Return the text of all tokens in this stream between `start` and /// `stop` (inclusive). /// /// If the specified `start` or `stop` token was not provided by /// this stream, or if the `stop` occurred before the `start` /// token, the behavior is unspecified. /// /// For streams which ensure that the _org.antlr.v4.runtime.Token#getTokenIndex_ method is /// accurate for all of its provided tokens, this method behaves like the /// following code. Other streams may implement this method in other ways /// provided the behavior is consistent with this at a high level. /// /// /// TokenStream stream = ...; /// String text = ""; /// for (int i = start.getTokenIndex(); i &lt;= stop.getTokenIndex(); i++) { /// text += stream.get(i).getText(); /// } /// /// /// - Parameter start: The first token in the interval to get text for. /// - Parameter stop: The last token in the interval to get text for (inclusive). /// - Throws: ANTLRError.unsupportedOperation if this stream does not support /// this method for the specified tokens /// - Returns: The text of all tokens lying between the specified `start` /// and `stop` tokens. /// /// func getText(_ start: Token?, _ stop: Token?) throws -> String }
bsd-3-clause
justindhill/Jiramazing
src/model/Project.swift
1
6177
// // Project.swift // Jiramazing // // Created by Justin Hill on 7/23/16. // Copyright © 2016 Justin Hill. All rights reserved. // import Foundation @objc(JRAProject) public class Project: NSObject, NSCoding { public var url: NSURL? @objc(identifier) public var id: String? public var key: String? public var projectDescription: String? public var lead: User? // TODO: components support public var issueTypes: [IssueType]? public var browseUrl: NSURL? public var email: String? public var assigneeType: String? public var versions: [Version]? public var name: String? public var roles: [String: NSURL]? public var avatarUrls: [AvatarSize: NSURL]? public var category: ProjectCategory? // Coding keys private let UrlKey = "url" private let IdKey = "id" private let KeyKey = "key" private let DescriptionKey = "description" private let LeadKey = "lead" private let IssueTypesKey = "issueTypes" private let BrowseUrlKey = "browseUrl" private let EmailKey = "emailKey" private let AssigneeTypeKey = "assigneeType" private let VersionsKey = "versions" private let NameKey = "name" private let RolesKey = "roles" private let AvatarUrlsKey = "avatarUrls" private let CategoryKey = "category" init(attributes: [String: AnyObject]) { super.init() self.id = attributes["id"] as? String self.key = attributes["key"] as? String self.projectDescription = attributes["description"] as? String self.email = attributes["email"] as? String self.assigneeType = attributes["assigneeType"] as? String self.name = attributes["name"] as? String if let urlString = attributes["self"] as? String, let url = NSURL(string: urlString) { self.url = url } if let urlString = attributes["url"] as? String, let url = NSURL(string: urlString) { self.browseUrl = url } if let leadAttributes = attributes["lead"] as? [String: AnyObject] { self.lead = User(attributes: leadAttributes) } if let issueTypesAttributes = attributes["issueTypes"] as? [[String: AnyObject]] { self.issueTypes = issueTypesAttributes.map({ (issueTypeAttributes) -> IssueType in return IssueType(attributes: issueTypeAttributes) }) } if let rolesAttributes = attributes["roles"] as? [String: String] { var roles = [String: NSURL]() for (roleName, roleUrlString) in rolesAttributes { if let roleUrl = NSURL(string: roleUrlString) { roles[roleName] = roleUrl } } self.roles = roles } if let versionsAttributes = attributes["versions"] as? [[String: AnyObject]] { self.versions = versionsAttributes.map({ (versionAttributes) -> Version in return Version(attributes: versionAttributes) }) } if let avatarUrlsAttributes = attributes["avatarUrls"] as? [String: String] { self.avatarUrls = avatarUrlsAttributes.avatarSizeMap() } if let projectCategoryAttributes = attributes["projectCategory"] as? [String: AnyObject] { self.category = ProjectCategory(attributes: projectCategoryAttributes) } } public required init?(coder d: NSCoder) { super.init() self.url = d.decodeObjectForKey(UrlKey) as? NSURL self.id = d.decodeObjectForKey(IdKey) as? String self.key = d.decodeObjectForKey(KeyKey) as? String self.projectDescription = d.decodeObjectForKey(DescriptionKey) as? String self.lead = d.decodeObjectForKey(LeadKey) as? User self.issueTypes = d.decodeObjectForKey(IssueTypesKey) as? [IssueType] self.browseUrl = d.decodeObjectForKey(BrowseUrlKey) as? NSURL self.email = d.decodeObjectForKey(EmailKey) as? String self.assigneeType = d.decodeObjectForKey(AssigneeTypeKey) as? String self.versions = d.decodeObjectForKey(VersionsKey) as? [Version] self.name = d.decodeObjectForKey(NameKey) as? String self.roles = d.decodeObjectForKey(RolesKey) as? [String: NSURL] if let decodableUrls = d.decodeObjectForKey(AvatarUrlsKey) as? [Int: NSURL] { var decodedUrls = [AvatarSize: NSURL]() for (key, value) in decodableUrls { if let avatarSize = AvatarSize(rawValue: key) { decodedUrls[avatarSize] = value } } self.avatarUrls = decodedUrls } self.category = d.decodeObjectForKey(CategoryKey) as? ProjectCategory } override public var description: String { get { let key = self.key ?? "nil" let id = self.id ?? "nil" return super.description.stringByAppendingString(" \(key) - \(id)") } } public func encodeWithCoder(c: NSCoder) { c.encodeObject(self.url, forKey: UrlKey) c.encodeObject(self.id, forKey: IdKey) c.encodeObject(self.key, forKey: KeyKey) c.encodeObject(self.projectDescription, forKey: DescriptionKey) c.encodeObject(self.lead, forKey: LeadKey) c.encodeObject(self.issueTypes, forKey: IssueTypesKey) c.encodeObject(self.browseUrl, forKey: BrowseUrlKey) c.encodeObject(self.email, forKey: EmailKey) c.encodeObject(self.assigneeType, forKey: AssigneeTypeKey) c.encodeObject(self.versions, forKey: VersionsKey) c.encodeObject(self.name, forKey: NameKey) c.encodeObject(self.roles, forKey: RolesKey) if let avatarUrls = self.avatarUrls { var encodableUrls = [Int: NSURL]() for (key, value) in avatarUrls { encodableUrls[key.rawValue] = value } c.encodeObject(encodableUrls, forKey: AvatarUrlsKey) } else { c.encodeObject(nil, forKey: AvatarUrlsKey) } c.encodeObject(self.category, forKey: CategoryKey) } }
mit
mitochrome/complex-gestures-demo
apps/GestureInput/Carthage/Checkouts/RxDataSources/Sources/DataSources+Rx/RxCollectionViewSectionedAnimatedDataSource.swift
22
3903
// // RxCollectionViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 7/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif /* This is commented becuse collection view has bugs when doing animated updates. Take a look at randomized sections. */ open class RxCollectionViewSectionedAnimatedDataSource<S: AnimatableSectionModelType> : CollectionViewSectionedDataSource<S> , RxCollectionViewDataSourceType { public typealias Element = [S] public var animationConfiguration = AnimationConfiguration() // For some inexplicable reason, when doing animated updates first time // it crashes. Still need to figure out that one. var dataSet = false private let disposeBag = DisposeBag() // This subject and throttle are here // because collection view has problems processing animated updates fast. // This should somewhat help to alleviate the problem. private let partialUpdateEvent = PublishSubject<(UICollectionView, Event<Element>)>() public override init() { super.init() self.partialUpdateEvent // so in case it does produce a crash, it will be after the data has changed .observeOn(MainScheduler.asyncInstance) // Collection view has issues digesting fast updates, this should // help to alleviate the issues with them. .throttle(0.5, scheduler: MainScheduler.instance) .subscribe(onNext: { [weak self] event in self?.collectionView(event.0, throttledObservedEvent: event.1) }) .addDisposableTo(disposeBag) } /** This method exists because collection view updates are throttled because of internal collection view bugs. Collection view behaves poorly during fast updates, so this should remedy those issues. */ open func collectionView(_ collectionView: UICollectionView, throttledObservedEvent event: Event<Element>) { UIBindingObserver(UIElement: self) { dataSource, newSections in let oldSections = dataSource.sectionModels do { // if view is not in view hierarchy, performing batch updates will crash the app if collectionView.window == nil { dataSource.setSections(newSections) collectionView.reloadData() return } let differences = try differencesForSectionedView(initialSections: oldSections, finalSections: newSections) for difference in differences { dataSource.setSections(difference.finalSections) collectionView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration) } } catch let e { #if DEBUG print("Error while binding data animated: \(e)\nFallback to normal `reloadData` behavior.") rxDebugFatalError(e) #endif self.setSections(newSections) collectionView.reloadData() } }.on(event) } open func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Element>) { UIBindingObserver(UIElement: self) { dataSource, newSections in #if DEBUG self._dataSourceBound = true #endif if !self.dataSet { self.dataSet = true dataSource.setSections(newSections) collectionView.reloadData() } else { let element = (collectionView, observedEvent) dataSource.partialUpdateEvent.on(.next(element)) } }.on(observedEvent) } }
mit
tkremenek/swift
validation-test/compiler_crashers_fixed/00154-swift-printingdiagnosticconsumer-handlediagnostic.swift
65
466
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var x1 =I Bool !(a) } func prefix(with: Strin) -> <T>(() -> T) in\n
apache-2.0
2345Team/Design-Pattern-For-Swift
19.ChainOfResponsibility/19.ChainOfResponsibilityUITests/_9_ChainOfResponsibilityUITests.swift
1
1290
// // _9_ChainOfResponsibilityUITests.swift // 19.ChainOfResponsibilityUITests // // Created by yangbin on 16/5/23. // Copyright © 2016年 yangbin. All rights reserved. // import XCTest class _9_ChainOfResponsibilityUITests: 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
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/model/entities/MediaUrl.swift
1
251
// // MediaUrl.swift // Emby.ApiClient // import Foundation public struct MediaUrl: Codable { var url: String? var name: String? enum CodingKeys: String, CodingKey { case url = "Url" case name = "Name" } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/09906-swift-lexer-lexidentifier.swift
11
211
// 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<{{()->a in class d<T where B:b{func f
mit
sugawaray/tools
toolsTests/TermLastLineTests.swift
1
1277
// // TermLastLineTests.swift // tools // // Created by Yutaka Sugawara on 2016/09/11. // Copyright © 2016 Yutaka Sugawara. All rights reserved. // import XCTest class TermLastLineTests: 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 testWithEmpty() { let r = getlastline("") XCTAssertNil(r) } func testWithNL() { let r = getlastline("\n") XCTAssertEqual("", r) } func testPSwoNL() { let r = getlastline("$ ") XCTAssertNil(r) } func testPSwNL() { let r = getlastline("$ \n") XCTAssertEqual("", r) } func testPSwS() { let r = getlastline("$ abcdefg\n") XCTAssertEqual("abcdefg", r) } func testPSwSwoNL() { let r = getlastline("$ abcdefg") XCTAssertNil(r) } func testMulti() { let r = getlastline("$ abcdefg\n$ hijklmn\n") XCTAssertEqual("hijklmn", r) } }
gpl-2.0
Hodglim/hacking-with-swift
Project-14/WhackAPenguin/WhackSlot.swift
1
1841
// // WhackSlot.swift // WhackAPenguin // // Created by Darren Hodges on 27/10/2015. // Copyright © 2015 Darren Hodges. All rights reserved. // import UIKit import SpriteKit class WhackSlot: SKNode { var charNode: SKSpriteNode! var visible = false var isHit = false func configureAtPosition(pos: CGPoint) { position = pos // Hole let sprite = SKSpriteNode(imageNamed: "whackHole") addChild(sprite) // Mask let cropNode = SKCropNode() cropNode.position = CGPoint(x: 0, y: 15) cropNode.zPosition = 1 cropNode.maskNode = SKSpriteNode(imageNamed: "whackMask") // Penguin charNode = SKSpriteNode(imageNamed: "penguinGood") charNode.position = CGPoint(x: 0, y: -90) charNode.name = "character" cropNode.addChild(charNode) addChild(cropNode) } func show(hideTime hideTime: Double) { if visible { return } // Reset scale (can get increased when penguin is tapped) charNode.xScale = 1 charNode.yScale = 1 charNode.runAction(SKAction.moveByX(0, y: 80, duration: 0.05)) visible = true isHit = false if RandomInt(min: 0, max: 2) == 0 { charNode.texture = SKTexture(imageNamed: "penguinGood") charNode.name = "charFriend" } else { charNode.texture = SKTexture(imageNamed: "penguinEvil") charNode.name = "charEnemy" } // Hide again after a delay RunAfterDelay(hideTime * 3.5) { [unowned self] in self.hide() } } func hide() { if !visible { return } charNode.runAction(SKAction.moveByX(0, y:-80, duration:0.05)) visible = false } func hit() { isHit = true let delay = SKAction.waitForDuration(0.25) let hide = SKAction.moveByX(0, y:-80, duration:0.5) let notVisible = SKAction.runBlock { [unowned self] in self.visible = false } charNode.runAction(SKAction.sequence([delay, hide, notVisible])) } }
mit
Zewo/HTTPSClient
Source/Client.swift
2
10075
// Client.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import TCPSSL @_exported import HTTPParser @_exported import HTTPSerializer public enum ClientError: ErrorProtocol { case httpsSchemeRequired case hostRequired case brokenConnection } public final class Client: Responder { public let host: String public let port: Int public let verifyBundle: String? public let certificate: String? public let privateKey: String? public let certificateChain: String? public let serializer: S4.RequestSerializer public let parser: S4.ResponseParser public let keepAlive: Bool public let connectionTimeout: Double public let requestTimeout: Double public let bufferSize: Int public var connection: C7.Connection? public init(uri: URI, configuration: ClientConfiguration = ClientConfiguration()) throws { guard let scheme = uri.scheme where scheme == "https" else { throw ClientError.httpsSchemeRequired } guard let host = uri.host else { throw ClientError.hostRequired } self.host = host self.port = uri.port ?? 443 self.verifyBundle = configuration.verifyBundle self.certificate = configuration.certificate self.privateKey = configuration.privateKey self.certificateChain = configuration.certificateChain self.serializer = configuration.serializer self.parser = configuration.parser self.keepAlive = configuration.keepAlive self.connectionTimeout = configuration.connectionTimeout self.requestTimeout = configuration.requestTimeout self.bufferSize = configuration.bufferSize } public convenience init(uri: String, configuration: ClientConfiguration = ClientConfiguration()) throws { try self.init(uri: URI(uri), configuration: configuration) } } extension Client { private func addHeaders(to request: inout Request) { let port = (self.port == 443) ? "" : ":\(self.port)" request.host = "\(host)\(port)" request.userAgent = "Zewo" if !keepAlive && request.connection == nil { request.connection = "close" } } public func respond(to request: Request) throws -> Response { var request = request addHeaders(to: &request) let connection: Connection if let c = self.connection { connection = c } else { connection = try TCPSSLConnection( host: host, port: port, verifyBundle: verifyBundle, certificate: certificate, privateKey: privateKey, certificateChain: certificateChain, SNIHostname: host, timingOut: now() + connectionTimeout ) try connection.open(timingOut: now() + connectionTimeout) self.connection = connection } let requestDeadline = now() + requestTimeout // TODO: Add deadline... S4.RequestSerializer.serialize(_:to:timingOut:) try serializer.serialize(request, to: connection) while true { let data = try connection.receive(upTo: bufferSize, timingOut: requestDeadline) if let response = try parser.parse(data) { if let didUpgrade = request.didUpgrade { try didUpgrade(response, connection) } if !keepAlive { self.connection = nil } return response } else if data.count == 0 { //no data received, connection got broken throw ClientError.brokenConnection } } } public func send(_ request: Request, middleware: Middleware...) throws -> Response { var request = request addHeaders(to: &request) return try middleware.chain(to: self).respond(to: request) } private func send(_ request: Request, middleware: [Middleware]) throws -> Response { var request = request addHeaders(to: &request) let response = try middleware.chain(to: self).respond(to: request) if 400..<600 ~= response.status.statusCode { //error response code, destroy the connection self.connection = nil } return response } } extension Client { public func send(method: Method, uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: method, uri: uri, headers: headers, body: body, middleware: middleware) } public func send(method: Method, uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: method, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { public func get(_ uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: .get, uri: uri, headers: headers, body: body, middleware: middleware) } public func get(_ uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: .get, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { public func post(_ uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: .post, uri: uri, headers: headers, body: body, middleware: middleware) } public func post(_ uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: .post, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { public func put(_ uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: .put, uri: uri, headers: headers, body: body, middleware: middleware) } public func put(_ uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: .put, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { public func patch(_ uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: .patch, uri: uri, headers: headers, body: body, middleware: middleware) } public func patch(_ uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: .patch, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { public func delete(_ uri: String, headers: Headers = [:], body: Data = [], middleware: Middleware...) throws -> Response { return try send(method: .delete, uri: uri, headers: headers, body: body, middleware: middleware) } public func delete(_ uri: String, headers: Headers = [:], body: DataConvertible, middleware: Middleware...) throws -> Response { return try send(method: .delete, uri: uri, headers: headers, body: body, middleware: middleware) } } extension Client { private func send(method: Method, uri: String, headers: Headers = [:], body: Data = [], middleware: [Middleware]) throws -> Response { let request = try Request(method: method, uri: URI(uri), headers: headers, body: body) return try send(request, middleware: middleware) } private func send(method: Method, uri: String, headers: Headers = [:], body: DataConvertible, middleware: [Middleware]) throws -> Response { let request = try Request(method: method, uri: URI(uri), headers: headers, body: body.data) return try send(request, middleware: middleware) } } extension Request { public var connection: String? { get { return headers["Connection"] } set(connection) { headers["Connection"] = connection } } var host: String? { get { return headers["Host"] } set(host) { headers["Host"] = host } } // Warning: The storage key has to be in sync with Zewo.HTTP's upgrade property. var didUpgrade: ((Response, Stream) throws -> Void)? { get { return storage["request-connection-upgrade"] as? (Response, Stream) throws -> Void } set(didUpgrade) { storage["request-connection-upgrade"] = didUpgrade } } var userAgent: String? { get { return headers["User-Agent"] } set(userAgent) { headers["User-Agent"] = userAgent } } }
mit
kenechilearnscode/AppUpdateCheck
AppUpdateCheck.swift
1
1449
// // AppUpdateCheck.swift // // // Created by Kc on 03/11/2015. // // import Foundation class AppUpdateCheck { let defaults = NSUserDefaults.standardUserDefaults() // gets instance of NSUserDefaults for persistent store let currentAppVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String // gets current app version on user's device func saveCurrentVersionToDefaults() { // saves currentAppVersion to defaults defaults.setObject(currentAppVersion, forKey: "appVersion") defaults.synchronize() } func hasAppBeenUpdated() -> Bool { var appUpdated = false // indicates whether app has been updated or not let previousAppVersion = defaults.stringForKey("appVersion") // checks stored app version in NSUserDefaults if previousAppVersion == nil { // first run, no appVersion has ever been saved to NSUserDefaults saveCurrentVersionToDefaults() } else if previousAppVersion != currentAppVersion { // app versions are different, thus the app has been updated saveCurrentVersionToDefaults() appUpdated = true } print("The current app version is: \(currentAppVersion). \n The app has been updated: \(appUpdated)") return appUpdated } }
mit
cuzv/TinyCoordinator
Sample/UICollectionViewSample/CollectionViewCell.swift
1
2575
// // CollectionViewCell.swift // Copyright (c) 2016 Red Rain (https://github.com/cuzv). // // 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 TinyCoordinator import SnapKit class CollectionViewCell: UICollectionViewCell, TCReusableViewSupport { let nameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.brown label.font = UIFont.systemFont(ofSize: 17) label.lineBreakMode = .byCharWrapping label.numberOfLines = 0 return label }() override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.lightGray nameLabel.layer.borderColor = UIColor.red.cgColor nameLabel.layer.borderWidth = 1 contentView.addSubview(nameLabel) nameLabel.snp.makeConstraints { (make) -> Void in make.edges.equalTo(contentView).inset(UIEdgeInsetsMake(8, 8, 8, 8)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { debugPrint("\(#file):\(#line):\(#function)") } override func layoutSubviews() { nameLabel.preferredMaxLayoutWidth = bounds.width - 16 super.layoutSubviews() } func populate(data: TCDataType) { if let data = data as? CellDataItem { nameLabel.text = data.name } else if let data = data as? CellDataItem2 { nameLabel.text = data.name } } }
mit
ReactiveX/RxSwift
Tests/RxCocoaTests/UIProgressView+RxTests.swift
5
1006
// // UIProgressView+RxTests.swift // Tests // // Created by Krunoslav Zaher on 11/26/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import RxCocoa import RxSwift import RxRelay import RxTest import XCTest final class UIProgressViewTests: RxTest { } extension UIProgressViewTests { func testProgressView_HasWeakReference() { ensureControlObserverHasWeakReference(UIProgressView(), { (progressView: UIProgressView) -> AnyObserver<Float> in progressView.rx.progress.asObserver() }, { BehaviorRelay<Float>(value: 0.0).asObservable() }) } func testProgressView_NextElementsSetsValue() { let subject = UIProgressView() let progressSequence = BehaviorRelay<Float>(value: 0.0) let disposable = progressSequence.asObservable().bind(to: subject.rx.progress) defer { disposable.dispose() } progressSequence.accept(1.0) XCTAssert(subject.progress == progressSequence.value, "Expected progress to have been set") } }
mit
proversity-org/edx-app-ios
Test/SnackbarViewsTests.swift
2
987
// // SnackbarViewsTests.swift // edX // // Created by Saeed Bashir on 7/15/16. // Copyright © 2016 edX. All rights reserved. // @testable import edX class SnackbarViewsTests: SnapshotTestCase { func testVersionUpgradeView() { let upgradeView = VersionUpgradeView(message: Strings.VersionUpgrade.newVersionAvailable) let size = upgradeView.systemLayoutSizeFitting(screenSize) upgradeView.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height) upgradeView.layoutIfNeeded() assertSnapshotValidWithContent(upgradeView) } func testOfflineView() { let offlineView = OfflineView(message: Strings.offline, selector: nil) let size = offlineView.systemLayoutSizeFitting(screenSize) offlineView.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height) offlineView.layoutIfNeeded() assertSnapshotValidWithContent(offlineView) } }
apache-2.0
coodly/laughing-adventure
iOS/UI/MenuContainerAware.swift
1
692
/* * Copyright 2017 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public protocol MenuContainerAware { var container: CoodlySlideMenuViewController? { get set } }
apache-2.0
kickstarter/ios-oss
Kickstarter-iOS/Features/RewardAddOnSelection/Datasource/RewardAddOnSelectionDataSource.swift
1
1340
import Foundation import KsApi import Library import Prelude import UIKit final class RewardAddOnSelectionDataSource: ValueCellDataSource { private enum Section: Int { case rewardAddOns case emptyState } func load(_ values: [RewardAddOnSelectionDataSourceItem]) { self.clearValues() let rewardAddOns = values.compactMap(\.rewardAddOnCardViewData) if !rewardAddOns.isEmpty { self.set( values: rewardAddOns, cellClass: RewardAddOnCell.self, inSection: Section.rewardAddOns.rawValue ) } else { let emptyStateViewTypes = values.compactMap(\.emptyStateViewType) self.set( values: emptyStateViewTypes, cellClass: EmptyStateCell.self, inSection: Section.emptyState.rawValue ) } } override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) { switch (cell, value) { case let (cell as RewardAddOnCell, value as RewardAddOnCardViewData): cell.configureWith(value: value) case let (cell as EmptyStateCell, value as EmptyStateViewType): cell.configureWith(value: value) default: assertionFailure("Unrecognized (cell, value) combo.") } } func isEmptyStateIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section == Section.emptyState.rawValue } }
apache-2.0
whitepaperclip/Exsilio-iOS
Exsilio/WaypointViewController.swift
1
8915
// // WaypointViewController.swift // Exsilio // // Created by Nick Kezhaya on 4/29/16. // // import UIKit import Fusuma import SwiftyJSON import Alamofire import SCLAlertView import FontAwesome_swift import SVProgressHUD import Mapbox class WaypointViewController: UIViewController, UITextFieldDelegate { @IBOutlet var nameField: UITextField? @IBOutlet var descriptionField: UITextField? @IBOutlet var selectedImageView: UIImageView? @IBOutlet var openMapButton: EXButton? @IBOutlet var pickImageButton: EXButton? var selectedImage: UIImage? { didSet { selectedImageView?.image = selectedImage } } var selectedPoint: CLLocationCoordinate2D? var waypoint: Waypoint? override func viewDidLoad() { self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UI.BackIcon, style: .plain, target: self, action: #selector(dismissModal)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(saveWaypoint)) self.openMapButton?.darkBorderStyle() self.pickImageButton?.darkBorderStyle() self.openMapButton?.setIcon(.map) self.pickImageButton?.setIcon(.camera) if let waypoint = self.waypoint { if let name = waypoint["name"] as? String { self.nameField?.text = name } if let description = waypoint["description"] as? String { self.descriptionField?.text = description } if let latitude = waypoint["latitude"] as? Double, let longitude = waypoint["longitude"] as? Double { self.pointSelected(CLLocationCoordinate2D(latitude: latitude, longitude: longitude)) } if let imageURL = waypoint["image_url"] as? String { if imageURL != API.MissingImagePath { SVProgressHUD.show() Alamofire.request(imageURL).responseImage { response in SVProgressHUD.dismiss() if let image = response.result.value { self.fusumaImageSelected(image) } } } } } self.nameField?.becomeFirstResponder() } @IBAction func openMap() { if let navController = self.storyboard!.instantiateViewController(withIdentifier: "MapNavigationController") as? UINavigationController { let vc = navController.viewControllers.first as! MapViewController vc.delegate = self vc.startingPoint = self.selectedPoint present(navController, animated: true, completion: nil) } } func dismissModal() { self.navigationController?.popViewController(animated: true) } func validateMessage() -> Bool { var message = "" if self.nameField?.text == nil || self.nameField!.text!.isEmpty { message = "You forgot to put a name in." } else if self.selectedPoint == nil { message = "You forgot to select a point on the map." } if !message.isEmpty { SCLAlertView().showError("Whoops!", subTitle: message, closeButtonTitle: "OK") return false } return true } func pointSelected(_ coordinate: CLLocationCoordinate2D) { selectedPoint = coordinate openMapButton?.layer.borderWidth = 0 openMapButton?.backgroundColor = UI.GreenColor openMapButton?.tintColor = .white openMapButton?.setIcon(.check) openMapButton?.updateColor(.white) } func saveWaypoint() { if !self.validateMessage() { return } var waypoint: Waypoint = self.waypoint == nil ? [:] : self.waypoint! if let name = self.nameField?.text { waypoint["name"] = name } if let description = self.descriptionField?.text { waypoint["description"] = description } if let coords = self.selectedPoint { waypoint["latitude"] = coords.latitude waypoint["longitude"] = coords.longitude } if let image = self.selectedImage { if waypoint["photo"] == nil || (waypoint["photo"] as! UIImage) != image { waypoint["photo"] = image } } if let tourId = CurrentTourSingleton.sharedInstance.tour["id"] as? Int { var method: Alamofire.HTTPMethod = .post let waypointId = waypoint["id"] var url = "\(API.URL)\(API.ToursPath)/\(tourId)\(API.WaypointsPath)" if waypointId != nil { method = .put url = url + "/\(waypointId!)" } var urlRequest: URLRequest do { urlRequest = try URLRequest(url: url, method: method, headers: API.authHeaders()) } catch { return } SVProgressHUD.show() Alamofire.upload( multipartFormData: { multipartFormData in let waypointName = waypoint["name"] as! String let latitude = waypoint["latitude"] as! Double let longitude = waypoint["longitude"] as! Double multipartFormData.append(waypointName.data(using: String.Encoding.utf8)!, withName: "waypoint[name]") multipartFormData.append("\(latitude)".data(using: String.Encoding.utf8)!, withName: "waypoint[latitude]") multipartFormData.append("\(longitude)".data(using: String.Encoding.utf8)!, withName: "waypoint[longitude]") if let description = waypoint["description"] as? String { multipartFormData.append(description.data(using: String.Encoding.utf8)!, withName: "waypoint[description]") } if let image = waypoint["photo"] as? UIImage { multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "waypoint[image]", fileName: "image.png", mimeType: "image/png") } }, with: urlRequest, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in switch response.result { case .success(let json): SVProgressHUD.dismiss() if let errors = JSON(json)["errors"].string { SCLAlertView().showError("Whoops!", subTitle: errors, closeButtonTitle: "OK") } else { self.dismissModal() } break default: SVProgressHUD.dismiss() break } } default: SVProgressHUD.dismiss() break } } ) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.descriptionField { self.descriptionField?.resignFirstResponder() } else { self.descriptionField?.becomeFirstResponder() } return true } } extension WaypointViewController: FusumaDelegate { func fusumaVideoCompleted(withFileURL fileURL: URL) { } @IBAction func pickImage() { let fusumaViewController = FusumaViewController() fusumaViewController.delegate = self self.present(fusumaViewController, animated: true, completion: nil) } func fusumaImageSelected(_ image: UIImage) { self.selectedImage = image self.pickImageButton?.layer.borderWidth = 0 self.pickImageButton?.backgroundColor = UI.GreenColor self.pickImageButton?.tintColor = .white self.pickImageButton?.setIcon(.check) self.pickImageButton?.setTitleColor(.white, for: .normal) self.pickImageButton?.updateColor(.white) } func fusumaCameraRollUnauthorized() { SCLAlertView().showError("Error", subTitle: "We need to access the camera in order to designate a photo for this waypoint.", closeButtonTitle: "OK") } } extension WaypointViewController: MapViewDelegate { func mapView(_ mapView: MGLMapView, didTapAt coordinate: CLLocationCoordinate2D) { mapView.clear() let annotation = MGLPointAnnotation() annotation.coordinate = coordinate mapView.addAnnotation(annotation) pointSelected(coordinate) } }
mit
realm/SwiftLint
Source/swiftlint/Helpers/ProgressBar.swift
1
2072
import Dispatch import Foundation import SwiftLintFramework // Inspired by https://github.com/jkandzi/Progress.swift actor ProgressBar { private var index = 1 private var lastPrintedTime: TimeInterval = 0.0 private let startTime = uptime() private let count: Int init(count: Int) { self.count = count } func initialize() { // When progress is printed, the previous line is reset, so print an empty line before anything else queuedPrintError("") } func printNext() { guard index <= count else { return } let currentTime = uptime() if currentTime - lastPrintedTime > 0.1 || index == count { let lineReset = "\u{1B}[1A\u{1B}[K" let bar = makeBar() let timeEstimate = makeTimeEstimate(currentTime: currentTime) let lineContents = "\(index) of \(count) \(bar) \(timeEstimate)" queuedPrintError("\(lineReset)\(lineContents)") lastPrintedTime = currentTime } index += 1 } // MARK: - Private private func makeBar() -> String { let barLength = 30 let completedBarElements = Int(Double(barLength) * (Double(index) / Double(count))) let barArray = Array(repeating: "=", count: completedBarElements) + Array(repeating: " ", count: barLength - completedBarElements) return "[\(barArray.joined())]" } private func makeTimeEstimate(currentTime: TimeInterval) -> String { let totalTime = currentTime - startTime let itemsPerSecond = Double(index) / totalTime let estimatedTimeRemaining = Double(count - index) / itemsPerSecond let estimatedTimeRemainingString = "\(Int(estimatedTimeRemaining))s" return "ETA: \(estimatedTimeRemainingString) (\(Int(itemsPerSecond)) files/s)" } } #if os(Linux) // swiftlint:disable:next identifier_name private let NSEC_PER_SEC = 1_000_000_000 #endif private func uptime() -> TimeInterval { Double(DispatchTime.now().uptimeNanoseconds) / Double(NSEC_PER_SEC) }
mit
rdlester/simply-giphy
Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UIGestureRecognizer.swift
1
724
import ReactiveSwift import UIKit import enum Result.NoError extension Reactive where Base: UIGestureRecognizer { /// Create a signal which sends a `next` event for each gesture event /// /// - returns: A trigger signal. public var stateChanged: Signal<Base, NoError> { return Signal { observer in let receiver = CocoaTarget<Base>(observer) { gestureRecognizer in return gestureRecognizer as! Base } base.addTarget(receiver, action: #selector(receiver.invoke)) let disposable = lifetime.ended.observeCompleted(observer.sendCompleted) return ActionDisposable { [weak base = self.base] in disposable?.dispose() base?.removeTarget(receiver, action: #selector(receiver.invoke)) } } } }
apache-2.0
Noah-Huppert/baking-app
baking-app/IngredientsWarningViewController.swift
1
2013
// // IngredientsWarningViewController.swift // baking-app // // Created by Noah Huppert on 1/19/16. // Copyright © 2016 noahhuppert.com. All rights reserved. // import UIKit class IngredientsWarningViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var recipe: Recipe? var uiIngredients: [UIIngredient] = [UIIngredient]() override func viewDidLoad() { super.viewDidLoad() for ing in (recipe?.ingredients)! { uiIngredients.append(UIIngredient(ingredient: ing)); } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let dc = segue.destinationViewController as! StepsViewController dc.recipe = recipe } @IBAction func onContinueButtonClicked(sender: AnyObject) { performSegueWithIdentifier("to_steps", sender: nil) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (recipe?.ingredients.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = indexPath.row let cell = tableView.dequeueReusableCellWithIdentifier("cell") let ingredient = uiIngredients[row] cell?.textLabel?.text = "\(ingredient.name) X \(ingredient.ammount)" if ingredient.checked { cell?.accessoryType = .Checkmark } else { cell?.accessoryType = .None } return cell! } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row uiIngredients[row].checked = !uiIngredients[row].checked if uiIngredients[row].checked { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark } else { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None } } }
mit
whiteshadow-gr/HatForIOS
HAT/Objects/Phatav2/HATProfile.swift
1
3093
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATProfile: HATObject, HatApiType { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `recordID` in JSON is `id` * `endpoint` in JSON is `endpoint` * `data` in JSON is `data` */ private enum CodingKeys: String, CodingKey { case recordID = "id" case endpoint = "endpoint" case data = "data" } // MARK: - Variables /// The endpoint the data are coming from. Optional public var endpoint: String? = "" /// The record ID of the data. Optional public var recordID: String? = "" /// The data of the profile public var data: HATProfileData = HATProfileData() // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(from dict: Dictionary<String, JSON>) { self.init() self.initialize(dict: dict) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public mutating func initialize(dict: Dictionary<String, JSON>) { if let tempRecordId: String = (dict[CodingKeys.recordID.rawValue]?.stringValue) { recordID = tempRecordId } if let tempEndPoint: String = (dict[CodingKeys.endpoint.rawValue]?.stringValue) { endpoint = tempEndPoint } if let tempData: [String: JSON] = (dict[CodingKeys.data.rawValue]?.dictionaryValue) { data = HATProfileData(dict: tempData) } } // MARK: - HatApiType Protocol /** It initialises everything from the received Dictionary file from the cache - fromCache: The dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let json: JSON = JSON(fromCache) self.initialize(dict: json.dictionaryValue) } // MARK: - JSON Mapper /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.endpoint.rawValue: self.endpoint ?? "", CodingKeys.recordID.rawValue: self.recordID ?? "", CodingKeys.data.rawValue: self.data.toJSON() ] } }
mpl-2.0
Candyroot/DesignPattern
iterator/iterator/MenuComponent.swift
1
917
// // MenuComponent.swift // iterator // // Created by Bing Liu on 11/27/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Foundation class MenuComponent { func add(menuComponent: MenuComponent) { fatalError("Unsupported Operation") } func remove(menuComponent: MenuComponent) { fatalError("Unsupported Operation") } func getChild(i: Int) -> MenuComponent { fatalError("Unsupported Operation") } func getName() -> String { fatalError("Unsupported Operation") } func getDescription() -> String { fatalError("Unsupported Operation") } func getPrice() -> Double { fatalError("Unsupported Operation") } func isVegetarian() -> Bool { fatalError("Unsupported Operation") } func print() { fatalError("Unsupported Operation") } }
apache-2.0
wireapp/wire-ios-data-model
Source/Model/Analytics/Analytics+UnknownMessage.swift
1
1328
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // private let unknownMessageEventName = "debug.compatibility_unknown_message" extension AnalyticsType { /// This method should be used to track messages which are not reported to /// be `known`, c.f. `knownMessage` in `ZMGenericMessage+Utils.m`. func tagUnknownMessageReceived() { tagEvent(unknownMessageEventName) } } /// Objective-C compatibility wrapper for the unknown message event class UnknownMessageAnalyticsTracker: NSObject { @objc(tagUnknownMessageWithAnalytics:) class func tagUnknownMessage(with analytics: AnalyticsType?) { analytics?.tagUnknownMessageReceived() } }
gpl-3.0
OneBestWay/EasyCode
Blog.playground/Pages/10.3.xcplaygroundpage/Contents.swift
1
537
//: [Previous](@previous) /*: # 新特性 * 允许用户在app内部对app进行评分,次数有限,每年三次 * 允许对app的评论做出回应,用户能够改变评分, * 改变app icon,不能远程添加,需要在发布app时添加icon到app内,会请求用户,需要用户的确认 1. 有多个icon可以让用户自由选择icon 1. [动态改变app icon](https://www.hackingwithswift.com/example-code/uikit/how-to-change-your-app-icon-dynamically-with-setalternateiconname) */ //: [Next](@next)
mit
octplane/Rapide
Rapide/AppDelegate.swift
1
7498
// // AppDelegate.swift // Rapide // // Created by Pierre Baillet on 11/06/2014. // Copyright (c) 2014 Pierre Baillet. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate, NSStreamDelegate, NSTextFieldDelegate { @IBOutlet var window :NSWindow! @IBOutlet var clipView :NSClipView! @IBOutlet var textView: NSTextView! @IBOutlet var tf :NSTextField! var inputStream :NSInputStream? var outputStream :NSOutputStream? var lineRemain :String = "" let nickname :String = "SpectreMan_" var server :CFString = "irc.freenode.org" var port :UInt32 = 6667 var ircPassword :String? = nil var motto :String = "Plus rapide qu'un missile !" var channel :String = "#swift-test" enum ConnectionStatus: Int { case Disconnected, BeforePassword, BeforeNick, BeforeUser, AfterUser, Connected func toString() -> String { switch self { case .Disconnected: return "Disconnected" case .BeforePassword: return "Before Password" case .BeforeNick: return "Before Nick Setting" case .BeforeUser: return "Before User Setting" case .AfterUser: return "After User Setting" case .Connected: return "Connected" } } } var status :ConnectionStatus = ConnectionStatus.Disconnected func get<T>(input: T?, orElse: T) -> T { if let i = input { return i } return orElse } func getI(input: String?, orElse: UInt32) -> UInt32 { if let i = input?.toInt() { return UInt32(i) } return orElse } func applicationDidFinishLaunching(aNotification: NSNotification) { let pi = NSProcessInfo.processInfo() server = get(pi.environment["server"] as? String, orElse: server as String) port = getI(pi.environment["port"] as? String, orElse: port) ircPassword = pi.environment["password"] as? String channel = get(pi.environment["channel"] as? String, orElse: channel) println("Connecting to \(server):\(port) and joining \(channel)") var readStream :Unmanaged<CFReadStream>? var writeStream :Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(nil, server, 6667, &readStream, &writeStream) self.inputStream = readStream!.takeUnretainedValue() self.outputStream = writeStream!.takeUnretainedValue() self.inputStream!.delegate = self self.outputStream!.delegate = self self.inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) self.outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) self.inputStream!.open() self.outputStream!.open() } func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){ var msg :String = "" switch eventCode { case NSStreamEvent.HasBytesAvailable: if aStream == self.inputStream { var data = [UInt8](count: 4096, repeatedValue: 0) let read = self.inputStream!.read(&data, maxLength: 4096) let strData = NSString(bytes: data, length: read, encoding: NSUTF8StringEncoding) handleInput(strData! as String) } case NSStreamEvent.HasSpaceAvailable: if aStream == self.outputStream { msg = "Can write bytes" handleCommunication() } else { msg = "Can write on inputStream ??!" } case NSStreamEvent.OpenCompleted: msg = "Open has completed" self.status = ConnectionStatus.BeforePassword case NSStreamEvent.ErrorOccurred: msg = "Something wrong happened..." default: msg = "Something happened !" } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func handleInput(input :String) { var lines: [String] = split(input) { $0 == "\r\n" } // what's remaining to process if lines.count > 0 { lines[0] = lineRemain + lines[0] } else { lines = [lineRemain] } lineRemain = lines[lines.count - 1] let parsable = lines[0...(lines.count-1)] for (line) in parsable { let parts = line.componentsSeparatedByString(" ") println(line) textView.insertText( line + "\n" ) let from = parts[0] let code = parts[1] if from == "PING" { sendMessage("PONG \(code)") } else if parts.count > 2 { let dest = parts[2] let rest = " ".join(parts[3...(parts.count - 1)]) if code == "JOIN" { let chan = dest.substringFromIndex(advance(dest.startIndex,1)) sendMessage("PRIVMSG \(chan) :\(motto)") } if code == "PRIVMSG" { if rest.rangeOfString("ping", options: nil, range: nil, locale: nil) != nil { sendMessage("PRIVMSG \(dest) :pong.") } if rest.rangeOfString("king", options: nil, range: nil, locale: nil) != nil { sendMessage("PRIVMSG \(dest) :kong.") } } } } } func handleCommunication() { switch self.status { case ConnectionStatus.BeforePassword: if ircPassword != nil { sendMessage("PASS \(ircPassword)") } println("PASS or not.") status = ConnectionStatus.BeforeNick // case ConnectionStatus.BeforeNick: println("Sending Nick") let msg = "NICK \(nickname)" sendMessage(msg) status = ConnectionStatus.BeforeUser // case ConnectionStatus.BeforeUser: println("Sending USER info") sendMessage("USER \(nickname) localhost servername Rapido Bot") status = ConnectionStatus.AfterUser case ConnectionStatus.AfterUser: println("JOINing") sendMessage("JOIN \(channel)") status = ConnectionStatus.Connected default: let c = 1 } } func sendMessage(msg: String) -> Int { let message = msg + "\r\n" let l = message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) var data = [UInt8](count: l, repeatedValue: 0) let r:Range = message.startIndex...(message.endIndex.predecessor()) let ret:Bool = message.getBytes(&data, maxLength: l, usedLength: nil, encoding: NSUTF8StringEncoding, options: nil, range: r, remainingRange: nil) return self.outputStream!.write(data, maxLength: l) } override func controlTextDidEndEditing(notif :NSNotification) { if notif.object as! NSObject == tf { sendMessage("PRIVMSG \(channel) :"+tf.stringValue) } } }
mit
milseman/swift
stdlib/public/SDK/Foundation/NSString.swift
14
4113
//===----------------------------------------------------------------------===// // // 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 Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
apache-2.0
johnno1962/eidolon
Kiosk/Bid Fulfillment/RegisterViewController.swift
1
3327
import UIKit import RxSwift protocol RegistrationSubController { // I know, leaky abstraction, but the amount // of useless syntax to change it isn't worth it. var finished: PublishSubject<Void> { get } } class RegisterViewController: UIViewController { @IBOutlet var flowView: RegisterFlowView! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! @IBOutlet var confirmButton: UIButton! var provider: Networking! let coordinator = RegistrationCoordinator() dynamic var placingBid = true private let _viewWillDisappear = PublishSubject<Void>() var viewWillDisappear: Observable<Void> { return self._viewWillDisappear.asObserver() } func internalNavController() -> UINavigationController? { return self.childViewControllers.first as? UINavigationController } override func viewDidLoad() { super.viewDidLoad() coordinator.storyboard = self.storyboard! let registerIndex = coordinator.currentIndex.asObservable() let indexIsConfirmed = registerIndex.map { return ($0 == RegistrationIndex.ConfirmVC.toInt()) } indexIsConfirmed .not() .bindTo(confirmButton.rx_hidden) .addDisposableTo(rx_disposeBag) registerIndex .bindTo(flowView.highlightedIndex) .addDisposableTo(rx_disposeBag) let details = self.fulfillmentNav().bidDetails flowView.details = details bidDetailsPreviewView.bidDetails = details flowView .highlightedIndex .asObservable() .distinctUntilChanged() .subscribeNext { [weak self] (index) in if let _ = self?.fulfillmentNav() { let registrationIndex = RegistrationIndex.fromInt(index) let nextVC = self?.coordinator.viewControllerForIndex(registrationIndex) self?.goToViewController(nextVC!) } } .addDisposableTo(rx_disposeBag) goToNextVC() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) _viewWillDisappear.onNext() } func goToNextVC() { let nextVC = coordinator.nextViewControllerForBidDetails(fulfillmentNav().bidDetails) goToViewController(nextVC) } func goToViewController(controller: UIViewController) { self.internalNavController()!.viewControllers = [controller] if let subscribableVC = controller as? RegistrationSubController { subscribableVC .finished .subscribeCompleted { [weak self] in self?.goToNextVC() self?.flowView.update() } .addDisposableTo(rx_disposeBag) } if let viewController = controller as? RegistrationPasswordViewController { viewController.provider = provider } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .ShowLoadingView { let nextViewController = segue.destinationViewController as! LoadingViewController nextViewController.placingBid = placingBid nextViewController.provider = provider } } }
mit
tonymuu/card-flipping-cell
cell flip/AppDelegate.swift
2
2137
// // AppDelegate.swift // cell flip // // Created by Mu Tong on 8/25/15. // Copyright (c) 2015 Tony Mu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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
haggag/spell-correct
SpellCorrector/ViewController.swift
1
520
// // ViewController.swift // SpellCorrector // // Created by Ahmad Haggag on 12/24/1435 AH. // Copyright (c) 1435 Ahmad Haggag. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
darthpelo/LedsControl
RPiLedsControl/Sources/App/GPIOService.swift
1
1819
#if os(Linux) import Glibc #else import Darwin.C #endif // MARK: - Darwin / Xcode Support #if os(OSX) private var O_SYNC: CInt { fatalError("Linux only") } #endif import SwiftyGPIO import SwiftGPIOLibrary enum Command { static let Zero = 0 static let One = 1 static let Two = 2 static let Three = 3 static let Four = 4 } enum GPIOError: Error { case InternalError } final class GPIOService { class var sharedInstance: GPIOService { struct Singleton { static let instance = GPIOService() } return Singleton.instance } private let gpioLib = GPIOLib.sharedInstance private var ports: [GPIOName: GPIO] = [:] private let list: [GPIOName] = [.P20, .P26] func setup() { self.ports = gpioLib.setupOUT(ports: [.P20, .P26], for: .RaspberryPi2) } var yellow: Int { return gpioLib.status(ports[.P20]) } var green: Int { return gpioLib.status(ports[.P26]) } func execute(command: Int) throws { switch(command) { case Command.Zero: powerOff() case Command.One: switchYellow(Command.One) case Command.Two: switchYellow(Command.Two) case Command.Three: switchGreen(Command.Three) case Command.Four: switchGreen(Command.Four) default: throw GPIOError.InternalError } } fileprivate func switchYellow(_ cmd: Int) { switch cmd { case Command.One: gpioLib.switchOn(ports: [.P20]) case Command.Two: gpioLib.switchOff(ports: [.P20]) default:() } } fileprivate func switchGreen(_ cmd: Int) { switch cmd { case Command.Three: gpioLib.switchOn(ports: [.P26]) case Command.Four: gpioLib.switchOff(ports: [.P26]) default:() } } fileprivate func powerOff() { gpioLib.switchOff(ports: list) } }
mit
abeschneider/stem
proto/tensor.pb.swift
1
6632
/* * DO NOT EDIT. * * Generated by the protocol buffer compiler. * Source: proto/tensor.proto * */ import Foundation import SwiftProtobuf struct header: ProtobufGeneratedMessage, ProtobufProto3Message { public var swiftClassName: String {return "header"} public var protoMessageName: String {return "header"} public var protoPackageName: String {return ""} public var jsonFieldNames: [String: Int] {return [ "type": 1, "rows": 2, "cols": 3, "stride": 4, "shape": 5, "dimIndex": 6, "offset": 7, ]} public var protoFieldNames: [String: Int] {return [ "type": 1, "rows": 2, "cols": 3, "stride": 4, "shape": 5, "dimIndex": 6, "offset": 7, ]} public var type: String = "" public var rows: Int64 = 0 public var cols: Int64 = 0 public var stride: [Int64] = [] public var shape: [Int64] = [] public var dimIndex: [Int64] = [] public var offset: [Int64] = [] public init() {} public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws { switch protoFieldNumber { case 1: try setter.decodeSingularField(fieldType: ProtobufString.self, value: &type) case 2: try setter.decodeSingularField(fieldType: ProtobufInt64.self, value: &rows) case 3: try setter.decodeSingularField(fieldType: ProtobufInt64.self, value: &cols) case 4: try setter.decodePackedField(fieldType: ProtobufInt64.self, value: &stride) case 5: try setter.decodePackedField(fieldType: ProtobufInt64.self, value: &shape) case 6: try setter.decodePackedField(fieldType: ProtobufInt64.self, value: &dimIndex) case 7: try setter.decodePackedField(fieldType: ProtobufInt64.self, value: &offset) default: break } } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if type != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: type, protoFieldNumber: 1, protoFieldName: "type", jsonFieldName: "type", swiftFieldName: "type") } if rows != 0 { try visitor.visitSingularField(fieldType: ProtobufInt64.self, value: rows, protoFieldNumber: 2, protoFieldName: "rows", jsonFieldName: "rows", swiftFieldName: "rows") } if cols != 0 { try visitor.visitSingularField(fieldType: ProtobufInt64.self, value: cols, protoFieldNumber: 3, protoFieldName: "cols", jsonFieldName: "cols", swiftFieldName: "cols") } if !stride.isEmpty { try visitor.visitPackedField(fieldType: ProtobufInt64.self, value: stride, protoFieldNumber: 4, protoFieldName: "stride", jsonFieldName: "stride", swiftFieldName: "stride") } if !shape.isEmpty { try visitor.visitPackedField(fieldType: ProtobufInt64.self, value: shape, protoFieldNumber: 5, protoFieldName: "shape", jsonFieldName: "shape", swiftFieldName: "shape") } if !dimIndex.isEmpty { try visitor.visitPackedField(fieldType: ProtobufInt64.self, value: dimIndex, protoFieldNumber: 6, protoFieldName: "dimIndex", jsonFieldName: "dimIndex", swiftFieldName: "dimIndex") } if !offset.isEmpty { try visitor.visitPackedField(fieldType: ProtobufInt64.self, value: offset, protoFieldNumber: 7, protoFieldName: "offset", jsonFieldName: "offset", swiftFieldName: "offset") } } public func _protoc_generated_isEqualTo(other: header) -> Bool { if type != other.type {return false} if rows != other.rows {return false} if cols != other.cols {return false} if stride != other.stride {return false} if shape != other.shape {return false} if dimIndex != other.dimIndex {return false} if offset != other.offset {return false} return true } } struct tensor: ProtobufGeneratedMessage, ProtobufProto3Message { public var swiftClassName: String {return "tensor"} public var protoMessageName: String {return "tensor"} public var protoPackageName: String {return ""} public var jsonFieldNames: [String: Int] {return [ "properties": 1, "storage": 2, ]} public var protoFieldNames: [String: Int] {return [ "properties": 1, "storage": 2, ]} private class _StorageClass { typealias ProtobufExtendedMessage = tensor var _properties: header? = nil var _storage: Data = Data() init() {} func decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws { switch protoFieldNumber { case 1: try setter.decodeSingularMessageField(fieldType: header.self, value: &_properties) case 2: try setter.decodeSingularField(fieldType: ProtobufBytes.self, value: &_storage) default: break } } func traverse(visitor: inout ProtobufVisitor) throws { if let v = _properties { try visitor.visitSingularMessageField(value: v, protoFieldNumber: 1, protoFieldName: "properties", jsonFieldName: "properties", swiftFieldName: "properties") } if _storage != Data() { try visitor.visitSingularField(fieldType: ProtobufBytes.self, value: _storage, protoFieldNumber: 2, protoFieldName: "storage", jsonFieldName: "storage", swiftFieldName: "storage") } } func isEqualTo(other: _StorageClass) -> Bool { if _properties != other._properties {return false} if _storage != other._storage {return false} return true } func copy() -> _StorageClass { let clone = _StorageClass() clone._properties = _properties clone._storage = _storage return clone } } private var _storage = _StorageClass() public var properties: header { get {return _storage._properties ?? header()} set {_uniqueStorage()._properties = newValue} } public var hasProperties: Bool { return _storage._properties != nil } public mutating func clearProperties() { return _storage._properties = nil } public var storage: Data { get {return _storage._storage} set {_uniqueStorage()._storage = newValue} } public init() {} public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws { try _uniqueStorage().decodeField(setter: &setter, protoFieldNumber: protoFieldNumber) } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { try _storage.traverse(visitor: &visitor) } public func _protoc_generated_isEqualTo(other: tensor) -> Bool { return _storage === other._storage || _storage.isEqualTo(other: other._storage) } private mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.copy() } return _storage } }
mit
SwiftyVK/SwiftyVK
Library/Sources/Networking/Attempt/Attempt.swift
2
3730
import Foundation protocol Attempt: class, OperationConvertible { init( request: URLRequest, session: VKURLSession, callbacks: AttemptCallbacks ) } final class AttemptImpl: Operation, Attempt { private let request: URLRequest private var task: VKURLSessionTask? private let urlSession: VKURLSession private let callbacks: AttemptCallbacks init( request: URLRequest, session: VKURLSession, callbacks: AttemptCallbacks ) { self.request = request self.urlSession = session self.callbacks = callbacks super.init() } override func main() { let semaphore = DispatchSemaphore(value: 0) let completion: (Data?, URLResponse?, Error?) -> () = { [weak self] data, response, error in /// Because URLSession executes completions in their own serial queue DispatchQueue.global(qos: .utility).async { defer { semaphore.signal() } guard let strongSelf = self, !strongSelf.isCancelled else { return } if let error = error as NSError?, error.code != NSURLErrorCancelled { strongSelf.callbacks.onFinish(.error(.urlRequestError(error))) } else if let data = data { strongSelf.callbacks.onFinish(Response(data)) } else { strongSelf.callbacks.onFinish(.error(.unexpectedResponse)) } } } task = urlSession.dataTask(with: request, completionHandler: completion) task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived), options: .new, context: nil) task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent), options: .new, context: nil) task?.resume() semaphore.wait() } override func observeValue( forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer? ) { guard let keyPath = keyPath else { return } guard let task = task else { return } switch keyPath { case (#keyPath(URLSessionTask.countOfBytesSent)): guard task.countOfBytesExpectedToSend > 0 else { return } callbacks.onSent(task.countOfBytesSent, task.countOfBytesExpectedToSend) case(#keyPath(URLSessionTask.countOfBytesReceived)): guard task.countOfBytesExpectedToReceive > 0 else { return } callbacks.onRecive(task.countOfBytesReceived, task.countOfBytesExpectedToReceive) default: break } } override func cancel() { super.cancel() task?.cancel() } deinit { task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived)) task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent)) } } struct AttemptCallbacks { let onFinish: (Response) -> () let onSent: (_ total: Int64, _ of: Int64) -> () let onRecive: (_ total: Int64, _ of: Int64) -> () init( onFinish: @escaping ((Response) -> ()) = { _ in }, onSent: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in }, onRecive: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in } ) { self.onFinish = onFinish self.onSent = onSent self.onRecive = onRecive } static var `default`: AttemptCallbacks { return AttemptCallbacks() } }
mit
doronkatz/firefox-ios
UITests/AuthenticationTests.swift
2
6021
/* 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 EarlGrey class AuthenticationTests: KIFTestCase { fileprivate var webRoot: String! override func setUp() { super.setUp() webRoot = SimplePageServer.start() BrowserUtils.dismissFirstRunUI() } override func tearDown() { BrowserUtils.resetToAboutHome(tester()) BrowserUtils.clearPrivateData(tester: tester()) super.tearDown() } /** * Tests HTTP authentication credentials and auto-fill. */ func testAuthentication() { loadAuthPage() // Make sure that 3 invalid credentials result in authentication failure. enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "foo", password: "bar") enterCredentials(usernameValue: "foo", passwordValue: "•••", username: "foo2", password: "bar2") enterCredentials(usernameValue: "foo2", passwordValue: "••••", username: "foo3", password: "bar3") // Use KIFTest framework for checking elements within webView tester().waitForWebViewElementWithAccessibilityLabel("auth fail") // Enter valid credentials and ensure the page loads. EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reload")).perform(grey_tap()) enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass") tester().waitForWebViewElementWithAccessibilityLabel("logged in") // Save the credentials. EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Save Login")) .inRoot(grey_kindOfClass(NSClassFromString("Client.SnackButton")!)) .perform(grey_tap()) logOut() loadAuthPage() // Make sure the credentials were saved and auto-filled. EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Log in")) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .perform(grey_tap()) tester().waitForWebViewElementWithAccessibilityLabel("logged in") // Add a private tab. EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("Menu")).perform(grey_tap()) EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("New Private Tab")) .inRoot(grey_kindOfClass(NSClassFromString("Client.MenuItemCollectionViewCell")!)) .perform(grey_tap()) loadAuthPage() // Make sure the auth prompt is shown. // Note that in the future, we might decide to auto-fill authentication credentials in private browsing mode, // but that's not currently supported. We assume the username and password fields are empty. enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass") tester().waitForWebViewElementWithAccessibilityLabel("logged in") } fileprivate func loadAuthPage() { EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\(webRoot!)/auth.html\n")) } fileprivate func logOut() { EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\(webRoot!)/auth.html?logout=1\n")) // Wait until the dialog shows up let dialogAppeared = GREYCondition(name: "Wait the login dialog to appear", block: { _ in var errorOrNil: NSError? let matcher = grey_allOf([grey_accessibilityLabel("Cancel"), grey_sufficientlyVisible()]) EarlGrey.select(elementWithMatcher: matcher) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success }).wait(withTimeout: 20) GREYAssertTrue(dialogAppeared, reason: "Failed to display login dialog") EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Cancel")) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .perform(grey_tap()) } fileprivate func enterCredentials(usernameValue: String, passwordValue: String, username: String, password: String) { // Wait until the dialog shows up let dialogAppeared = GREYCondition(name: "Wait the login dialog to appear", block: { () -> Bool in var errorOrNil: NSError? let matcher = grey_allOf([grey_accessibilityValue(usernameValue), grey_sufficientlyVisible()]) EarlGrey.select(elementWithMatcher: matcher).assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success }) let success = dialogAppeared?.wait(withTimeout: 20) GREYAssertTrue(success!, reason: "Failed to display login dialog") let usernameField = EarlGrey.select(elementWithMatcher: grey_accessibilityValue(usernameValue)) let passwordField = EarlGrey.select(elementWithMatcher: grey_accessibilityValue(passwordValue)) if usernameValue != "Username" { usernameField.perform(grey_doubleTap()) EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Select All")) .inRoot(grey_kindOfClass(NSClassFromString("UICalloutBarButton")!)) .perform(grey_tap()) } usernameField.perform(grey_typeText(username)) passwordField.perform(grey_typeText(password)) EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Log in")) .inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)) .perform(grey_tap()) } }
mpl-2.0
silt-lang/silt
Sources/Lithosphere/Utils.swift
1
2454
//===-------------------- Utils.swift - Utility Functions -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public struct ByteSourceRange { public let offset: Int public let length: Int public init(offset: Int, length: Int) { self.offset = offset self.length = length } public var endOffset: Int { return offset+length } public var isEmpty: Bool { return length == 0 } public func intersectsOrTouches(_ other: ByteSourceRange) -> Bool { return self.endOffset >= other.offset && self.offset <= other.endOffset } public func intersects(_ other: ByteSourceRange) -> Bool { return self.endOffset > other.offset && self.offset < other.endOffset } /// Returns the byte range for the overlapping region between two ranges. public func intersected(_ other: ByteSourceRange) -> ByteSourceRange { let start = max(self.offset, other.offset) let end = min(self.endOffset, other.endOffset) if start > end { return ByteSourceRange(offset: 0, length: 0) } else { return ByteSourceRange(offset: start, length: end-start) } } } public struct SourceEdit { /// The byte range of the original source buffer that the edit applies to. public let range: ByteSourceRange /// The length of the edit replacement in UTF8 bytes. public let replacementLength: Int public init(range: ByteSourceRange, replacementLength: Int) { self.range = range self.replacementLength = replacementLength } public func intersectsOrTouchesRange(_ other: ByteSourceRange) -> Bool { return self.range.intersectsOrTouches(other) } public func intersectsRange(_ other: ByteSourceRange) -> Bool { return self.range.intersects(other) } } extension String { func utf8Slice(offset: Int, length: Int) -> Substring { if length == 0 { return Substring() } let utf8 = self.utf8 let begin = utf8.index(utf8.startIndex, offsetBy: offset) let end = utf8.index(begin, offsetBy: length) return Substring(utf8[begin..<end]) } }
mit
DivineDominion/mac-licensing-fastspring-cocoafob
Shared/License/License.swift
1
698
// Copyright (c) 2015-2019 Christian Tietze // // See the file LICENSE for copying permission. /// Valid license information. public struct License { public let name: String public let licenseCode: String public init(name: String, licenseCode: String) { self.name = name self.licenseCode = licenseCode } } extension License { internal struct DefaultsKey: RawRepresentable { let rawValue: String init(rawValue: String) { self.rawValue = rawValue } static let name = DefaultsKey(rawValue: "licensee") static let licenseCode = DefaultsKey(rawValue: "license_code") } } extension License: Equatable { }
mit
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift
8
2236
// // UIBarButtonItem+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif fileprivate var rx_tap_key: UInt8 = 0 extension Reactive where Base: UIBarButtonItem { /// Bindable sink for `enabled` property. public var isEnabled: Binder<Bool> { return Binder(self.base) { element, value in element.isEnabled = value } } /// Bindable sink for `title` property. public var title: Binder<String> { return Binder(self.base) { element, value in element.title = value } } /// Reactive wrapper for target action pattern on `self`. public var tap: ControlEvent<()> { let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in Observable.create { [weak control = self.base] observer in guard let control = control else { observer.on(.completed) return Disposables.create() } let target = BarButtonItemTarget(barButtonItem: control) { observer.on(.next(())) } return target } .takeUntil(self.deallocated) .share() } return ControlEvent(events: source) } } @objc final class BarButtonItemTarget: RxTarget { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) } override func dispose() { super.dispose() #if DEBUG MainScheduler.ensureExecutingOnScheduler() #endif barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } @objc func action(_ sender: AnyObject) { callback() } } #endif
mit
codergaolf/DouYuTV
DouYuTV/DouYuTV/Classes/Tools/Extension/UIColor-Extension.swift
1
511
// // UIColor-Extension.swift // DouYuTV // // Created by 高立发 on 2016/11/14. // Copyright © 2016年 GG. All rights reserved. // import UIKit extension UIColor { convenience init(r : CGFloat, g : CGFloat,b : CGFloat) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0) } class func randomColor() -> UIColor { return UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) } }
mit
EPICmynamesBG/SKButton
SKButton-Demo2/SKButton-Demo2/GameScene.swift
1
3218
// // GameScene.swift // SKButton-Demo2 // // Created by Brandon Groff on 12/10/15. // Copyright (c) 2015 Brandon Groff. All rights reserved. // import SpriteKit class GameScene: SKScene, SKButtonDelegate { var myButtonArray = [SKButton]() override func didMoveToView(view: SKView) { /* Setup your scene here */ //Different ways to initialize an SKButton self.myButtonArray.append(SKButton()) self.myButtonArray.append(SKButton( buttonImage: "Button")) self.myButtonArray.append(SKButton( buttonImage: "Button", atPosition: CGPoint(x: 100,y: 100))) self.myButtonArray.append(SKButton( color: UIColor.orangeColor())) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click")) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click", atPosition: CGPoint(x: 150, y: 150))) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click", withText: "Text!")) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click", withText: "Text again!", atPosition: CGPoint(x: 200, y: 200))) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click", withText: "Text x 2!", withTextOffset: CGPoint(x: 5, y: 10))) self.myButtonArray.append(SKButton( defaultButtonImage: "Button", clickedImageName: "Button_click", withText: "The Last One", withTextOffset: CGPoint(x: 2, y: 5), atPosition: CGPoint(x: 250, y: 250))) //add my buttons to the view for button:SKButton in self.myButtonArray { //add the delegate first so we can get clicks! button.delegate = self self.addChild(button) } /* -- THINGS TO NOTICE AT RUNTIME -- * 1. Many buttons are stacked in the middle of the view. This is because * * the default position is center, and we didn't move them. * 2. On each button click, each button has a unique name. * 3. The next is overflowing from some of our buttons. That is because our * button is too small and our font size too large. Both of these can be changed * though using button.size and button.fontSize. Similarly, a larger button image * could also be provided. */ } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } //IMPORTANT: This is required by the SKButtonDelegate and to recieve button touches func skButtonTouchEnded(sender: SKButton) { print(sender.name) } }
mit
trafi/NibView
Sources/NibLoadable.swift
1
3432
// // NibLoadable.swift // NibLoadable // // Created by Domas on 10/02/2017. // Copyright © 2016 Trafi. All rights reserved. // import UIKit /** `NibLoadable` helps you reuse views created in .xib files. # Reference only from code Setup class by conforming to `NibLoadable`: class MyView: UIView, NibLoadable {} Get the view loaded from nib with a one-liner: let myView = MyView.fromNib() Setup like this will look for a file named "MyView.xib" in your project and load the view that is of type `MyView`. *Optionally* provide custom nib name (defaults to type name): class var nibName: String { return "MyCustomView" } *Optionally* provide custom bundle (defaults to class location): class var bundle: Bundle { return Bundle(for: self) } # Refencing from IB To reference view from another .xib or .storyboard file simply subclass `NibView`: class MyView: NibView {} If subclassing is **not an option** override `awakeAfter(using:)` with a call to `nibLoader`: class MyView: SomeBaseView, NibLoadable { open override func awakeAfter(using aDecoder: NSCoder) -> Any? { return nibLoader.awakeAfter(using: aDecoder, super.awakeAfter(using: aDecoder)) } } # @IBDesignable referencing from IB To see live updates and get intrinsic content size of view reference simply subclass `NibView` with `@IBDesignable` attribute: @IBDesignable class MyView: NibView {} If subclassing is **not an option** override functions of the view with calls to `nibLoader`: @IBDesignable class MyView: SomeBaseView, NibLoadable { open override func awakeAfter(using aDecoder: NSCoder) -> Any? { return nibLoader.awakeAfter(using: aDecoder, super.awakeAfter(using: aDecoder)) } #if TARGET_INTERFACE_BUILDER public override init(frame: CGRect) { super.init(frame: frame) nibLoader.initWithFrame() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() nibLoader.prepareForInterfaceBuilder() } open override func setValue(_ value: Any?, forKeyPath keyPath: String) { super.setValue(value, forKeyPath: keyPath) nibLoader.setValue(value, forKeyPath: keyPath) } #endif } */ public protocol NibLoadable: class { static var nibName: String { get } static var bundle: Bundle { get } } // MARK: - From Nib public extension NibLoadable where Self: UIView { static var nibName: String { return String(describing: self) } static var bundle: Bundle { return Bundle(for: self) } static func fromNib() -> Self { guard let nib = self.bundle.loadNibNamed(nibName, owner: nil, options: nil) else { fatalError("Failed loading the nib named \(nibName) for 'NibLoadable' view of type '\(self)'.") } guard let view = (nib.first { $0 is Self }) as? Self else { fatalError("Did not find 'NibLoadable' view of type '\(self)' inside '\(nibName).xib'.") } return view } }
mit
wscqs/FMDemo-
FMDemo/Classes/Module/Main/SettingViewController.swift
1
1276
// // SettingViewController.swift // FMDemo // // Created by mba on 17/2/12. // Copyright © 2017年 mbalib. All rights reserved. // import UIKit class SettingViewController: BaseViewController { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // MBACache.fetchString(key: kUserAvator) { (headimgurl) in // self.userImageView.qs_setImageFromUrl(headimgurl ?? "", placeholder: #imageLiteral(resourceName: "course_chapt_state1_ico"), isAvatar: true) // } // MBACache.fetchString(key: kUserName) { (nickname) in // self.userNameLabel.text = nickname // } self.userImageView.qs_setImageFromUrl(KeUserAccount.shared?.avatar ?? "", placeholder: #imageLiteral(resourceName: "user-ico"), isAvatar: true) self.userNameLabel.text = KeUserAccount.shared?.nickname } @IBAction func actionExitUser(_ sender: UIButton) { //清除账号 KeUserAccount.cleanAccount() _ = navigationController?.popToRootViewController(animated: false) } }
apache-2.0
nervousnet/nervousnet-iOS
nervous/Views/MainCVCellCollectionViewCell.swift
1
335
// // MainCVCellCollectionViewCell.swift // nervousnet // // Created by Sam Sulaimanov on 03/04/16. // Copyright © 2016 ethz. All rights reserved. // import UIKit class MainCVCellCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textLabel: UILabel! }
gpl-3.0
quintonwall/SalesforceViews
Pods/SwiftlySalesforce/Pod/Classes/LoginDelegate.swift
2
4080
// // LoginDelegate.swift // SwiftlySalesforce // // For license & details see: https://www.github.com/mike4aday/SwiftlySalesforce // Copyright (c) 2016. All rights reserved. // import SafariServices import PromiseKit import Alamofire public typealias LoginResult = Alamofire.Result<AuthData> public protocol LoginDelegate { func login(url: URL) throws } public protocol LoginViewController: class { var replacedRootViewController: UIViewController? { get set } } fileprivate final class SafariLoginViewController: SFSafariViewController, LoginViewController { // Hold reference to the view controller that's temporarily replaced by the login view controller var replacedRootViewController: UIViewController? } // MARK: - Extension extension LoginDelegate { public var loggingIn: Bool { get { if let _ = UIApplication.shared.keyWindow?.rootViewController as? LoginViewController { return true } else { return false } } } /// Initiates login process by replacing current root view controller with /// Salesforce-hosted webform, per OAuth2 "user-agent" flow. This is the prescribed /// authentication method, as the client app does not access the user credentials. /// See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_user_agent_oauth_flow.htm /// - Parameter url: Salesforce authorization URL public func login(url: URL) throws { guard !loggingIn else { throw SalesforceError.invalidity(message: "Already logging in!") } guard let window = UIApplication.shared.keyWindow else { throw SalesforceError.invalidity(message: "No valid window!") } // Replace current root view controller with Safari view controller for login let loginVC = SafariLoginViewController(url: url) loginVC.replacedRootViewController = window.rootViewController window.rootViewController = loginVC } /// Handles the redirect URL returned by Salesforce after OAuth2 authentication and authorization. /// Restores the root view controller that was replaced by the Salesforce-hosted login web form /// - Parameter url: URL returned by Salesforce after OAuth2 authentication & authorization public func handleRedirectURL(url: URL) { var result:LoginResult // Note: docs are wrong - error information may be in URL fragment *or* in query string... if let urlEncodedString = url.fragment ?? url.query, let authData = AuthData(urlEncodedString: urlEncodedString) { result = .success(authData) } else { // Can't make sense of the redirect URL result = .failure(SalesforceError.unsupportedURL(url: url)) } salesforce.authManager.loginCompleted(result: result) // Restore the original root view controller if let window = UIApplication.shared.keyWindow, let currentRootVC = window.rootViewController as? LoginViewController, let replacedRootVC = currentRootVC.replacedRootViewController { window.rootViewController = replacedRootVC } } @available(*, deprecated: 3.1.0, message: "Parameter 'redirectURL' renamed to 'url.' Call handleRedirectURL(url: URL) instead.") public func handleRedirectURL(redirectURL: URL) { return handleRedirectURL(url: redirectURL) } /// Call this to initiate logout process. /// Revokes OAuth2 refresh and/or access token, then replaces /// the current root view controller with a Safari view controller for login /// - Returns: Promise<Void>; chain to this for custom post-logout actions public func logout() -> Promise<Void> { return Promise<Void> { fulfill, reject in firstly { salesforce.authManager.revoke() }.then { () -> () in if let loginURL = try? salesforce.authManager.loginURL(), let window = UIApplication.shared.keyWindow { // Replace current root view controller with Safari view controller for login let loginVC = SafariLoginViewController(url: loginURL) loginVC.replacedRootViewController = window.rootViewController window.rootViewController = loginVC } fulfill() }.catch { error -> () in reject(error) } } } }
mit
nathawes/swift
test/Driver/response-file.swift
20
2383
// RUN: echo "-DTEST0" > %t.0.resp // RUN: %target-build-swift -typecheck @%t.0.resp %s 2>&1 | %FileCheck %s -check-prefix=SHORT // SHORT: warning: result of call to 'abs' is unused // RUN: %{python} -c 'for a in ["A", "B", "C", "D"]: print("-DTEST1" + a)' > %t.1.resp // RUN: %target-build-swift -typecheck @%t.1.resp %s 2>&1 | %FileCheck %s -check-prefix=MULTIPLE // MULTIPLE: warning: result of call to 'abs' is unused // RUN: echo "-DTEST2A -DTEST2B" > %t.2A.resp // RUN: echo "-DTEST2C -DTEST2D" > %t.2B.resp // RUN: %target-build-swift -typecheck @%t.2A.resp %s @%t.2B.resp 2>&1 | %FileCheck %s -check-prefix=MIXED // MIXED: warning: result of call to 'abs' is unused // RUN: echo "-DTEST3A" > %t.3.resp // RUN: echo "%s" >> %t.3.resp // RUN: echo "-DTEST3B" >> %t.3.resp // RUN: %target-build-swift -typecheck @%t.3.resp 2>&1 | %FileCheck %s -check-prefix=RESPONLY // RESPONLY: warning: result of call to 'abs' is unused // RUN: echo "-DTEST4A" > %t.4A.resp // RUN: echo "%s" >> %t.4A.resp // RUN: echo "@%t.4A.resp" > %t.4B.resp // RUN: echo "-DTEST4B" >> %t.4B.resp // RUN: %target-build-swift -typecheck @%t.4B.resp 2>&1 | %FileCheck %s -check-prefix=RECURSIVE // RECURSIVE: warning: result of call to 'abs' is unused // RUN: %{python} -c 'for i in range(500001): print("-DTEST5_" + str(i))' > %t.5.resp // RUN: %target-build-swift -typecheck @%t.5.resp %s 2>&1 | %FileCheck %s -check-prefix=LONG // LONG: warning: result of call to 'abs' is unused // RUN: %empty-directory(%t/tmp) // RUN: env TMPDIR=%t/tmp/ TMP=%t/tmp/ %target-swiftc_driver %s @%t.5.resp -save-temps -o %t/main // RUN: ls %t/tmp | grep arguments.*resp // RUN: %target-build-swift -typecheck -v @%t.5.resp %s 2>&1 | %FileCheck %s -check-prefix=VERBOSE // VERBOSE: @{{[^ ]*}}arguments-{{[0-9a-zA-Z]+}}.resp{{"?}} # -frontend -typecheck -primary-file // RUN: not %target-swiftc_driver %s @%t.5.resp -Xfrontend -debug-crash-immediately 2>&1 | %FileCheck %s -check-prefix=TRACE // TRACE: Program arguments: {{[^ ]*}}swift{{(-frontend|c)?(\.exe)?}} -frontend -c -primary-file #if TEST0 abs(-5) #endif #if TEST1A && TEST1B && TEST1C && TEST1D abs(-5) #endif #if TEST2A && TEST2B && TEST2C && TEST2D abs(-5) #endif #if TEST3A && TEST3B abs(-5) #endif #if TEST4A && TEST4B abs(-5) #endif #if TEST5_0 && TEST5_10 && TEST5_100 && TEST5_1000 && TEST5_10000 && TEST5_100000 && TEST5_500000 abs(-5) #endif
apache-2.0
gavrix/ViewModelsSamples
ImageViewModelExample/ImageViewModelExample/Models.swift
1
413
// // Models.swift // ImageViewModelExample // // Created by Sergii Gavryliuk on 2016-04-07. // Copyright © 2016 Sergey Gavrilyuk. All rights reserved. // import Foundation struct User { var username: String var userpicUrl: String init(json: [String: AnyObject]) { self.username = (json["login"] as? String) ?? "" self.userpicUrl = (json["avatar_url"] as? String) ?? "" } }
mit
ruddfawcett/Notepad
Example macOS/ViewController.swift
1
860
// // ViewController.swift // Example macOS // // Created by Christian Tietze on 21.07.17. // Copyright © 2017 Rudd Fawcett. All rights reserved. // import Cocoa import Notepad class ViewController: NSViewController { @IBOutlet var textView: NSTextView! let storage = Storage() override func viewDidLoad() { super.viewDidLoad() let theme = Theme("one-dark") storage.theme = theme textView.backgroundColor = theme.backgroundColor textView.insertionPointColor = theme.tintColor textView.layoutManager?.replaceTextStorage(storage) if let testFile = Bundle.main.path(forResource: "tests", ofType: "md"), let text = try? String(contentsOfFile: testFile) { textView.string = text } else { print("Unable to load demo text.") } } }
mit
practicalswift/swift
test/attr/accessibility.swift
23
10283
// RUN: %target-typecheck-verify-swift // CHECK PARSING private // expected-note {{modifier already specified here}} private // expected-error {{duplicate modifier}} func duplicateAttr() {} private // expected-note {{modifier already specified here}} public // expected-error {{duplicate modifier}} func duplicateAttrChanged() {} private // expected-note 2 {{modifier already specified here}} public // expected-error {{duplicate modifier}} internal // expected-error {{duplicate modifier}} func triplicateAttrChanged() {} private // expected-note 3 {{modifier already specified here}} public // expected-error {{duplicate modifier}} internal // expected-error {{duplicate modifier}} fileprivate // expected-error {{duplicate modifier}} func quadruplicateAttrChanged() {} private(set) public var customSetter = 0 fileprivate(set) public var customSetter2 = 0 private(set) // expected-note {{modifier already specified here}} public(set) // expected-error {{duplicate modifier}} var customSetterDuplicateAttr = 0 private(set) // expected-note {{modifier already specified here}} public // expected-note {{modifier already specified here}} public(set) // expected-error {{duplicate modifier}} private // expected-error {{duplicate modifier}} var customSetterDuplicateAttrsAllAround = 0 private(get) // expected-error{{expected 'set' as subject of 'private' modifier}} var invalidSubject = 0 private(42) // expected-error{{expected 'set' as subject of 'private' modifier}} var invalidSubject2 = 0 private(a bunch of random tokens) // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}} var invalidSubject3 = 0 private(set // expected-error{{expected ')' in 'private' modifier}} var unterminatedSubject = 0 private(42 // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}} var unterminatedInvalidSubject = 0 private() // expected-error{{expected 'set' as subject of 'private' modifier}} var emptySubject = 0 private( // expected-error{{expected 'set' as subject of 'private' modifier}} var unterminatedEmptySubject = 0 // Check that the parser made it here. duplicateAttr(1) // expected-error{{argument passed to call that takes no arguments}} // CHECK ALLOWED DECLS private import Swift // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-9=}} private(set) infix operator ~~~ // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}} private typealias MyInt = Int private struct TestStruct { private typealias LocalInt = MyInt private var x = 0 private let y = 1 private func method() {} private static func method() {} private init() {} private subscript(_: MyInt) -> LocalInt { return x } } private class TestClass { private init() {} internal deinit {} // expected-error {{'internal' modifier cannot be applied to this declaration}} {{3-12=}} } private enum TestEnum { private case Foo, Bar // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}} } private protocol TestProtocol { private associatedtype Foo // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}} internal var Bar: Int { get } // expected-error {{'internal' modifier cannot be used in protocols}} {{3-12=}} // expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}} public func baz() // expected-error {{'public' modifier cannot be used in protocols}} {{3-10=}} // expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}} } public(set) func publicSetFunc() {} // expected-error {{'public' modifier cannot be applied to this declaration}} {{1-13=}} public(set) var defaultVis = 0 // expected-error {{internal variable cannot have a public setter}} internal(set) private var privateVis = 0 // expected-error {{private variable cannot have an internal setter}} private(set) var defaultVisOK = 0 private(set) public var publicVis = 0 private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only variables}} {{1-14=}} return 42 } private(set) var computedRW: Int { get { return 42 } set { } } private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to constants}} {{1-14=}} public struct Properties { private(set) var stored = 42 private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}} return 42 } private(set) var computedRW: Int { get { return 42 } set { } } private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}} public(set) var defaultVis = 0 // expected-error {{internal property cannot have a public setter}} open(set) var defaultVis2 = 0 // expected-error {{internal property cannot have an open setter}} public(set) subscript(a a: Int) -> Int { // expected-error {{internal subscript cannot have a public setter}} get { return 0 } set {} } internal(set) private subscript(b b: Int) -> Int { // expected-error {{private subscript cannot have an internal setter}} get { return 0 } set {} } private(set) subscript(c c: Int) -> Int { get { return 0 } set {} } private(set) public subscript(d d: Int) -> Int { get { return 0 } set {} } private(set) subscript(e e: Int) -> Int { return 0 } // expected-error {{'private(set)' modifier cannot be applied to read-only subscripts}} {{3-16=}} } private extension Properties { public(set) var extProp: Int { // expected-error {{private property cannot have a public setter}} get { return 42 } set { } } open(set) var extProp2: Int { // expected-error {{private property cannot have an open setter}} get { return 42 } set { } } } internal protocol EmptyProto {} internal protocol EmptyProto2 {} private extension Properties : EmptyProto {} // expected-error {{'private' modifier cannot be used with extensions that declare protocol conformances}} {{1-9=}} private(set) extension Properties : EmptyProto2 {} // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}} public struct PublicStruct {} internal struct InternalStruct {} // expected-note * {{declared here}} private struct PrivateStruct {} // expected-note * {{declared here}} protocol InternalProto { // expected-note * {{declared here}} associatedtype Assoc } public extension InternalProto {} // expected-error {{extension of internal protocol cannot be declared public}} {{1-8=}} internal extension InternalProto where Assoc == PublicStruct {} internal extension InternalProto where Assoc == InternalStruct {} internal extension InternalProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}} private extension InternalProto where Assoc == PublicStruct {} private extension InternalProto where Assoc == InternalStruct {} private extension InternalProto where Assoc == PrivateStruct {} public protocol PublicProto { associatedtype Assoc } public extension PublicProto {} public extension PublicProto where Assoc == PublicStruct {} public extension PublicProto where Assoc == InternalStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}} public extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses a private type}} internal extension PublicProto where Assoc == PublicStruct {} internal extension PublicProto where Assoc == InternalStruct {} internal extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}} private extension PublicProto where Assoc == PublicStruct {} private extension PublicProto where Assoc == InternalStruct {} private extension PublicProto where Assoc == PrivateStruct {} extension PublicProto where Assoc == InternalStruct { public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}} open func bar() {} // expected-error {{cannot declare an open instance method in an extension with internal requirements}} {{3-7=internal}} } extension InternalProto { public func foo() {} // no effect, but no warning } extension InternalProto where Assoc == PublicStruct { public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}} open func bar() {} // expected-error {{cannot declare an open instance method in an extension with internal requirements}} {{3-7=internal}} } public struct GenericStruct<Param> {} public extension GenericStruct where Param: InternalProto {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}} extension GenericStruct where Param: InternalProto { public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}} } public class OuterClass { class InnerClass {} } public protocol PublicProto2 { associatedtype T associatedtype U } // FIXME: With the current design, the below should not diagnose. // // However, it does, because we look at the bound decl in the // TypeRepr first, and it happens to already be set. // // FIXME: Once we no longer do that, come up with another strategy // to make the above diagnose. extension PublicProto2 where Self.T : OuterClass, Self.U == Self.T.InnerClass { public func cannotBePublic() {} // expected-error@-1 {{cannot declare a public instance method in an extension with internal requirements}} } public extension OuterClass { open convenience init(x: ()) { self.init() } // expected-warning@-1 {{'open' modifier conflicts with extension's default access of 'public'}} // expected-error@-2 {{only classes and overridable class members can be declared 'open'; use 'public'}} }
apache-2.0
bzatrok/iOSAssessment
BestBuy/Classes/Controllers/BBGridSelectorViewController.swift
1
4527
// // BBGridSelectorViewController.swift // BestBuy // // Created by Ben Zatrok on 28/02/17. // Copyright © 2017 AmberGlass. All rights reserved. // import UIKit class BBGridSelectorViewController: UIViewController { //MARK: Variables var itemsList : [BBObject] = [] var SKUList : [Int]? var selectedItem : BBObject? let gridCellID = "gridCellID" let emptyCellID = "emptyCellID" let accessoryProductDetailSegue = "accessoryProductDetailSegue" //MARK: IBOutlets @IBOutlet weak var collectionView : UICollectionView! //MARK: IBActions //MARK: Life-Cycle override func viewDidLoad() { super.viewDidLoad() setupDelegation() setupView() } //MARK: Functions /** Sets up required delegates */ func setupDelegation() { collectionView.delegate = self collectionView.dataSource = self } /** Sets up the view and fetches required data */ func setupView() { guard let SKUList = SKUList, SKUList.count > 0 else { return } BBRequestManager.shared.queryProducts(withSKUs: SKUList) { [weak self] success, responseProductsList in guard let strongSelf = self, let responseProductsList = responseProductsList, success else { return } strongSelf.itemsList = responseProductsList DispatchQueue.main.async { strongSelf.collectionView.reloadData() } } } //MARK: Segue handling override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let selectedProduct = selectedItem as? BBProduct, let destination = segue.destination as? BBProductDetailViewController, segue.identifier == accessoryProductDetailSegue else { return } destination.selectedProduct = selectedProduct } } extension BBGridSelectorViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedItem = itemsList[indexPath.row] performSegue(withIdentifier: accessoryProductDetailSegue, sender: self) } } extension BBGridSelectorViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemsList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: gridCellID, for: indexPath) as? BBGridCollectionViewCell, let product = itemsList[indexPath.row] as? BBProduct else { return collectionView.dequeueReusableCell(withReuseIdentifier: emptyCellID, for: indexPath) } cell.backgroundImageView.contentMode = .scaleAspectFit if let image_URL = product.image_URL { cell.backgroundImageView.kf.setImage(with: URL(string: image_URL), placeholder: nil, options: nil, progressBlock: nil) { Image, error, cacheType, url in DispatchQueue.main.async { cell.setNeedsLayout() } } } if let sale_price = product.sale_price, let regular_price = product.regular_price { let salePriceString = NSMutableAttributedString(string: "$\(sale_price) ") if sale_price != regular_price { let strikeThroughPriceString: NSMutableAttributedString = NSMutableAttributedString(string: "$\(regular_price)") strikeThroughPriceString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, strikeThroughPriceString.length)) salePriceString.append(strikeThroughPriceString) } cell.priceLabel.attributedText = salePriceString } return cell } }
mit
dereknex/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
42
11477
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart) } public override func computeAxis(#xValAverageLength: Double, xValues: [String?]) { _xAxis.values = xValues var longest = _xAxis.getLongestLabel() as NSString var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]) _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5) _xAxis.labelHeight = longestSize.height } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return } var xoffset = _xAxis.xOffset if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left) } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right) } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left) } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right) drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left) } } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment) { var labelFont = _xAxis.labelFont var labelTextColor = _xAxis.labelTextColor // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) var bd = _chart.data as! BarChartData var step = bd.dataSetCount for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { var label = _xAxis.values[i] if (label == nil) { continue } position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0 // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0 } transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var position = CGPoint(x: 0.0, y: 0.0) var bd = _chart.data as! BarChartData // take into consideration that multiple DataSets increase _deltaX var step = bd.dataSetCount for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5 transformer.pointValueToPixel(&position) if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _gridLineSegmentsBuffer[0].y = position.y _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight _gridLineSegmentsBuffer[1].y = position.y CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _xAxis.axisLineWidth) if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) var trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i] position.x = 0.0 position.y = CGFloat(l.limit) position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _limitLineSegmentsBuffer[0].y = position.y _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight _limitLineSegmentsBuffer[1].y = position.y CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) var label = l.label // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) var xOffset: CGFloat = add var yOffset: CGFloat = l.lineWidth + labelLineHeight if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
apache-2.0
randallli/material-components-ios
components/TextFields/examples/TextFieldLegacyExample.swift
1
16090
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length import MaterialComponents.MaterialTextFields final class TextFieldLegacySwiftExample: UIViewController { let scrollView = UIScrollView() let name: MDCTextField = { let name = MDCTextField() name.translatesAutoresizingMaskIntoConstraints = false name.autocapitalizationType = .words return name }() let address: MDCTextField = { let address = MDCTextField() address.translatesAutoresizingMaskIntoConstraints = false address.autocapitalizationType = .words return address }() let city: MDCTextField = { let city = MDCTextField() city.translatesAutoresizingMaskIntoConstraints = false city.autocapitalizationType = .words return city }() let cityController: MDCTextInputControllerLegacyDefault let state: MDCTextField = { let state = MDCTextField() state.translatesAutoresizingMaskIntoConstraints = false state.autocapitalizationType = .allCharacters return state }() let zip: MDCTextField = { let zip = MDCTextField() zip.translatesAutoresizingMaskIntoConstraints = false return zip }() let zipController: MDCTextInputControllerLegacyDefault let phone: MDCTextField = { let phone = MDCTextField() phone.translatesAutoresizingMaskIntoConstraints = false return phone }() let message: MDCMultilineTextField = { let message = MDCMultilineTextField() message.translatesAutoresizingMaskIntoConstraints = false return message }() var allTextFieldControllers = [MDCTextInputControllerLegacyDefault]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { cityController = MDCTextInputControllerLegacyDefault(textInput: city) zipController = MDCTextInputControllerLegacyDefault(textInput: zip) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white:0.97, alpha: 1.0) title = "Material Text Fields" setupScrollView() setupTextFields() registerKeyboardNotifications() addGestureRecognizer() let styleButton = UIBarButtonItem(title: "Style", style: .plain, target: self, action: #selector(buttonDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = styleButton } func setupTextFields() { scrollView.addSubview(name) let nameController = MDCTextInputControllerLegacyDefault(textInput: name) name.delegate = self name.text = "Grace Hopper" nameController.placeholderText = "Name" nameController.helperText = "First and Last" allTextFieldControllers.append(nameController) scrollView.addSubview(address) let addressController = MDCTextInputControllerLegacyDefault(textInput: address) address.delegate = self addressController.placeholderText = "Address" allTextFieldControllers.append(addressController) scrollView.addSubview(city) city.delegate = self cityController.placeholderText = "City" allTextFieldControllers.append(cityController) // In iOS 9+, you could accomplish this with a UILayoutGuide. // TODO: (larche) add iOS version specific implementations let stateZip = UIView() stateZip.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stateZip) stateZip.addSubview(state) let stateController = MDCTextInputControllerLegacyDefault(textInput: state) state.delegate = self stateController.placeholderText = "State" allTextFieldControllers.append(stateController) stateZip.addSubview(zip) zip.delegate = self zipController.placeholderText = "Zip Code" zipController.helperText = "XXXXX" allTextFieldControllers.append(zipController) scrollView.addSubview(phone) let phoneController = MDCTextInputControllerLegacyDefault(textInput: phone) phone.delegate = self phoneController.placeholderText = "Phone Number" allTextFieldControllers.append(phoneController) scrollView.addSubview(message) let messageController = MDCTextInputControllerLegacyDefault(textInput: message) #if swift(>=3.2) message.text = """ This is where you could put a multi-line message like an email. It can even handle new lines. """ #else message.text = "This is where you could put a multi-line message like an email. It can even handle new lines./n" #endif message.textView?.delegate = self messageController.placeholderText = "Message" allTextFieldControllers.append(messageController) var tag = 0 for controller in allTextFieldControllers { guard let textField = controller.textInput as? MDCTextField else { continue } textField.tag = tag tag += 1 } let views = [ "name": name, "address": address, "city": city, "stateZip": stateZip, "phone": phone, "message": message ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[name]-[address]-[city]-[stateZip]-[phone]-[message]", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: name, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1, constant: 0)] constraints += [NSLayoutConstraint(item: name, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1, constant: 0)] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[name]|", options: [], metrics: nil, views: views) #if swift(>=3.2) if #available(iOS 11.0, *) { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .bottomMargin, multiplier: 1, constant: -20)] } else { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] } #else constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] #endif let stateZipViews = [ "state": state, "zip": zip ] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[state(80)]-[zip]|", options: [.alignAllTop], metrics: nil, views: stateZipViews) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[state]|", options: [], metrics: nil, views: stateZipViews) NSLayoutConstraint.activate(constraints) } func setupScrollView() { view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(NSLayoutConstraint.constraints( withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) let marginOffset: CGFloat = 16 let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset) scrollView.layoutMargins = margins } func addGestureRecognizer() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDidTouch(sender: ))) self.scrollView.addGestureRecognizer(tapRecognizer) } // MARK: - Actions @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } @objc func buttonDidTouch(sender: Any) { let isFloatingEnabled = allTextFieldControllers.first?.isFloatingEnabled ?? false let alert = UIAlertController(title: "Floating Labels", message: nil, preferredStyle: .actionSheet) let defaultAction = UIAlertAction(title: "Default (Yes)" + (isFloatingEnabled ? " ✓" : ""), style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = true }) } alert.addAction(defaultAction) let floatingAction = UIAlertAction(title: "No" + (isFloatingEnabled ? "" : " ✓"), style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = false }) } alert.addAction(floatingAction) present(alert, animated: true, completion: nil) } } extension TextFieldLegacySwiftExample: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let rawText = textField.text else { return true } let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string) if textField == zip { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters), fullString[range].characterCount > 0 { zipController.setErrorText("Error: Zip can only contain numbers", errorAccessibilityValue: nil) } else if fullString.characterCount > 5 { zipController.setErrorText("Error: Zip can only contain five digits", errorAccessibilityValue: nil) } else { zipController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == city { if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits), fullString[range].characterCount > 0 { cityController.setErrorText("Error: City can only contain letters", errorAccessibilityValue: nil) } else { cityController.setErrorText(nil, errorAccessibilityValue: nil) } } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let index = textField.tag if index + 1 < allTextFieldControllers.count, let nextField = allTextFieldControllers[index + 1].textInput { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } } extension TextFieldLegacySwiftExample: UITextViewDelegate { func textViewDidEndEditing(_ textView: UITextView) { print(textView.text) } } // MARK: - Keyboard Handling extension TextFieldLegacySwiftExample { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: .UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: frame.height, right: 0.0) } @objc func keyboardWillHide(notif: Notification) { scrollView.contentInset = UIEdgeInsets() } } // MARK: - Status Bar Style extension TextFieldLegacySwiftExample { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension TextFieldLegacySwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Text Field", "[Legacy] Typical Use"] } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TransactionsRouter/TransactionsRouter.swift
1
28055
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainComponentLibrary import BlockchainNamespace import Combine import DIKit import ErrorsUI import FeatureFormDomain import FeatureKYCUI import FeatureProductsDomain import FeatureTransactionDomain import Localization import MoneyKit import PlatformKit import PlatformUIKit import RIBs import SwiftUI import ToolKit import UIComponentsKit /// A protocol defining the API for the app's entry point to any `Transaction Flow`. /// NOTE: Presenting a Transaction Flow can never fail because it's expected for any error to be handled within the flow. /// Non-recoverable errors should force the user to abandon the flow. public protocol TransactionsRouterAPI { /// Some APIs may not have UIKit available. In this instance we use /// `TopMostViewControllerProviding`. func presentTransactionFlow( to action: TransactionFlowAction ) -> AnyPublisher<TransactionFlowResult, Never> func presentTransactionFlow( to action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> } public enum UserActionServiceResult: Equatable { case canPerform case cannotPerform(upgradeTier: KYC.Tier?) case questions } public protocol UserActionServiceAPI { func canPresentTransactionFlow( toPerform action: TransactionFlowAction ) -> AnyPublisher<UserActionServiceResult, Never> } final class TransactionsRouter: TransactionsRouterAPI { private let app: AppProtocol private let analyticsRecorder: AnalyticsEventRecorderAPI private let featureFlagsService: FeatureFlagsServiceAPI private let pendingOrdersService: PendingOrderDetailsServiceAPI private let eligibilityService: EligibilityServiceAPI private let userActionService: UserActionServiceAPI private let coincore: CoincoreAPI private let kycRouter: PlatformUIKit.KYCRouting private let kyc: FeatureKYCUI.Routing private let alertViewPresenter: AlertViewPresenterAPI private let topMostViewControllerProvider: TopMostViewControllerProviding private let loadingViewPresenter: LoadingViewPresenting private var transactionFlowBuilder: TransactionFlowBuildable private let buyFlowBuilder: BuyFlowBuildable private let sellFlowBuilder: SellFlowBuildable private let signFlowBuilder: SignFlowBuildable private let sendFlowBuilder: SendRootBuildable private let interestFlowBuilder: InterestTransactionBuilder private let withdrawFlowBuilder: WithdrawRootBuildable private let depositFlowBuilder: DepositRootBuildable private let receiveCoordinator: ReceiveCoordinator private let fiatCurrencyService: FiatCurrencySettingsServiceAPI private let productsService: FeatureProductsDomain.ProductsServiceAPI @LazyInject var tabSwapping: TabSwapping /// Currently retained RIBs router in use. private var currentRIBRouter: RIBs.Routing? private var cancellables: Set<AnyCancellable> = [] init( app: AppProtocol = resolve(), analyticsRecorder: AnalyticsEventRecorderAPI = resolve(), featureFlagsService: FeatureFlagsServiceAPI = resolve(), pendingOrdersService: PendingOrderDetailsServiceAPI = resolve(), eligibilityService: EligibilityServiceAPI = resolve(), userActionService: UserActionServiceAPI = resolve(), kycRouter: PlatformUIKit.KYCRouting = resolve(), alertViewPresenter: AlertViewPresenterAPI = resolve(), coincore: CoincoreAPI = resolve(), topMostViewControllerProvider: TopMostViewControllerProviding = resolve(), loadingViewPresenter: LoadingViewPresenting = LoadingViewPresenter(), transactionFlowBuilder: TransactionFlowBuildable = TransactionFlowBuilder(), buyFlowBuilder: BuyFlowBuildable = BuyFlowBuilder(analyticsRecorder: resolve()), sellFlowBuilder: SellFlowBuildable = SellFlowBuilder(), signFlowBuilder: SignFlowBuildable = SignFlowBuilder(), sendFlowBuilder: SendRootBuildable = SendRootBuilder(), interestFlowBuilder: InterestTransactionBuilder = InterestTransactionBuilder(), withdrawFlowBuilder: WithdrawRootBuildable = WithdrawRootBuilder(), depositFlowBuilder: DepositRootBuildable = DepositRootBuilder(), receiveCoordinator: ReceiveCoordinator = ReceiveCoordinator(), fiatCurrencyService: FiatCurrencySettingsServiceAPI = resolve(), kyc: FeatureKYCUI.Routing = resolve(), productsService: FeatureProductsDomain.ProductsServiceAPI = resolve() ) { self.app = app self.analyticsRecorder = analyticsRecorder self.featureFlagsService = featureFlagsService self.eligibilityService = eligibilityService self.userActionService = userActionService self.kycRouter = kycRouter self.topMostViewControllerProvider = topMostViewControllerProvider self.alertViewPresenter = alertViewPresenter self.coincore = coincore self.loadingViewPresenter = loadingViewPresenter self.pendingOrdersService = pendingOrdersService self.transactionFlowBuilder = transactionFlowBuilder self.buyFlowBuilder = buyFlowBuilder self.sellFlowBuilder = sellFlowBuilder self.signFlowBuilder = signFlowBuilder self.sendFlowBuilder = sendFlowBuilder self.interestFlowBuilder = interestFlowBuilder self.withdrawFlowBuilder = withdrawFlowBuilder self.depositFlowBuilder = depositFlowBuilder self.receiveCoordinator = receiveCoordinator self.fiatCurrencyService = fiatCurrencyService self.kyc = kyc self.productsService = productsService } func presentTransactionFlow( to action: TransactionFlowAction ) -> AnyPublisher<TransactionFlowResult, Never> { guard let viewController = topMostViewControllerProvider.topMostViewController else { fatalError("Expected a UIViewController") } return presentTransactionFlow(to: action, from: viewController) } func presentTransactionFlow( to action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { isUserEligible(for: action) .handleEvents( receiveSubscription: { [app] _ in app.state.transaction { state in state.set(blockchain.ux.transaction.id, to: action.asset.rawValue) } app.post(event: blockchain.ux.transaction.event.will.start) } ) .receive(on: DispatchQueue.main) .flatMap { [weak self] ineligibility -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .empty() } guard let ineligibility = ineligibility else { // There is no 'ineligibility' reason, continue. return self.continuePresentingTransactionFlow( to: action, from: presenter, showKycQuestions: action.isCustodial ) } // There is a 'ineligibility' reason. // Show KYC flow or 'blocked' flow. switch ineligibility.type { case .insufficientTier: let tier: KYC.Tier = ineligibility.reason == .tier2Required ? .tier2 : .tier1 return self.presentKYCUpgradeFlow(from: presenter, requiredTier: tier) default: guard let presenter = self.topMostViewControllerProvider.topMostViewController else { return .just(.abandoned) } let viewController = self.buildIneligibilityErrorView(ineligibility, from: presenter) presenter.present(viewController, animated: true, completion: nil) return .just(.abandoned) } } .eraseToAnyPublisher() } private func isUserEligible( for action: TransactionFlowAction ) -> AnyPublisher<ProductIneligibility?, Never> { guard action.isCustodial, let productId = action.toProductIdentifier else { return .just(nil) } return productsService .fetchProducts() .replaceError(with: []) .flatMap { products -> AnyPublisher<ProductIneligibility?, Never> in let product: ProductValue? = products.first { $0.id == productId } return .just(product?.reasonNotEligible) } .eraseToAnyPublisher() } private func presentKYCUpgradeFlow( from presenter: UIViewController, requiredTier: KYC.Tier? ) -> AnyPublisher<TransactionFlowResult, Never> { kycRouter.presentKYCUpgradeFlow(from: presenter) .map { result in switch result { case .abandoned: return .abandoned case .completed, .skipped: return .completed } } .eraseToAnyPublisher() } /// Call this only after having checked that users can perform the requested action private func continuePresentingTransactionFlow( to action: TransactionFlowAction, from presenter: UIViewController, showKycQuestions: Bool ) -> AnyPublisher<TransactionFlowResult, Never> { do { let isKycQuestionsEmpty: Bool = try app.state.get(blockchain.ux.kyc.extra.questions.form.is.empty) if showKycQuestions, !isKycQuestionsEmpty { return presentKycQuestionsIfNeeded( to: action, from: presenter ) } } catch { /* ignore */ } switch action { case .buy: return presentTradingCurrencySelectorIfNeeded(from: presenter) .flatMap { result -> AnyPublisher<TransactionFlowResult, Never> in guard result == .completed else { return .just(result) } return self.presentBuyTransactionFlow(to: action, from: presenter) } .eraseToAnyPublisher() case .sell, .order, .swap, .interestTransfer, .interestWithdraw, .sign, .send, .receive, .withdraw, .deposit: return presentNewTransactionFlow(action, from: presenter) } } private func presentKycQuestionsIfNeeded( to action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { let subject = PassthroughSubject<TransactionFlowResult, Never>() kyc.routeToKYC( from: presenter, requiredTier: .tier1, flowCompletion: { [weak self] result in guard let self = self else { return } switch result { case .abandoned: subject.send(.abandoned) case .completed, .skipped: self.continuePresentingTransactionFlow( to: action, from: presenter, showKycQuestions: false // if questions were skipped ) .sink(receiveValue: subject.send) .store(in: &self.cancellables) } } ) return subject.eraseToAnyPublisher() } private func presentBuyTransactionFlow( to action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { eligibilityService.eligibility() .receive(on: DispatchQueue.main) .handleLoaderForLifecycle(loader: loadingViewPresenter) .flatMap { [weak self] eligibility -> AnyPublisher<TransactionFlowResult, Error> in guard let self = self else { return .empty() } if eligibility.simpleBuyPendingTradesEligible { return self.pendingOrdersService.pendingOrderDetails .receive(on: DispatchQueue.main) .flatMap { [weak self] orders -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .empty() } let isAwaitingAction = orders.filter(\.isAwaitingAction) if let order = isAwaitingAction.first { return self.presentNewTransactionFlow(action, from: presenter) .zip( self.pendingOrdersService.cancel(order) .receive(on: DispatchQueue.main) .ignoreFailure() ) .map(\.0) .eraseToAnyPublisher() } else { return self.presentNewTransactionFlow(action, from: presenter) } } .eraseError() .eraseToAnyPublisher() } else { return self.presentTooManyPendingOrders( count: eligibility.maxPendingDepositSimpleBuyTrades, from: presenter ) .setFailureType(to: Error.self) .eraseToAnyPublisher() } } .catch { [weak self] error -> AnyPublisher<TransactionFlowResult, Never> in guard let self = self else { return .empty() } return self.presentError(error: error, action: action, from: presenter) } .eraseToAnyPublisher() } } extension TransactionsRouter { // since we're not attaching a RIB to a RootRouter we have to retain the router and manually activate it private func mimicRIBAttachment(router: RIBs.Routing) { currentRIBRouter?.interactable.deactivate() currentRIBRouter = router router.load() router.interactable.activate() } } extension TransactionsRouter { // swiftlint:disable:next cyclomatic_complexity private func presentNewTransactionFlow( _ action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { switch action { case .interestWithdraw(let cryptoAccount): let listener = InterestTransactionInteractor(transactionType: .withdraw(cryptoAccount)) let router = interestFlowBuilder.buildWithInteractor(listener) router.start() mimicRIBAttachment(router: router) return listener.publisher case .interestTransfer(let cryptoAccount): let listener = InterestTransactionInteractor(transactionType: .transfer(cryptoAccount)) let router = interestFlowBuilder.buildWithInteractor(listener) router.start() mimicRIBAttachment(router: router) return listener.publisher case .buy(let cryptoAccount): let listener = BuyFlowListener( kycRouter: kycRouter, alertViewPresenter: alertViewPresenter ) let interactor = BuyFlowInteractor() let router = buyFlowBuilder.build(with: listener, interactor: interactor) router.start(with: cryptoAccount, order: nil, from: presenter) mimicRIBAttachment(router: router) return listener.publisher case .order(let order): let listener = BuyFlowListener( kycRouter: kycRouter, alertViewPresenter: alertViewPresenter ) let interactor = BuyFlowInteractor() let router = buyFlowBuilder.build(with: listener, interactor: interactor) router.start(with: nil, order: order, from: presenter) mimicRIBAttachment(router: router) return listener.publisher case .sell(let cryptoAccount): let listener = SellFlowListener() let interactor = SellFlowInteractor() let router = SellFlowBuilder().build(with: listener, interactor: interactor) startSellRouter(router, cryptoAccount: cryptoAccount, from: presenter) mimicRIBAttachment(router: router) return listener.publisher case .swap(let cryptoAccount): let listener = SwapRootInteractor() let router = transactionFlowBuilder.build( withListener: listener, action: .swap, sourceAccount: cryptoAccount, target: nil ) presenter.present(router.viewControllable.uiviewController, animated: true) mimicRIBAttachment(router: router) return .empty() case .sign(let sourceAccount, let destination): let listener = SignFlowListener() let interactor = SignFlowInteractor() let router = signFlowBuilder.build(with: listener, interactor: interactor) router.start(sourceAccount: sourceAccount, destination: destination, presenter: presenter) mimicRIBAttachment(router: router) return listener.publisher case .send(let fromAccount, let target): let router = sendFlowBuilder.build() switch (fromAccount, target) { case (.some(let fromAccount), let target): router.routeToSend(sourceAccount: fromAccount, destination: target) case (nil, _): router.routeToSendLanding(navigationBarHidden: true) } presenter.present(router.viewControllable.uiviewController, animated: true) mimicRIBAttachment(router: router) return .empty() case .receive(let account): presenter.present(receiveCoordinator.builder.receive(), animated: true) if let account = account { receiveCoordinator.routeToReceive(sourceAccount: account) } return .empty() case .withdraw(let fiatAccount): let router = withdrawFlowBuilder.build(sourceAccount: fiatAccount) router.start() mimicRIBAttachment(router: router) return .empty() case .deposit(let fiatAccount): let router = depositFlowBuilder.build(with: fiatAccount) router.start() mimicRIBAttachment(router: router) return .empty() } } private func startSellRouter( _ router: SellFlowRouting, cryptoAccount: CryptoAccount?, from presenter: UIViewController ) { @Sendable func startRouterOnMainThread(target: TransactionTarget?) async { await MainActor.run { router.start(with: cryptoAccount, target: target, from: presenter) } } Task(priority: .userInitiated) { do { let currency: FiatCurrency = try await app.get(blockchain.user.currency.preferred.fiat.trading.currency) let account = try await coincore .account(where: { $0.currencyType == currency }) .values .next() .first as? TransactionTarget await startRouterOnMainThread(target: account) } catch { await startRouterOnMainThread(target: nil) } } } private func presentTooManyPendingOrders( count: Int, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { let subject = PassthroughSubject<TransactionFlowResult, Never>() func dismiss() { presenter.dismiss(animated: true) { subject.send(.abandoned) } } presenter.present( PrimaryNavigationView { TooManyPendingOrdersView( count: count, viewActivityAction: { [tabSwapping] in tabSwapping.switchToActivity() dismiss() }, okAction: dismiss ) .whiteNavigationBarStyle() .trailingNavigationButton(.close, action: dismiss) } ) return subject.eraseToAnyPublisher() } /// Checks if the user has a valid trading currency set. If not, it presents a modal asking the user to select one. /// /// If presented, the modal allows the user to select a trading fiat currency to be the base of transactions. This currency can only be one of the currencies supported for any of our official trading pairs. /// At the time of this writing, the supported trading currencies are USD, EUR, and GBP. /// /// The trading currency should be used to define the fiat inputs in the Enter Amount Screen and to show fiat values in the transaction flow. /// /// - Note: Checking for a trading currency is only required for the Buy flow at this time. However, it may be required for other flows as well in the future. /// /// - Returns: A `Publisher` whose result is `TransactionFlowResult.completed` if the user had or has successfully selected a trading currency. /// Otherwise, it returns `TransactionFlowResult.abandoned`. In this case, the user should be prevented from entering the desired transaction flow. private func presentTradingCurrencySelectorIfNeeded( from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { let viewControllerGenerator = viewControllerForSelectingTradingCurrency // 1. Fetch Trading Currency and supported trading currencies return fiatCurrencyService.tradingCurrency .zip(fiatCurrencyService.supportedFiatCurrencies) .receive(on: DispatchQueue.main) .flatMap { tradingCurrency, supportedTradingCurrencies -> AnyPublisher<TransactionFlowResult, Never> in // 2a. If trading currency matches one of supported currencies, return .completed guard !supportedTradingCurrencies.contains(tradingCurrency) else { return .just(.completed) } // 2b. Otherwise, present new screen, with close => .abandoned, selectCurrency => settingsService.setTradingCurrency let subject = PassthroughSubject<TransactionFlowResult, Never>() let sortedCurrencies = Array(supportedTradingCurrencies) .sorted(by: { $0.displayCode < $1.displayCode }) let viewController = viewControllerGenerator(tradingCurrency, sortedCurrencies) { result in presenter.dismiss(animated: true) { subject.send(result) subject.send(completion: .finished) } } presenter.present(viewController, animated: true, completion: nil) return subject.eraseToAnyPublisher() } .eraseToAnyPublisher() } private func viewControllerForSelectingTradingCurrency( displayCurrency: FiatCurrency, currencies: [FiatCurrency], handler: @escaping (TransactionFlowResult) -> Void ) -> UIViewController { UIHostingController( rootView: TradingCurrencySelector( store: .init( initialState: .init( displayCurrency: displayCurrency, currencies: currencies ), reducer: TradingCurrency.reducer, environment: .init( closeHandler: { handler(.abandoned) }, selectionHandler: { [weak self] selectedCurrency in guard let self = self else { return } self.fiatCurrencyService .update(tradingCurrency: selectedCurrency, context: .simpleBuy) .map(TransactionFlowResult.completed) .receive(on: DispatchQueue.main) .handleLoaderForLifecycle(loader: self.loadingViewPresenter) .sink(receiveValue: handler) .store(in: &self.cancellables) }, analyticsRecorder: analyticsRecorder ) ) ) ) } private func presentError( error: Error, action: TransactionFlowAction, from presenter: UIViewController ) -> AnyPublisher<TransactionFlowResult, Never> { let subject = PassthroughSubject<TransactionFlowResult, Never>() func dismiss() { presenter.dismiss(animated: true) { subject.send(.abandoned) } } let state = TransactionErrorState.fatalError(.generic(error)) presenter.present( NavigationView { ErrorView( ux: state.ux(action: action.asset), fallback: { Icon.globe.accentColor(.semantic.primary) }, dismiss: dismiss ) } .app(app) ) return subject.eraseToAnyPublisher() } private func buildIneligibilityErrorView( _ reason: ProductIneligibility?, from presenter: UIViewController ) -> UIViewController { let error = UX.Error( source: nil, title: LocalizationConstants.MajorProductBlocked.title, message: reason?.message ?? LocalizationConstants.MajorProductBlocked.defaultMessage, actions: { var actions: [UX.Action] = .default if let learnMoreUrl = reason?.learnMoreUrl { let newAction = UX.Action( title: LocalizationConstants.MajorProductBlocked.ctaButtonLearnMore, url: learnMoreUrl ) actions.append(newAction) } return actions }() ) return UIHostingController( rootView: ErrorView( ux: error, dismiss: { presenter.dismiss(animated: true) } ).app(app) ) } } extension TransactionFlowAction { /// https://www.notion.so/blockchaincom/Russia-Sanctions-10k-euro-limit-5th-EC-Sanctions-d07a493c9b014a25a83986f390e0ac35 fileprivate var toProductIdentifier: ProductIdentifier? { switch self { case .buy: return .buy case .sell: return .sell case .swap: return .swap case .deposit: return .depositFiat case .withdraw: return .withdrawFiat case .receive: return .depositCrypto case .send: return .withdrawCrypto case .interestTransfer: return .depositInterest case .interestWithdraw: return .withdrawCrypto default: return nil } } }
lgpl-3.0
huonw/swift
validation-test/stdlib/Collection/DefaultedRandomAccessCollection.swift
17
1164
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("Collection") // Test collections using value types as elements. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRandomAccessCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedRandomAccessCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedRandomAccessCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) } runAllTests()
apache-2.0
michaelhenry/card.io-iOS-SDK
SampleApp-Swift/SampleApp-Swift/ViewController.swift
2
1488
// // ViewController.swift // SampleApp-Swift // // Copyright (c) 2014 PayPal. All rights reserved. // import UIKit class ViewController: UIViewController, CardIOPaymentViewControllerDelegate { @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. CardIOUtilities.preload() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func scanCard(sender: AnyObject) { var cardIOVC = CardIOPaymentViewController(paymentDelegate: self) cardIOVC.modalPresentationStyle = .FormSheet presentViewController(cardIOVC, animated: true, completion: nil) } func userDidCancelPaymentViewController(paymentViewController: CardIOPaymentViewController!) { resultLabel.text = "user canceled" paymentViewController?.dismissViewControllerAnimated(true, completion: nil) } func userDidProvideCreditCardInfo(cardInfo: CardIOCreditCardInfo!, inPaymentViewController paymentViewController: CardIOPaymentViewController!) { if let info = cardInfo { let str = NSString(format: "Received card info.\n Number: %@\n expiry: %02lu/%lu\n cvv: %@.", info.redactedCardNumber, info.expiryMonth, info.expiryYear, info.cvv) resultLabel.text = str } paymentViewController?.dismissViewControllerAnimated(true, completion: nil) } }
mit
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ResponseDetective/ResponseDetective/Sources/ResponseDetective.swift
1
5129
// // ResponseDetective.swift // // Copyright © 2016-2017 Netguru Sp. z o.o. All rights reserved. // Licensed under the MIT License. // import Foundation /// ResponseDetective configuration cluster class that defines the behavior /// of request interception and logging. @objc(RDTResponseDetective) public final class ResponseDetective: NSObject { // MARK: Properties /// An output facility for reporting requests, responses and errors. public static var outputFacility: OutputFacility = ConsoleOutputFacility() /// A class of the URL protocol used to intercept requests. public static let URLProtocolClass: Foundation.URLProtocol.Type = URLProtocol.self /// A storage for request predicates. private static var requestPredicates: [NSPredicate] = [] /// Body deserializers stored by a supported content type. private static var customBodyDeserializers: [String: BodyDeserializer] = [:] /// Default body deserializers provided by ResponseDetective. private static let defaultBodyDeserializers: [String: BodyDeserializer] = [ "*/json": JSONBodyDeserializer(), "*/xml": XMLBodyDeserializer(), "*/html": HTMLBodyDeserializer(), "*/x-www-form-urlencoded": URLEncodedBodyDeserializer(), "image/*": ImageBodyDeserializer(), "text/*": PlaintextBodyDeserializer(), ] // MARK: Configuration /// Resets the ResponseDetective mutable state. public static func reset() { outputFacility = ConsoleOutputFacility() requestPredicates = [] customBodyDeserializers = [:] } /// Enables ResponseDetective in an URL session configuration. /// /// - Parameters: /// - configuration: The URL session configuration to enable the /// session in. @objc(enableInConfiguration:) public static func enable(inConfiguration configuration: URLSessionConfiguration) { configuration.protocolClasses?.insert(URLProtocolClass, at: 0) } /// Ignores requests matching the given predicate. The predicate will be /// evaluated with an instance of NSURLRequest. /// /// - Parameters: /// - predicate: A predicate for matching a request. If the /// predicate evaluates to `false`, the request is not intercepted. @objc(ignoreRequestsMatchingPredicate:) public static func ignoreRequests(matchingPredicate predicate: NSPredicate) { requestPredicates.append(predicate) } /// Checks whether the given request can be incercepted. /// /// - Parameters: /// - request: The request to check. /// /// - Returns: `true` if request can be intercepted, `false` otherwise. @objc(canInterceptRequest:) public static func canIncercept(request: URLRequest) -> Bool { return requestPredicates.reduce(true) { return $0 && !$1.evaluate(with: request) } } // MARK: Deserialization /// Registers a body deserializer. /// /// - Parameters: /// - deserializer: The deserializer to register. /// - contentType: The supported content type. @objc(registerBodyDeserializer:forContentType:) public static func registerBodyDeserializer(_ deserializer: BodyDeserializer, forContentType contentType: String) { customBodyDeserializers[contentType] = deserializer } /// Registers a body deserializer. /// /// - Parameters: /// - deserializer: The deserializer to register. /// - contentTypes: The supported content types. @objc(registerBodyDeserializer:forContentTypes:) public static func registerBodyDeserializer(_ deserializer: BodyDeserializer, forContentTypes contentTypes: [String]) { for contentType in contentTypes { registerBodyDeserializer(deserializer, forContentType: contentType) } } /// Deserializes a HTTP body into a string. /// /// - Parameters: /// - body: The body to deserialize. /// - contentType: The content type of the body. /// /// - Returns: A deserialized body or `nil` if no serializer is capable of /// deserializing body with the given content type. @objc(deserializeBody:contentType:) public static func deserialize(body: Data, contentType: String) -> String? { if let deserializer = findBodyDeserializer(forContentType: contentType) { return deserializer.deserialize(body: body) } else { return nil } } /// Finds a body deserializer by pattern. /// /// - Parameters: /// - contentType: The content type to find a deserializer for. /// /// - Returns: A body deserializer for given `contentType` or `nil`. @objc(findBodyDeserializerForContentType:) private static func findBodyDeserializer(forContentType contentType: String) -> BodyDeserializer? { guard let trimmedContentType = contentType.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) else { return nil } for (pattern, deserializer) in defaultBodyDeserializers.appending(elementsOf: customBodyDeserializers) { let patternParts = pattern.components(separatedBy: "/") let actualParts = trimmedContentType.components(separatedBy: "/") guard patternParts.count == 2 && actualParts.count == 2 else { return nil } if ["*" , actualParts[0]].contains(patternParts[0]) && ["*" , actualParts[1]].contains(patternParts[1]) { return deserializer } } return nil } }
mit
konanxu/WeiBoWithSwift
WeiBo/WeiBo/Classes/Home/View/StatusPictureView.swift
1
3958
// // StatusPictureView.swift // WeiBo // // Created by Konan on 16/3/22. // Copyright © 2016年 Konan. All rights reserved. // import UIKit import SDWebImage class StatusPictureView: UICollectionView { var status:Status? { didSet{ reloadData() } } private var pictureViewLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout() init() { super.init(frame: CGRectZero, collectionViewLayout: pictureViewLayout) //注册cell registerClass(PictureViewCell.self, forCellWithReuseIdentifier: collectionCellIdentifier) delegate = self dataSource = self //设置cell之间的间隙 pictureViewLayout.minimumInteritemSpacing = 10 pictureViewLayout.minimumLineSpacing = 10 //设置配图颜色 backgroundColor = UIColor.redColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func calculateImageSize() ->CGSize{ //1.取出配图数量 let count = status?.storedPicURLS?.count //2.没有配图 if count == 0 || count == nil{ return CGSizeZero } //3.配图为一张 print("count:\(count)") if count == 1{ // let key = status?.storedPicURLS!.first?.absoluteString let key = status?.bmiddle_picUrl?.absoluteString print("key:" + key!) let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) let size = CGSizeMake(image.size.width * 0.5, image.size.height * 0.5) return size } //4.配图为4张 let width = 90 let margin = 10 if count == 4{ let viewWidth = CGFloat(width * 2 + margin) pictureViewLayout.itemSize = CGSize(width: width, height: width) return CGSize(width: viewWidth, height: viewWidth) } //5.配图为其他张数 let colNumber = 3 let rowNumber = (count! - 1) / 3 + 1 let viewWidth = colNumber * width + (colNumber - 1) * margin let viewHeight = rowNumber * width + (rowNumber - 1) * margin // pictureViewLayout.itemSize = CGSize(width: width, height: width) return CGSize(width: viewWidth, height: viewHeight) } } extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return status?.storedPicURLS?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellIdentifier, forIndexPath: indexPath) as! PictureViewCell cell.imageUrl = status?.storedPicURLS![indexPath.row] cell.backgroundColor = UIColor.yellowColor() return cell } } class PictureViewCell:UICollectionViewCell{ var imageUrl:NSURL? { didSet{ pictureImageView.sd_setImageWithURL(imageUrl) } } override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpUI(){ self.addSubview(pictureImageView) pictureImageView.snp_makeConstraints { (make) -> Void in make.size.equalTo(pictureImageView.superview!) make.center.equalTo(pictureImageView.superview!) } } private lazy var pictureImageView:UIImageView = { let view = UIImageView() return view }() }
mit
otakisan/SmartToDo
SmartToDo/Views/Cells/ToDoEditorDueDateTableViewCell.swift
1
1222
// // ToDoEditorDueDateTableViewCell.swift // SmartToDo // // Created by Takashi Ikeda on 2014/10/26. // Copyright (c) 2014年 ti. All rights reserved. // import UIKit class ToDoEditorDueDateTableViewCell: ToDoEditorDateBaseTableViewCell { @IBOutlet weak var dueDateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func setValueForDate(datePicker: UIDatePicker) { self.dueDateLabel.text = self.stringFromDate(datePicker.date) } override func valueOfCell() -> AnyObject? { return self.dateFromString(self.dueDateLabel.text!) } override func setDateStringOfCell(value: String) { self.dueDateLabel.text = value } override func bindingString() -> String { return "dueDate" } override func detailViewInitValue() -> AnyObject? { return self.dateFromString(self.dueDateLabel.text ?? "") ?? NSDate() } override var readOnly : Bool { get{ return true } } }
mit
yotao/YunkuSwiftSDKTEST
YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/CRC32.swift
1
1124
// // Created by Brandon on 2017/8/4. // Copyright (c) 2017 goukuai. All rights reserved. // import Foundation final class CRC32 { static let MPEG2:CRC32 = CRC32(polynomial: 0x04c11db7) let table:[UInt32] init(polynomial:UInt32) { var table:[UInt32] = [UInt32](repeating: 0x00000000, count: 256) for i in 0..<table.count { var crc:UInt32 = UInt32(i) << 24 for _ in 0..<8 { crc = (crc << 1) ^ ((crc & 0x80000000) == 0x80000000 ? polynomial : 0) } table[i] = crc } self.table = table } func calculate(_ data:Data) -> UInt32 { return calculate(data, seed: nil) } func calculate(_ data:Data, seed:UInt32?) -> UInt32 { var crc:UInt32 = seed ?? 0xffffffff for i in 0..<data.count { crc = (crc << 8) ^ table[Int((crc >> 24) ^ (UInt32(data[i]) & 0xff) & 0xff)] } return crc } } extension CRC32: CustomStringConvertible { // MARK: CustomStringConvertible var description:String { return Mirror(reflecting: self).description } }
mit
santidediego/Learning-Swif-on-my-own
My first playground.playground/Contents.swift
1
1800
//: Playground - noun: a place where people can play import Cocoa //String var var str = "Hello, world" let number_five : Int = 5 //Problem trying to change the value of number_five because it´s a constant //number_five=4 str = str + " i´m fine" //If you want to use a variable you must write \() str = str + " \(number_five)" //Arrays var my_array = [1,2,3,4,5,6] my_array.count for var i=1;i<5;i++ { my_array.append(0) } my_array for index in 1...4 { my_array.removeLast() } my_array if my_array[4]==5 { str="The fourth element is \(my_array[4])" } while my_array[0] != 6 { my_array[0]++ } my_array //Optionals //If we write ? we have a nil variable var number: Int? number number=4 var str2="The number is \(number)" //We have to write ! in order to show the variable, because it´s an optional str2="The number is \(number!)" //Classes and Structs class vehicle { var identificate: Int var model: String var km: Int=0 init (identificate: Int, model: String) { self.identificate=identificate self.model=model } } //Now we can define: class car: vehicle { let seats: Int=4 //It´s the same init because seats is a constant override init(identificate: Int, model: String) { super.init(identificate: identificate, model: model) } } class ship: vehicle { var seats: Int init(identificate: Int, model: String, seats: Int) { self.seats=seats super.init(identificate: identificate, model: model) } } //Protocols protocol fix { var damaged: Bool {get} } class plane: vehicle, fix { var damaged : Bool { return super.km==100000 } //In this case, the vehicle is damaged if it has 100000 km let seats: Int=100 }
mpl-2.0
vmachiel/swift
Concentration/Concentration/Concentration.swift
1
5660
// // Concentration.swift // Concentration // // Created by Machiel van Dorst on 24-03-18. // Copyright © 2018 vmachiel. All rights reserved. // import Foundation // The brain of the concentration game. Part of model in MVC. Name the file after the main class // Think about what your public API should be like: get into the public/private design. // Three states: none, one, or two cards face up (see methods) struct Concentration { // MARK: Properties // Flipcout: how many cards you've flipped, and score. var flipCount = 0 var score = 0 // The cards that are availible (defined in Card file). Inited as empty array. // Private set, because a UI needs to see it, but don't set. private(set) var cards = [Card]() // variable that keeps track of the card that's currently faceup if one is faceup ready to be checked // for a match against a newly chosen card. Optional: of none, or two cards are faceup, set to nil // Make it a computed property: if get, look at all cards. If only one faceup, return that, else return nil // if set, pass an index and set the value to that. Turn that card up, all other // down. Use newValue (also the default local value) for the new value to use // in the compute. // Private implemtation. private var indexOfOneAndOnlyFaceUpCard: Int? { // Use a closure to get all the indexes of faceup cards. If there's one, one is faceup // and you return that. If not, return nil get { let faceUpCardIndexes = cards.indices.filter{ cards[$0].isFaceUp } // trailing closure syntax! return faceUpCardIndexes.count == 1 ? faceUpCardIndexes.first : nil } // Again if a one and only face up index is set, set all the faceUp properties to false EXCEPT the one // corresponding to the index. set(newValue) { for index in cards.indices { cards[index].isFaceUp = (index == newValue) // true for only the right index, others will be false } } } // Init for the Concentration class. Make a card with an ID and add two of them to cards array. // Do this for the number of pairs you want. This will create two identical cards (same emoji in the // view, same identifier here). Set flipcount and score to 0, and suffle the cards init(numberOfPairsOfCards: Int) { for _ in 0..<numberOfPairsOfCards { let card = Card() // The unique ID is made here! See Card.swift cards.append(card) cards.append(card) // You do this because Card is a struct, and thus a seperate copy is made (same id). } flipCount = 0 score = 0 // Shuffle cards. Take random index using the Int extention for _ in 1...100 { for index in cards.indices { let randomIndex = cards.count.arc4random let tempCard = cards[index] cards[index] = cards [randomIndex] cards[randomIndex] = tempCard } } } // MARK: Methods // Main public function: the method that gets called when a user picks a card. // Three options 1: no cards faceup: just flip the card // 2: two cards face up (matching or not): face them both down and a new one up, // starting a new match // 3: one card face up: face up the new card and check if they match mutating func chooseCard(at index: Int) { // Demo assert: check if the index passed is actually one of the indexes of the cards assert(cards.indices.contains(index), "Concentration.chooseCard(at \(index): index not in cards") // Only act if card hasn't matched yet. if !cards[index].isMatched{ flipCount += 1 // Case if there is already one matched, not just one card/chose the same card again // (if you did this, it ignores and nothing happens and you need to tap another card) if let matchIndex = indexOfOneAndOnlyFaceUpCard, matchIndex != index { // match? set isMatched and update score. (no need to update seenBefore. if cards[matchIndex].identifier == cards[index].identifier { cards[matchIndex].isMatched = true cards[index].isMatched = true score += 2 // not a match? Check if seen before and lower score. Set seen before for both } else { if cards[matchIndex].seenBefore || cards[index].seenBefore { score -= 1 } cards[matchIndex].seenBefore = true cards[index].seenBefore = true } // Now the check is done, face up the card you just chose (so the controller can update view) // the indexOfOneAndOnlyFaceUpCard DOESN'T need to be set to nil, because every time it is // referenced, the property's value is computed based on the current state. cards[index].isFaceUp = true // none or two cards face up so can't match, so set the chosen index as // indexOfOneAndOnlyFaceUpCard. The isFaceUp state of all the cards is updated // because of the set method of indexOfOneAndOnlyFaceUpCard (computed property) } else { indexOfOneAndOnlyFaceUpCard = index } } } }
mit
edmw/Volumio_ios
Pods/Eureka/Source/Core/BaseRow.swift
4
9534
// BaseRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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 open class BaseRow : BaseRowType { var callbackOnChange: (()-> Void)? var callbackCellUpdate: (()-> Void)? var callbackCellSetup: Any? var callbackCellOnSelection: (()-> Void)? var callbackOnExpandInlineRow: Any? var callbackOnCollapseInlineRow: Any? var callbackOnCellHighlightChanged: (()-> Void)? var callbackOnRowValidationChanged: (() -> Void)? var _inlineRow: BaseRow? public var validationOptions: ValidationOptions = .validatesOnBlur // validation state public internal(set) var validationErrors = [ValidationError]() { didSet { guard validationErrors != oldValue else { return } RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self) callbackOnRowValidationChanged?() } } public internal(set) var wasBlurred = false public internal(set) var wasChanged = false public var isValid: Bool { return validationErrors.isEmpty } public var isHighlighted: Bool = false /// The title will be displayed in the textLabel of the row. public var title: String? /// Parameter used when creating the cell for this row. public var cellStyle = UITableViewCellStyle.value1 /// String that uniquely identifies a row. Must be unique among rows and sections. public var tag: String? /// The untyped cell associated to this row. public var baseCell: BaseCell! { return nil } /// The untyped value of this row. public var baseValue: Any? { set {} get { return nil } } public func validate() -> [ValidationError] { return [] } public static var estimatedRowHeight: CGFloat = 44.0 /// Condition that determines if the row should be disabled or not. public var disabled : Condition? { willSet { removeFromDisabledRowObservers() } didSet { addToDisabledRowObservers() } } /// Condition that determines if the row should be hidden or not. public var hidden : Condition? { willSet { removeFromHiddenRowObservers() } didSet { addToHiddenRowObservers() } } /// Returns if this row is currently disabled or not public var isDisabled : Bool { return disabledCache } /// Returns if this row is currently hidden or not public var isHidden : Bool { return hiddenCache } /// The section to which this row belongs. public weak var section: Section? public required init(tag: String? = nil){ self.tag = tag } /** Method that reloads the cell */ open func updateCell() {} /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ open func didSelect() {} open func prepare(for segue: UIStoryboardSegue) {} /** Returns the IndexPath where this row is in the current form. */ public final var indexPath: IndexPath? { guard let sectionIndex = section?.index, let rowIndex = section?.index(of: self) else { return nil } return IndexPath(row: rowIndex, section: sectionIndex) } var hiddenCache = false var disabledCache = false { willSet { if newValue == true && disabledCache == false { baseCell.cellResignFirstResponder() } } } } extension BaseRow { /** Evaluates if the row should be hidden or not and updates the form accordingly */ public final func evaluateHidden() { guard let h = hidden, let form = section?.form else { return } switch h { case .function(_ , let callback): hiddenCache = callback(form) case .predicate(let predicate): hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } if hiddenCache { section?.hide(row: self) } else{ section?.show(row: self) } } /** Evaluates if the row should be disabled or not and updates it accordingly */ public final func evaluateDisabled() { guard let d = disabled, let form = section?.form else { return } switch d { case .function(_ , let callback): disabledCache = callback(form) case .predicate(let predicate): disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } updateCell() } final func wasAddedTo(section: Section) { self.section = section if let t = tag { assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)") self.section?.form?.rowsByTag[t] = self self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull() } addToRowObservers() evaluateHidden() evaluateDisabled() } final func addToHiddenRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden) case .predicate(let predicate): section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden) } } final func addToDisabledRowObservers() { guard let d = disabled else { return } switch d { case .function(let tags, _): section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled) case .predicate(let predicate): section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled) } } final func addToRowObservers(){ addToHiddenRowObservers() addToDisabledRowObservers() } final func willBeRemovedFromForm(){ (self as? BaseInlineRowType)?.collapseInlineRow() if let t = tag { section?.form?.rowsByTag[t] = nil section?.form?.tagToValues[t] = nil } removeFromRowObservers() } final func removeFromHiddenRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden) case .predicate(let predicate): section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden) } } final func removeFromDisabledRowObservers() { guard let d = disabled else { return } switch d { case .function(let tags, _): section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled) case .predicate(let predicate): section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled) } } final func removeFromRowObservers(){ removeFromHiddenRowObservers() removeFromDisabledRowObservers() } } extension BaseRow: Equatable, Hidable, Disableable {} extension BaseRow { public func reload(with rowAnimation: UITableViewRowAnimation = .none) { guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return } tableView.reloadRows(at: [indexPath], with: rowAnimation) } public func deselect(animated: Bool = true) { guard let indexPath = indexPath, let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.deselectRow(at: indexPath, animated: animated) } public func select(animated: Bool = false) { guard let indexPath = indexPath, let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none) } } public func ==(lhs: BaseRow, rhs: BaseRow) -> Bool{ return lhs === rhs }
gpl-3.0
stripe/stripe-ios
Stripe/STPPaymentConfiguration.swift
1
11345
// // STPPaymentConfiguration.swift // StripeiOS // // Created by Jack Flintermann on 5/18/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeCore /// An `STPPaymentConfiguration` represents all the options you can set or change /// around a payment. /// You provide an `STPPaymentConfiguration` object to your `STPPaymentContext` /// when making a charge. The configuration generally has settings that /// will not change from payment to payment and thus is reusable, while the context /// is specific to a single particular payment instance. public class STPPaymentConfiguration: NSObject, NSCopying { /// This is a convenience singleton configuration that uses the default values for /// every property @objc(sharedConfiguration) public static var shared = STPPaymentConfiguration() private var _applePayEnabled = true /// The user is allowed to pay with Apple Pay if it's configured and available on their device. @objc public var applePayEnabled: Bool { get { return appleMerchantIdentifier != nil && _applePayEnabled && StripeAPI.deviceSupportsApplePay() } set { _applePayEnabled = newValue } } /// The user is allowed to pay with FPX. @objc public var fpxEnabled = false /// The billing address fields the user must fill out when prompted for their /// payment details. These fields will all be present on the returned PaymentMethod from /// Stripe. /// The default value is `STPBillingAddressFieldsPostalCode`. /// - seealso: https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details @objc public var requiredBillingAddressFields = STPBillingAddressFields.postalCode /// The shipping address fields the user must fill out when prompted for their /// shipping info. Set to nil if shipping address is not required. /// The default value is nil. @objc public var requiredShippingAddressFields: Set<STPContactField>? /// Whether the user should be prompted to verify prefilled shipping information. /// The default value is YES. @objc public var verifyPrefilledShippingAddress = true /// The type of shipping for this purchase. This property sets the labels displayed /// when the user is prompted for shipping info, and whether they should also be /// asked to select a shipping method. /// The default value is STPShippingTypeShipping. @objc public var shippingType = STPShippingType.shipping /// The set of countries supported when entering an address. This property accepts /// a set of ISO 2-character country codes. /// The default value is all known countries. Setting this property will limit /// the available countries to your selected set. @objc public var availableCountries: Set<String> = Set<String>(NSLocale.isoCountryCodes) /// The name of your company, for displaying to the user during payment flows. For /// example, when using Apple Pay, the payment sheet's final line item will read /// "PAY {companyName}". /// The default value is the name of your iOS application which is derived from the /// `kCFBundleNameKey` of `Bundle.main`. @objc public var companyName = Bundle.stp_applicationName() ?? "" /// The Apple Merchant Identifier to use during Apple Pay transactions. To create /// one of these, see our guide at https://stripe.com/docs/apple-pay . You /// must set this to a valid identifier in order to automatically enable Apple Pay. @objc public var appleMerchantIdentifier: String? /// Determines whether or not the user is able to delete payment options /// This is only relevant to the `STPPaymentOptionsViewController` which, if /// enabled, will allow the user to delete payment options by tapping the "Edit" /// button in the navigation bar or by swiping left on a payment option and tapping /// "Delete". Currently, the user is not allowed to delete the selected payment /// option but this may change in the future. /// Default value is YES but will only work if `STPPaymentOptionsViewController` is /// initialized with a `STPCustomerContext` either through the `STPPaymentContext` /// or directly as an init parameter. @objc public var canDeletePaymentOptions = true /// Determines whether STPAddCardViewController allows the user to /// scan cards using the camera on devices running iOS 13 or later. /// To use this feature, you must also set the `NSCameraUsageDescription` /// value in your app's Info.plist. /// @note This feature is currently in beta. Please file bugs at /// https://github.com/stripe/stripe-ios/issues /// The default value is currently NO. This will be changed in a future update. @objc public var cardScanningEnabled = false // MARK: - Deprecated /// An enum value representing which payment options you will accept from your user /// in addition to credit cards. @available( *, deprecated, message: "additionalPaymentOptions has been removed. Set applePayEnabled and fpxEnabled on STPPaymentConfiguration instead." ) @objc public var additionalPaymentOptions: Int = 0 private var _publishableKey: String? /// If you used STPPaymentConfiguration.shared.publishableKey, use STPAPIClient.shared.publishableKey instead. The SDK uses STPAPIClient.shared to make API requests by default. /// Your Stripe publishable key /// - seealso: https://dashboard.stripe.com/account/apikeys @available( *, deprecated, message: "If you used STPPaymentConfiguration.shared.publishableKey, use STPAPIClient.shared.publishableKey instead. If you passed a STPPaymentConfiguration instance to an SDK component, create an STPAPIClient, set publishableKey on it, and set the SDK component's APIClient property." ) @objc public var publishableKey: String? { get { if self == STPPaymentConfiguration.shared { return STPAPIClient.shared.publishableKey } return _publishableKey ?? "" } set(publishableKey) { if self == STPPaymentConfiguration.shared { STPAPIClient.shared.publishableKey = publishableKey } else { _publishableKey = publishableKey } } } private var _stripeAccount: String? /// If you used STPPaymentConfiguration.shared.stripeAccount, use STPAPIClient.shared.stripeAccount instead. The SDK uses STPAPIClient.shared to make API requests by default. /// In order to perform API requests on behalf of a connected account, e.g. to /// create charges for a connected account, set this property to the ID of the /// account for which this request is being made. /// - seealso: https://stripe.com/docs/payments#connected-accounts @available( *, deprecated, message: "If you used STPPaymentConfiguration.shared.stripeAccount, use STPAPIClient.shared.stripeAccount instead. If you passed a STPPaymentConfiguration instance to an SDK component, create an STPAPIClient, set stripeAccount on it, and set the SDK component's APIClient property." ) @objc public var stripeAccount: String? { get { if self == STPPaymentConfiguration.shared { return STPAPIClient.shared.stripeAccount } return _stripeAccount ?? "" } set(stripeAccount) { if self == STPPaymentConfiguration.shared { STPAPIClient.shared.stripeAccount = stripeAccount } else { _stripeAccount = stripeAccount } } } // MARK: - Description /// :nodoc: @objc public override var description: String { var additionalPaymentOptionsDescription: String? var paymentOptions: [String] = [] if _applePayEnabled { paymentOptions.append("STPPaymentOptionTypeApplePay") } if fpxEnabled { paymentOptions.append("STPPaymentOptionTypeFPX") } additionalPaymentOptionsDescription = paymentOptions.joined(separator: "|") var requiredBillingAddressFieldsDescription: String? switch requiredBillingAddressFields { case .none: requiredBillingAddressFieldsDescription = "STPBillingAddressFieldsNone" case .postalCode: requiredBillingAddressFieldsDescription = "STPBillingAddressFieldsPostalCode" case .full: requiredBillingAddressFieldsDescription = "STPBillingAddressFieldsFull" case .name: requiredBillingAddressFieldsDescription = "STPBillingAddressFieldsName" default: break } let requiredShippingAddressFieldsDescription = requiredShippingAddressFields?.map({ $0.rawValue }).joined(separator: "|") var shippingTypeDescription: String? switch shippingType { case .shipping: shippingTypeDescription = "STPShippingTypeShipping" case .delivery: shippingTypeDescription = "STPShippingTypeDelivery" default: break } let props = [ // Object String(format: "%@: %p", NSStringFromClass(STPPaymentConfiguration.self), self), // Basic configuration "additionalPaymentOptions = \(additionalPaymentOptionsDescription ?? "")", // Billing and shipping "requiredBillingAddressFields = \(requiredBillingAddressFieldsDescription ?? "")", "requiredShippingAddressFields = \(requiredShippingAddressFieldsDescription ?? "")", "verifyPrefilledShippingAddress = \((verifyPrefilledShippingAddress) ? "YES" : "NO")", "shippingType = \(shippingTypeDescription ?? "")", "availableCountries = \(availableCountries )", // Additional configuration "companyName = \(companyName )", "appleMerchantIdentifier = \(appleMerchantIdentifier ?? "")", "canDeletePaymentOptions = \((canDeletePaymentOptions) ? "YES" : "NO")", "cardScanningEnabled = \((cardScanningEnabled) ? "YES" : "NO")", ] return "<\(props.joined(separator: "; "))>" } // MARK: - NSCopying /// :nodoc: @objc public func copy(with zone: NSZone? = nil) -> Any { let copy = STPPaymentConfiguration() copy.applePayEnabled = _applePayEnabled copy.fpxEnabled = fpxEnabled copy.requiredBillingAddressFields = requiredBillingAddressFields copy.requiredShippingAddressFields = requiredShippingAddressFields copy.verifyPrefilledShippingAddress = verifyPrefilledShippingAddress copy.shippingType = shippingType copy.companyName = companyName copy.appleMerchantIdentifier = appleMerchantIdentifier copy.canDeletePaymentOptions = canDeletePaymentOptions copy.cardScanningEnabled = cardScanningEnabled copy.availableCountries = availableCountries copy._publishableKey = _publishableKey copy._stripeAccount = _stripeAccount return copy } }
mit
liuweicode/LinkimFoundation
Example/LinkimFoundation/Foundation/UI/Component/TextField/PasswordTextField.swift
1
1185
// // PasswordTextField.swift // LinkimFoundation // // Created by 刘伟 on 16/7/8. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit let kPasswordMaxLen = 20 // 密码最大长度限制 class PasswordTextField: BaseTextField,UITextFieldDelegate,BaseTextFieldDelegate { func initTextData() { self.placeholder = "请输入密码" self.keyboardType = .Default self.font = UIFont.systemFontOfSize(16) self.secureTextEntry = true self.clearButtonMode = .WhileEditing self.translatesAutoresizingMaskIntoConstraints = false } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { self.delegate?.textField!(textField, shouldChangeCharactersInRange: range, replacementString: string) let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) return newString.length <= kPasswordMaxLen } func textFieldDidEndEditing(textField: UITextField) { self.delegate?.textFieldDidEndEditing?(textField) } }
mit
austinzheng/swift-compiler-crashes
fixed/25497-llvm-foldingset-swift-constraints-constraintlocator-nodeequals.swift
7
231
// 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 b{let e:a(e class a{ class A{class d<T where g:P{class e
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/27154-swift-modulefile-getdecl.swift
4
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a{typealias f=[(var f{enum b{class A{struct c<T:T.a
mit
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceWebAPI/API Adapter/PushNotificationService.swift
1
577
import Foundation public protocol PushNotificationService { var pushNotificationServiceToken: String { get } func registerForPushNotifications(registration: PushNotificationServiceRegistration) } public struct PushNotificationServiceRegistration: Equatable { var pushNotificationDeviceTokenData: Data? var channels: Set<String> public init(pushNotificationDeviceTokenData: Data?, channels: Set<String>) { self.pushNotificationDeviceTokenData = pushNotificationDeviceTokenData self.channels = channels } }
mit
austinzheng/swift-compiler-crashes
crashes-fuzzing/27569-swift-typechecker-validatedecl.swift
4
300
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a<T{struct B{struct B<A{ class a<T where g:a{class a{ struct A{ class a{ class A{ class A let c{func g{ class B<b{ class B:A
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/27302-swift-conformancelookuptable-conformancelookuptable.swift
4
244
// 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 a{{class B<T where f:P{struct A{struct B{struct B{struct A}}func a{A{
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/22756-swift-parser-parsedeclenum.swift
11
236
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing Void{ return class A { classB protocol A { ( " class A : A { } } }
mit
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift
4
4909
// // Completable+AndThen.swift // RxSwift // // Created by Krunoslav Zaher on 7/2/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Single<E>) -> Single<E> { let completable = self.primitiveSequence.asObservable() return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> { let completable = self.primitiveSequence.asObservable() return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen(_ second: Completable) -> Completable { let completable = self.primitiveSequence.asObservable() return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Observable<E>) -> Observable<E> { let completable = self.primitiveSequence.asObservable() return ConcatCompletable(completable: completable, second: second.asObservable()) } } final private class ConcatCompletable<Element>: Producer<Element> { fileprivate let _completable: Observable<Never> fileprivate let _second: Observable<Element> init(completable: Observable<Never>, second: Observable<Element>) { self._completable = completable self._second = second } override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O : ObserverType, O.E == Element { let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final private class ConcatCompletableSink<O: ObserverType> : Sink<O> , ObserverType { typealias E = Never typealias Parent = ConcatCompletable<O.E> private let _parent: Parent private let _subscription = SerialDisposable() init(parent: Parent, observer: O, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .error(let error): self.forwardOn(.error(error)) self.dispose() case .next: break case .completed: let otherSink = ConcatCompletableSinkOther(parent: self) self._subscription.disposable = self._parent._second.subscribe(otherSink) } } func run() -> Disposable { let subscription = SingleAssignmentDisposable() self._subscription.disposable = subscription subscription.setDisposable(self._parent._completable.subscribe(self)) return self._subscription } } final private class ConcatCompletableSinkOther<O: ObserverType> : ObserverType { typealias E = O.E typealias Parent = ConcatCompletableSink<O> private let _parent: Parent init(parent: Parent) { self._parent = parent } func on(_ event: Event<O.E>) { self._parent.forwardOn(event) if event.isStopEvent { self._parent.dispose() } } }
apache-2.0
mozilla-mobile/focus-ios
XCUITest/ShortcutsTest.swift
1
3043
/* 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 XCTest class ShortcutsTest: BaseTestCase { override func tearDown() { XCUIDevice.shared.orientation = UIDeviceOrientation.portrait super.tearDown() } func testAddRemoveShortcut() { addShortcut(website: "mozilla.org") // Tap on erase button to go to homepage and check the shortcut created app.eraseButton.tap() // Verify the shortcut is created XCTAssertTrue(app.otherElements.staticTexts["Mozilla"].exists) // Remove created shortcut app.otherElements["outerView"].press(forDuration: 2) waitForExistence(app.collectionViews.cells.buttons["Remove from Shortcuts"]) app.collectionViews.cells.buttons["Remove from Shortcuts"].tap() waitForNoExistence(app.otherElements.staticTexts["Mozilla"]) XCTAssertFalse(app.otherElements.staticTexts["Mozilla"].exists) } func testAddRenameShortcut() { addShortcut(website: "mozilla.org") // Tap on erase button to go to homepage and check the shortcut created app.eraseButton.tap() // Verify the shortcut is created XCTAssertTrue(app.otherElements.staticTexts["Mozilla"].exists) // Rename shortcut app.otherElements["outerView"].press(forDuration: 2) waitForExistence(app.collectionViews.cells.buttons["Rename Shortcut"]) app.collectionViews.cells.buttons["Rename Shortcut"].tap() let textField = app.alerts.textFields.element textField.clearAndEnterText(text: "Cheese") app.alerts.buttons["Save"].tap() waitForExistence(app.otherElements.staticTexts["Cheese"]) XCTAssertTrue(app.otherElements.staticTexts["Cheese"].exists) } func testShortcutShownWhileTypingURLBar() { addShortcut(website: "example.com") app.urlTextField.tap() XCTAssertTrue(app.otherElements.staticTexts["Example"].exists) app.urlTextField.typeText("foo") waitForNoExistence(app.otherElements.staticTexts["E"]) XCTAssertFalse(app.otherElements.staticTexts["Example"].exists) } private func addShortcut(website: String) { loadWebPage(website) waitForWebPageLoad() // Tap on shortcuts settings menu option waitForExistence(app.buttons["HomeView.settingsButton"], timeout: 15) app.buttons["HomeView.settingsButton"].tap() if iPad() { waitForExistence(app.collectionViews.cells.element(boundBy: 0)) app.collectionViews.cells.element(boundBy: 0).tap() } else { waitForExistence(app.collectionViews.cells.buttons["Add to Shortcuts"]) app.collectionViews.cells.buttons["Add to Shortcuts"].tap() } waitForNoExistence(app.collectionViews.cells.buttons.element(boundBy: 0)) } }
mpl-2.0
DianQK/StudyUnwindSegue
StudyUnwindsegue/TestUnwindsegue/AnimalPickerViewController.swift
1
1522
// // PickerViewController.swift // TestUnwindsegue // // Created by 宋宋 on 12/28/15. // Copyright © 2015 TransitionTreasury. All rights reserved. // import UIKit class AnimalPickerViewController: UIViewController { static let UnwindSegue = "UnwindAnimalPicker" private(set) var selectedAnimal: String! @IBOutlet weak var pickerButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func dogButtonPressed(sender: AnyObject) { selectAnimal("Dog") } @IBAction func catButtonPressed(sender: AnyObject) { selectAnimal("Cat") } @IBAction func snakeButtonPressed(sender: AnyObject) { selectAnimal("Snake") } private func selectAnimal(animal: String) { selectedAnimal = animal performSegueWithIdentifier(AnimalPickerViewController.UnwindSegue, sender: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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