repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tensorflow/examples
lite/examples/classification_by_retrieval/ios/ImageClassifierBuilder/ModelTrainerView.swift
1
2504
// Copyright 2021 The TensorFlow 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. import SwiftUI /// Displays a progress view while the model is being trained, and the result once trained. /// /// This screen is part of the model creation UX. struct ModelTrainerView: View { /// The metadata of the model to create. let modelMetadata: ModelMetadata /// The list of selected albums from the Photos Library. let albums: [Album] /// The closure to call once the Model object will be created. let completion: (Model?) -> Void /// The Model object associated to the model trained in this step. @State private var model: Model? var body: some View { VStack { if model == nil { Text("The model is being trained…") .padding() ProgressView() } else { Text("The model has been trained.") .padding() Image(systemName: "checkmark") .accessibility(hidden: true) } } .onAppear { // onAppear will strangely be called if the back button is tapped [1], on a new // ModelTrainerView whose albums are not set. // [1]: https://developer.apple.com/forums/thread/655338 guard !albums.isEmpty else { return } DispatchQueue.global(qos: .userInitiated).async { let model = ModelTrainer().trainModel(metadata: modelMetadata, on: albums) DispatchQueue.main.async { self.model = model } } } .navigationBarTitle(Text("Training"), displayMode: .inline) .toolbar { ToolbarItem(placement: .primaryAction) { if let model = model { Button("Save") { completion(model) } .accessibilityHint("Saves the created model locally.") } else { Button("Save") {} .disabled(true) .accessibilityHint( "Saves the created model locally. Dimmed until the model has been created.") } } } } }
apache-2.0
f2f5d9d11b8d1a726042c8bb7f443bfd
33.75
91
0.644684
4.491921
false
false
false
false
vapor/vapor
Sources/Vapor/Validation/Validators/Case.swift
1
1811
extension Validator { /// Validates that the data can be converted to a value of an enum type with iterable cases. public static func `case`<E>(of enum: E.Type) -> Validator<T> where E: RawRepresentable & CaseIterable, E.RawValue == T, T: CustomStringConvertible { .init { ValidatorResults.Case(enumType: E.self, rawValue: $0) } } } extension ValidatorResults { /// `ValidatorResult` of a validator that validates whether the data can be represented as a specific Enum case. public struct Case<T, E> where E: RawRepresentable & CaseIterable, E.RawValue == T, T: CustomStringConvertible { /// The type of the enum to check. public let enumType: E.Type /// The raw value that would be tested against the enum type. public let rawValue: T } } extension ValidatorResults.Case: ValidatorResult { public var isFailure: Bool { return enumType.init(rawValue: rawValue) == nil } public var successDescription: String? { makeDescription(not: false) } public var failureDescription: String? { makeDescription(not: true) } func makeDescription(not: Bool) -> String { let items = E.allCases.map { "\($0.rawValue)" } let description: String switch items.count { case 1: description = items[0].description case 2: description = "\(items[0].description) or \(items[1].description)" default: let first = items[0..<(items.count - 1)] .map { $0.description }.joined(separator: ", ") let last = items[items.count - 1].description description = "\(first), or \(last)" } return "is\(not ? " not" : "") \(description)" } }
mit
6a6c75921f6cdd66b390f04646f0109c
32.537037
116
0.603534
4.406326
false
false
false
false
Dwarven/ShadowsocksX-NG
ShadowsocksX-NG/ServerProfile.swift
1
11512
// // ServerProfile.swift // ShadowsocksX-NG // // Created by 邱宇舟 on 16/6/6. // Copyright © 2016年 qiuyuzhou. All rights reserved. // import Cocoa class ServerProfile: NSObject, NSCopying { @objc var uuid: String @objc var serverHost: String = "" @objc var serverPort: uint16 = 8379 @objc var method:String = "aes-128-gcm" @objc var password:String = "" @objc var remark:String = "" // SIP003 Plugin @objc var plugin: String = "" // empty string disables plugin @objc var pluginOptions: String = "" override init() { uuid = UUID().uuidString } init(uuid: String) { self.uuid = uuid } convenience init?(url: URL) { self.init() func padBase64(string: String) -> String { var length = string.utf8.count if length % 4 == 0 { return string } else { length = 4 - length % 4 + length return string.padding(toLength: length, withPad: "=", startingAt: 0) } } func decodeUrl(url: URL) -> (String?,String?) { let urlStr = url.absoluteString let base64Begin = urlStr.index(urlStr.startIndex, offsetBy: 5) let base64End = urlStr.firstIndex(of: "#") let encodedStr = String(urlStr[base64Begin..<(base64End ?? urlStr.endIndex)]) guard let data = Data(base64Encoded: padBase64(string: encodedStr)) else { // Not legacy format URI return (url.absoluteString, nil) } guard let decoded = String(data: data, encoding: String.Encoding.utf8) else { return (nil, nil) } var s = decoded.trimmingCharacters(in: CharacterSet(charactersIn: "\n")) // May be legacy format URI // Note that the legacy URI doesn't follow RFC3986. It means the password here // should be plain text, not percent-encoded. // Ref: https://shadowsocks.org/en/config/quick-guide.html let parser = try? NSRegularExpression( pattern: "(.+):(.+)@(.+)", options: .init()) if let match = parser?.firstMatch(in:s, options: [], range: NSRange(location: 0, length: s.utf16.count)) { // Convert legacy format to SIP002 format let r1 = Range(match.range(at: 1), in: s)! let r2 = Range(match.range(at: 2), in: s)! let r3 = Range(match.range(at: 3), in: s)! let user = String(s[r1]) let password = String(s[r2]) let hostAndPort = String(s[r3]) let rawUserInfo = "\(user):\(password)".data(using: .utf8)! let userInfo = rawUserInfo.base64EncodedString() s = "ss://\(userInfo)@\(hostAndPort)" } if let index = base64End { let i = urlStr.index(index, offsetBy: 1) let fragment = String(urlStr[i...]) return (s, fragment) } return (s, nil) } func decodeLegacyFormat(url: String) -> (URL?,String?) { return (nil, nil) } let (_decodedUrl, _tag) = decodeUrl(url: url) guard let decodedUrl = _decodedUrl else { return nil } guard var parsedUrl = URLComponents(string: decodedUrl) else { return nil } guard let host = parsedUrl.host, let port = parsedUrl.port, let user = parsedUrl.user else { return nil } self.serverHost = host self.serverPort = UInt16(port) // This can be overriden by the fragment part of SIP002 URL remark = parsedUrl.queryItems? .filter({ $0.name == "Remark" }).first?.value ?? "" if let tag = _tag { remark = tag } // SIP002 URL have no password section guard let data = Data(base64Encoded: padBase64(string: user)), let userInfo = String(data: data, encoding: .utf8) else { return nil } let parts = userInfo.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) if parts.count != 2 { return nil } self.method = String(parts[0]).lowercased() self.password = String(parts[1]) // SIP002 defines where to put the profile name if let profileName = parsedUrl.fragment { self.remark = profileName } if let pluginStr = parsedUrl.queryItems? .filter({ $0.name == "plugin" }).first?.value { let parts = pluginStr.split(separator: ";", maxSplits: 1) if parts.count == 2 { plugin = String(parts[0]) pluginOptions = String(parts[1]) } else if parts.count == 1 { plugin = String(parts[0]) } } } public func copy(with zone: NSZone? = nil) -> Any { let copy = ServerProfile() copy.serverHost = self.serverHost copy.serverPort = self.serverPort copy.method = self.method copy.password = self.password copy.remark = self.remark copy.plugin = self.plugin copy.pluginOptions = self.pluginOptions return copy; } static func fromDictionary(_ data:[String:Any?]) -> ServerProfile { let cp = { (profile: ServerProfile) in profile.serverHost = data["ServerHost"] as! String profile.serverPort = (data["ServerPort"] as! NSNumber).uint16Value profile.method = data["Method"] as! String profile.password = data["Password"] as! String if let remark = data["Remark"] { profile.remark = remark as! String } if let plugin = data["Plugin"] as? String { profile.plugin = plugin } if let pluginOptions = data["PluginOptions"] as? String { profile.pluginOptions = pluginOptions } } if let id = data["Id"] as? String { let profile = ServerProfile(uuid: id) cp(profile) return profile } else { let profile = ServerProfile() cp(profile) return profile } } func toDictionary() -> [String:AnyObject] { var d = [String:AnyObject]() d["Id"] = uuid as AnyObject? d["ServerHost"] = serverHost as AnyObject? d["ServerPort"] = NSNumber(value: serverPort as UInt16) d["Method"] = method as AnyObject? d["Password"] = password as AnyObject? d["Remark"] = remark as AnyObject? d["Plugin"] = plugin as AnyObject d["PluginOptions"] = pluginOptions as AnyObject return d } func toJsonConfig() -> [String: AnyObject] { var conf: [String: AnyObject] = ["password": password as AnyObject, "method": method as AnyObject,] let defaults = UserDefaults.standard conf["local_port"] = NSNumber(value: UInt16(defaults.integer(forKey: "LocalSocks5.ListenPort")) as UInt16) conf["local_address"] = defaults.string(forKey: "LocalSocks5.ListenAddress") as AnyObject? conf["timeout"] = NSNumber(value: UInt32(defaults.integer(forKey: "LocalSocks5.Timeout")) as UInt32) conf["server"] = serverHost as AnyObject conf["server_port"] = NSNumber(value: serverPort as UInt16) if !plugin.isEmpty { // all plugin binaries should be located in the plugins dir // so that we don't have to mess up with PATH envvars conf["plugin"] = "plugins/\(plugin)" as AnyObject conf["plugin_opts"] = pluginOptions as AnyObject } return conf } func debugString() -> String { var buf = "" print("ServerHost=\(String(repeating: "*", count: serverHost.count))", to: &buf) print("ServerPort=\(serverPort)", to: &buf) print("Method=\(method)", to: &buf) print("Password=\(String(repeating: "*", count: password.count))", to: &buf) print("Plugin=\(plugin)", to: &buf) print("PluginOptions=\(pluginOptions)", to: &buf) return buf } func isValid() -> Bool { func validateIpAddress(_ ipToValidate: String) -> Bool { var sin = sockaddr_in() var sin6 = sockaddr_in6() if ipToValidate.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1 { // IPv6 peer. return true } else if ipToValidate.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1 { // IPv4 peer. return true } return false; } func validateDomainName(_ value: String) -> Bool { let validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$" if (value.range(of: validHostnameRegex, options: .regularExpression) != nil) { return true } else { return false } } if !(validateIpAddress(serverHost) || validateDomainName(serverHost)){ return false } if password.isEmpty { return false } return true } private func makeLegacyURL() -> URL? { var url = URLComponents() url.host = serverHost url.user = method url.password = password url.port = Int(serverPort) url.fragment = remark let parts = url.string?.replacingOccurrences( of: "//", with: "", options: String.CompareOptions.anchored, range: nil) let base64String = parts?.data(using: String.Encoding.utf8)? .base64EncodedString(options: Data.Base64EncodingOptions()) if var s = base64String { s = s.trimmingCharacters(in: CharacterSet(charactersIn: "=")) return Foundation.URL(string: "ss://\(s)") } return nil } func URL(legacy: Bool = false) -> URL? { // If you want the URL from <= 1.5.1 if (legacy) { return self.makeLegacyURL() } guard let rawUserInfo = "\(method):\(password)".data(using: .utf8) else { return nil } let userInfo = rawUserInfo.base64EncodedString() var items: [URLQueryItem] = [] if !plugin.isEmpty { let value = "\(plugin);\(pluginOptions)" items.append(URLQueryItem(name: "plugin", value: value)) } var comps = URLComponents() comps.scheme = "ss" comps.host = serverHost comps.port = Int(serverPort) comps.user = userInfo comps.path = "/" // This is required by SIP0002 for URLs with fragment or query comps.fragment = remark comps.queryItems = items let url = try? comps.asURL() return url } func title() -> String { if remark.isEmpty { return "\(serverHost):\(serverPort)" } else { return "\(String(remark.prefix(24))) (\(serverHost):\(serverPort))" } } }
gpl-3.0
71a078c8ad978c10e176d6ff305a9815
33.337313
149
0.536382
4.393812
false
false
false
false
victorchee/VCElasticTextField
VCElasticTextField/VCElasticTextField/ElasticTextField.swift
1
1544
// // ElasticTextField.swift // VCElasticTextField // // Created by qihaijun on 9/11/15. // Copyright (c) 2015 VictorChee. All rights reserved. // import UIKit class ElasticTextField: UITextField { var elasticView: ElasticView! @IBInspectable var overshootAmount: CGFloat = 10.0 { didSet { elasticView.overshootAmount = overshootAmount } } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { clipsToBounds = false borderStyle = .None elasticView = ElasticView(frame: bounds) elasticView.backgroundColor = backgroundColor addSubview(elasticView) backgroundColor = UIColor.clearColor() // use elastic view's background color as background color elasticView.userInteractionEnabled = false // 不能触发当前View的Touches事件,而通过传递进去 } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { elasticView.touchesBegan(touches, withEvent: event) } // Add some padding to the text and editing bounds override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, 10.0, 5.0) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, 10.0, 5.0) } }
mit
dc8a8ea1f78b637b32e5f09a40304507
26.454545
105
0.638411
4.660494
false
false
false
false
kevintavog/Radish
src/Radish/WikipediaProvider.swift
1
2822
import Foundation import Alamofire import SwiftyJSON open class WikipediaDetail { public let id: String public let title: String public let pageId: Int public let latitude: Double public let longitude: Double public let distance: Int public let type: String init(id: String, title: String, pageId: Int, latitude: Double, longitude: Double, distance: Int, type: String) { self.id = id self.title = title self.pageId = pageId self.latitude = latitude self.longitude = longitude self.distance = distance self.type = type } } open class WikipediaProvider { public init() { } public func lookup(latitude: Double, longitude: Double) -> [WikipediaDetail] { var details = [WikipediaDetail]() let url = "https://en.wikipedia.org/w/api.php" let parameters = [ "action": "query", "format": "json", "gslimit": "20", "gscoord": "\(latitude)|\(longitude)", "gsprop": "globe|type", "gsradius": "2000", "list": "geosearch"] var error: Swift.Error? = nil var resultData: Data? = nil let semaphore = DispatchSemaphore(value: 0) Alamofire.request(url, parameters: parameters) .validate() .response { response in if response.error != nil { error = response.error } else { resultData = response.data } semaphore.signal() } semaphore.wait() if error != nil { return details } do { let json = try JSON(data: resultData!) if let resultsJson = json["query"]["geosearch"].array { for itemJson in resultsJson { if let title = itemJson["title"].string, let pageId = itemJson["pageid"].int, let lat = itemJson["lat"].double, let lon = itemJson["lon"].double, let distance = itemJson["dist"].double { let index = details.count + 1 details.append(WikipediaDetail( id: String(index), title: title, pageId: pageId, latitude: lat, longitude: lon, distance: Int(distance), type: itemJson["type"].string ?? "")) } } } return details } catch { return details } } }
mit
8a344c5172824b0aec24d4c1c19a3eb1
29.021277
114
0.468462
5.235622
false
false
false
false
PureSwift/Bluetooth
Tests/BluetoothTests/BluetoothTests.swift
1
18063
// // BluetoothTests.swift // Bluetooth // // Created by Alsey Coleman Miller on 11/28/17. // Copyright © 2017 PureSwift. All rights reserved. // import XCTest import Foundation @testable import Bluetooth #if canImport(BluetoothHCI) import BluetoothHCI #endif #if canImport(BluetoothGATT) import BluetoothGATT #endif final class BluetoothTests: XCTestCase { #if canImport(BluetoothHCI) func testAdvertisingInterval() { let value = AdvertisingInterval.default XCTAssertNil(AdvertisingInterval(rawValue: 0)) XCTAssertNil(AdvertisingInterval(rawValue: .max)) // Equatable, comparable, hashable XCTAssert(value < .max) XCTAssert(value > .min) XCTAssertNotEqual(value, .max) XCTAssertNotEqual(value, .min) // Range: 0x0020 to 0x4000 XCTAssertEqual(AdvertisingInterval.min.miliseconds, 20, "The `advInterval` shall be an integer multiple of 0.625 ms in the range of `20` ms to `10.24` s") XCTAssertEqual(AdvertisingInterval(miliseconds: 20), .min) XCTAssertEqual(AdvertisingInterval.max.miliseconds, 10240, "The `advInterval` shall be an integer multiple of 0.625 ms in the range of `20` ms to `10.24` s") XCTAssertEqual(AdvertisingInterval(miliseconds: 10240), .max) XCTAssertEqual(AdvertisingInterval.default.miliseconds, Int(Double(1.28 * 1000)), "Default: N = 0x0800 (1.28 second)") XCTAssertEqual(AdvertisingInterval(miliseconds: 1280), .default) XCTAssertEqual("\(AdvertisingInterval.min)", "20ms") XCTAssertEqual("\(AdvertisingInterval.max)", "10240ms") XCTAssertEqual("\(AdvertisingInterval.default)", "1280ms") } #endif func testSecurityLevel() { let level = SecurityLevel() XCTAssertTrue(level < .high) XCTAssertTrue(SecurityLevel.low < .high) } func testCompanyIdentifier() { let company: CompanyIdentifier = 76 // Apple, Inc. #if !os(WASI) XCTAssertEqual(company.description, "Apple, Inc.") #endif XCTAssertNotEqual(company.hashValue, 0) XCTAssertNotEqual(company, 77) } #if canImport(BluetoothHCI) func testChannelIdentifier() { XCTAssertEqual(ChannelIdentifier.att, 4) XCTAssertEqual(ChannelIdentifier.att.description, "4") } func testHCICommandTimeout() { let timeout: HCICommandTimeout = 1000 XCTAssertEqual(timeout, .default) XCTAssertEqual(timeout.duration, 1.0) XCTAssertEqual(timeout.rawValue, 1000) XCTAssertNotEqual(timeout, 2000) XCTAssertEqual(timeout.description, "1.0 seconds") } func testHCIVersion() { XCTAssertEqual(HCIVersion.v4_2.rawValue, 0x8, "HCI Version: 4.2 (0x8)") XCTAssertEqual(HCIVersion.v4_0.description, "4.0") XCTAssertEqual(HCIVersion.v4_1.description, "4.1") XCTAssertEqual(HCIVersion.v4_2.description, "4.2") XCTAssertEqual(HCIVersion.v5_0.description, "5.0") XCTAssertEqual(HCIVersion.v4_0, .v4_0) XCTAssertNotEqual(HCIVersion.v4_0, .v5_0) XCTAssertLessThan(HCIVersion.v4_0, .v4_2) XCTAssertGreaterThan(HCIVersion.v5_0, .v4_2) } #endif func testLowEnergyAdvertisingData() { do { // zeroed data XCTAssertEqual(LowEnergyAdvertisingData(data: Data())?.data, Data()) XCTAssertEqual(LowEnergyAdvertisingData().data, Data()) XCTAssertNotEqual(LowEnergyAdvertisingData().hashValue, 0) } do { let advertisingData: LowEnergyAdvertisingData = [0x0B, 0x09, 0x42, 0x6C, 0x75, 0x65, 0x5A, 0x20, 0x35, 0x2E, 0x34, 0x33] XCTAssertEqual(advertisingData.data.count, advertisingData.count) XCTAssertEqual(advertisingData, [0x0B, 0x09, 0x42, 0x6C, 0x75, 0x65, 0x5A, 0x20, 0x35, 0x2E, 0x34, 0x33]) XCTAssertNotEqual(advertisingData.hashValue, 0) } } #if canImport(BluetoothHCI) func testLowEnergyAddressType() { XCTAssertEqual(LowEnergyAddressType(), .public) XCTAssert(LowEnergyAddressType.public.isCompatible(with: .v4_0)) XCTAssert(LowEnergyAddressType.public.isCompatible(with: .v4_2)) XCTAssert(LowEnergyAddressType.public.isCompatible(with: .v5_0)) XCTAssert(LowEnergyAddressType.random.isCompatible(with: .v4_0)) XCTAssert(LowEnergyAddressType.random.isCompatible(with: .v4_2)) XCTAssert(LowEnergyAddressType.random.isCompatible(with: .v5_0)) XCTAssert(LowEnergyAddressType.publicIdentity.isCompatible(with: .v5_0)) XCTAssert(LowEnergyAddressType.randomIdentity.isCompatible(with: .v5_0)) XCTAssert(LowEnergyAddressType.publicIdentity.isCompatible(with: .v4_2) == false) XCTAssert(LowEnergyAddressType.randomIdentity.isCompatible(with: .v4_2) == false) } func testLowEnergyState() { var states = BitMaskOptionSet<LowEnergyState>.all XCTAssert(states.isEmpty == false) XCTAssertEqual(states.count, LowEnergyState.allCases.count) XCTAssert(Array(states) == LowEnergyState.allCases) states.forEach { XCTAssert(LowEnergyState.allCases.contains($0)) } states.removeAll() XCTAssert(states.count == 0) XCTAssert(states.isEmpty) XCTAssertEqual(LowEnergyStateSet.state0.states, [.nonConnectableAdvertising]) XCTAssertEqual(LowEnergyStateSet.state1.states, [.scannableAdvertising]) XCTAssertEqual(LowEnergyState.scannableAdvertising.description, "Scannable Advertising State") } func testLowEnergyAdvertisingFilterPolicy() { typealias FilterPolicy = HCILESetAdvertisingParameters.FilterPolicy XCTAssertEqual(FilterPolicy(), .any) XCTAssertEqual(FilterPolicy(whiteListScan: false, whiteListConnect: true), .whiteListConnect) XCTAssertEqual(FilterPolicy(whiteListScan: true, whiteListConnect: false), .whiteListScan) XCTAssertEqual(FilterPolicy(whiteListScan: true, whiteListConnect: true), .whiteListScanConnect) XCTAssertEqual(FilterPolicy(whiteListScan: false, whiteListConnect: false), .any) } func testLowEnergyFeature() { XCTAssertEqual(LowEnergyFeature.encryption.description, "LE Encryption") XCTAssert(LowEnergyFeature.encryption.isValidControllerToController) var featureSet: LowEnergyFeatureSet = [.encryption, .connectionParametersRequestProcedure, .ping] XCTAssert(featureSet.count == 3) XCTAssert(featureSet.isEmpty == false) XCTAssert(featureSet.contains(.encryption)) XCTAssert(featureSet.contains(.connectionParametersRequestProcedure)) XCTAssert(featureSet.contains(.ping)) XCTAssert(featureSet.contains(.le2mPhy) == false) XCTAssert(featureSet.rawValue != LowEnergyFeature.encryption.rawValue) XCTAssert(featureSet.rawValue != LowEnergyFeature.connectionParametersRequestProcedure.rawValue) XCTAssert(featureSet.rawValue != LowEnergyFeature.ping.rawValue) XCTAssert(LowEnergyFeature(rawValue: featureSet.rawValue) == nil) XCTAssert(LowEnergyFeature.RawValue.bitWidth == LowEnergyFeatureSet.RawValue.bitWidth) XCTAssert(LowEnergyFeature.RawValue.bitWidth == MemoryLayout<LowEnergyFeature.RawValue>.size * 8) XCTAssert(LowEnergyFeature.RawValue.bitWidth == 64) XCTAssert(MemoryLayout<LowEnergyFeatureSet>.size == MemoryLayout<LowEnergyFeature.RawValue>.size) XCTAssert(MemoryLayout<LowEnergyFeatureSet>.size == 8) // 64 bit featureSet = .all XCTAssertFalse(featureSet.isEmpty) XCTAssertEqual(featureSet.count, LowEnergyFeature.allCases.count) XCTAssertEqual(Array(featureSet), LowEnergyFeature.allCases) typealias Bit64 = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) let bigEndianByteValue: Bit64 = (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01) let littleEndianByteValue: Bit64 = (0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) let rawValue: UInt64 = 0b01 XCTAssert(rawValue.littleEndian.bytes.0 == littleEndianByteValue.0) XCTAssert(rawValue.littleEndian.bytes.1 == littleEndianByteValue.1) XCTAssert(rawValue.littleEndian.bytes.2 == littleEndianByteValue.2) XCTAssert(rawValue.littleEndian.bytes.3 == littleEndianByteValue.3) XCTAssert(rawValue.littleEndian.bytes.4 == littleEndianByteValue.4) XCTAssert(rawValue.littleEndian.bytes.5 == littleEndianByteValue.5) XCTAssert(rawValue.littleEndian.bytes.6 == littleEndianByteValue.6) XCTAssert(rawValue.littleEndian.bytes.7 == littleEndianByteValue.7) XCTAssert(UInt64(littleEndian: UInt64(bytes: littleEndianByteValue)) == rawValue) XCTAssert(rawValue.bigEndian.bytes.0 == bigEndianByteValue.0) XCTAssert(rawValue.bigEndian.bytes.1 == bigEndianByteValue.1) XCTAssert(rawValue.bigEndian.bytes.2 == bigEndianByteValue.2) XCTAssert(rawValue.bigEndian.bytes.3 == bigEndianByteValue.3) XCTAssert(rawValue.bigEndian.bytes.4 == bigEndianByteValue.4) XCTAssert(rawValue.bigEndian.bytes.5 == bigEndianByteValue.5) XCTAssert(rawValue.bigEndian.bytes.6 == bigEndianByteValue.6) XCTAssert(rawValue.bigEndian.bytes.7 == bigEndianByteValue.7) XCTAssert(UInt64(bigEndian: UInt64(bytes: bigEndianByteValue)) == rawValue) featureSet.forEach { XCTAssert(LowEnergyFeature.allCases.contains($0)) } featureSet.removeAll() XCTAssertEqual(featureSet.rawValue, 0) XCTAssertEqual(featureSet.count, 0) XCTAssertEqual(featureSet.hashValue, featureSet.rawValue.hashValue) } func testLowEnergyEventMask() { typealias EventMask = HCILESetEventMask.EventMask XCTAssert(EventMask().isEmpty) XCTAssert(EventMask(rawValue: 0x00).isEmpty) XCTAssertEqual(0x0000_0000_0000_001F, 0b11111) XCTAssertEqual(EventMask(rawValue: 0x0000_0000_0000_001F), [.connectionComplete, .advertisingReport, .connectionUpdateComplete, .readRemoteFeaturesComplete, .longTermKeyRequest, .remoteConnectionParameterRequest], "The default is for bits 0 to 4 inclusive (the value 0x0000 0000 0000 001F) to be set.") } func testAdvertisingChannelHeader() { XCTAssertEqual(AdvertisingChannelHeader().rawValue, 0) XCTAssertEqual(AdvertisingChannelHeader(), .undirectedAdvertising) } #endif #if canImport(BluetoothGATT) func testBitMaskOption() { do { // set conversion let all = BitMaskOptionSet(ATTAttributePermission.allCases) let expected: Set<ATTAttributePermission> = [.read, .write, .readEncrypt, .writeEncrypt, .readAuthentication, .writeAuthentication, .authorized, .noAuthorization] XCTAssertEqual(expected, Set(ATTAttributePermission.allCases)) XCTAssert(all.contains(ATTAttributePermission.allCases)) XCTAssertEqual(all.count, ATTAttributePermission.allCases.count) XCTAssertEqual(all.count, 8) XCTAssertEqual(Set(all), Set(ATTAttributePermission.allCases)) XCTAssertEqual(all, BitMaskOptionSet<ATTAttributePermission>.all) XCTAssert(all.contains(ATTAttributePermission.encrypt)) XCTAssert(all.contains(ATTAttributePermission.authentication)) XCTAssert(BitMaskOptionSet<ATTAttributePermission>().contains(.read) == false) XCTAssert(BitMaskOptionSet<ATTAttributePermission>().contains(ATTAttributePermission.allCases) == false) } do { // Sets are as large as a single element XCTAssert(MemoryLayout<BitMaskOptionSet<GATTCharacteristicProperty>>.size == MemoryLayout<GATTCharacteristicProperty>.size) // create empty set var set = BitMaskOptionSet<GATTCharacteristicProperty>() XCTAssert(set.count == 0) XCTAssert(set.isEmpty) XCTAssert(set.rawValue == 0) // insert value set.insert(.read) XCTAssert(set.rawValue == GATTCharacteristicProperty.read.rawValue) XCTAssert(set.count == 1) XCTAssert(set.isEmpty == false) // cant store duplicates set.insert(.read) XCTAssert(set.rawValue == GATTCharacteristicProperty.read.rawValue) XCTAssert(set.count == 1) XCTAssert(set.isEmpty == false) // can store different values set.insert(.write) XCTAssert(set.rawValue == (GATTCharacteristicProperty.read.rawValue | GATTCharacteristicProperty.write.rawValue)) XCTAssert(set.count == 2) XCTAssert(set.isEmpty == false) // comparison with other collections XCTAssert(set.contains([.read, .write])) XCTAssert(set == [.read, .write]) } } #endif func testClassOfDevice() { do { let data = Data([0b00001101, 0b00000001, 0b11000010]) guard let classOfDevice = ClassOfDevice(data: data) else { XCTFail("Could not decode"); return } XCTAssertTrue(classOfDevice.majorServiceClass.contains(.networking)) guard case let .computer(computer) = classOfDevice.majorDeviceClass else { XCTFail("majorDeviceClass is wrong"); return } guard computer == .laptop else { XCTFail("majorDeviceClass is wrong"); return } XCTAssertEqual(classOfDevice.data, data) XCTAssertEqual(classOfDevice.formatType, ClassOfDevice.FormatType(rawValue: 0b01)) guard let formatType = ClassOfDevice.FormatType(rawValue: 0b01) else { XCTFail("Could not init formatType"); return } let majorServiceClass = BitMaskOptionSet<ClassOfDevice.MajorServiceClass>(rawValue: 0b11000010000) let majorDeviceClass = ClassOfDevice.MajorDeviceClass.computer(.laptop) let classOfDeviceManual = ClassOfDevice(formatType: formatType, majorServiceClass: majorServiceClass, majorDeviceClass: majorDeviceClass) XCTAssertEqual(classOfDevice.formatType, formatType) XCTAssertEqual(classOfDevice.majorDeviceClass, majorDeviceClass) XCTAssertEqual(classOfDevice, classOfDeviceManual) } do { let data = Data([0b00001101, 0b00100010, 0b11000000]) guard let classOfDevice = ClassOfDevice(data: data) else { XCTFail("Could not decode"); return } XCTAssertTrue(classOfDevice.majorServiceClass.contains(.limitedDiscoverable)) XCTAssertTrue(classOfDevice.majorServiceClass.contains(.telephony)) XCTAssertTrue(classOfDevice.majorServiceClass.contains(.information)) XCTAssertFalse(classOfDevice.majorServiceClass.contains(.audio)) XCTAssertFalse(classOfDevice.majorServiceClass.contains(.objectTransfer)) guard case let .phone(phone) = classOfDevice.majorDeviceClass else { XCTFail("majorDeviceClass is wrong"); return } guard phone == .smartphone else { XCTFail("majorDeviceClass is wrong"); return } XCTAssertEqual(classOfDevice.data, data) XCTAssertEqual(classOfDevice.formatType, ClassOfDevice.FormatType(rawValue: 0b01)) } do { let data = Data([0b01000100, 0b00100101, 0b11100000]) guard let classOfDevice = ClassOfDevice(data: data) else { XCTFail("Could not decode"); return } XCTAssertTrue(classOfDevice.majorServiceClass.contains(.audio)) guard case let .peripheral(peripheral, device) = classOfDevice.majorDeviceClass else { XCTFail("majorDeviceClass is wrong"); return } XCTAssertEqual(peripheral, .keyboard) XCTAssertEqual(device, .joystick) XCTAssertEqual(classOfDevice.data, data) XCTAssertEqual(classOfDevice.formatType, ClassOfDevice.FormatType(rawValue: 0b00)) } do { let data = Data([0b00000100, 0b00000111, 0b11100110]) guard let classOfDevice = ClassOfDevice(data: data) else { XCTFail("Could not decode"); return } XCTAssertTrue(classOfDevice.majorServiceClass.contains(.telephony)) guard case let .wearable(wearable) = classOfDevice.majorDeviceClass else { XCTFail("majorDeviceClass is wrong"); return } XCTAssertEqual(wearable, .wristwatch) XCTAssertEqual(classOfDevice.data, data) XCTAssertEqual(classOfDevice.formatType, ClassOfDevice.FormatType(rawValue: 0b00)) } } }
mit
a74871a96471050d4aec319d02740d3c
43.269608
165
0.637914
4.749408
false
false
false
false
uias/Tabman
Sources/Tabman/Bar/BarView/TMBarViewUpdateHandler.swift
1
5636
// // TMBarViewUpdateHandler.swift // Tabman // // Created by Merrick Sapsford on 30/10/2018. // Copyright © 2022 UI At Six. All rights reserved. // import UIKit /// Handler for executing positional updates on bar view components. /// /// Interprets and calculates appropriate values for updates dependent on component animation styles. All components which use /// this must conform to `TMAnimateable`. internal final class TMBarViewUpdateHandler<Layout: TMBarLayout, Button: TMBarButton, Indicator: TMBarIndicator> { /// Context which describes the current positional and focus values for the bar view. struct Context { let position: CGFloat let capacity: Int let direction: TMBarUpdateDirection let maxArea: CGRect let focusArea: CGRect let focusRect: TMBarViewFocusRect init(position: CGFloat, capacity: Int, direction: TMBarUpdateDirection, maxArea: CGRect, focusArea: CGRect, layoutDirection: UIUserInterfaceLayoutDirection) { self.position = position self.capacity = capacity self.direction = direction self.maxArea = maxArea self.focusArea = focusArea self.focusRect = TMBarViewFocusRect(rect: focusArea, maxRect: maxArea, at: position, capacity: capacity, layoutDirection: layoutDirection) } } private weak var barView: TMBarView<Layout, Button, Indicator>! private let position: CGFloat private let capacity: Int private let direction: TMBarUpdateDirection private let animation: TMAnimation private var focusArea: CGRect? // MARK: Init init(for barView: TMBarView<Layout, Button, Indicator>, at position: CGFloat, capacity: Int, direction: TMBarUpdateDirection, expectedAnimation: TMAnimation) { self.barView = barView self.position = position self.capacity = capacity self.direction = direction self.animation = expectedAnimation } /// Update a component. /// /// - Parameters: /// - component: Component to update. /// - action: Action closure with Component relevant context. func update(component: TMTransitionStyleable, action: @escaping (Context) -> Void) { let transitionStyle = component.transitionStyle let animation = makeAnimation(for: transitionStyle, expected: self.animation) let update = { let context = self.generateContext(for: transitionStyle) action(context) } if animation.isEnabled { UIView.animate(withDuration: animation.duration) { update() } } else { update() } } // MARK: Utility /// Generate a new context from an existing one, that takes account of animation style. /// /// - Parameters: /// - transitionStyle: Animation style. /// - Returns: Context relevant for animation style. private func generateContext(for transitionStyle: TMTransitionStyle) -> Context { let focusArea = self.focusArea ?? makeFocusArea(for: position, capacity: capacity) return Context(position: makePosition(from: position, for: transitionStyle), capacity: capacity, direction: direction, maxArea: CGRect(origin: .zero, size: barView.scrollView.contentSize), focusArea: focusArea, layoutDirection: UIView.userInterfaceLayoutDirection(for: barView.semanticContentAttribute)) } /// Generate a new position dependending on animation style. /// /// - Parameters: /// - position: Original position. /// - transitionStyle: Animation style. /// - Returns: Position relevant for animation style. private func makePosition(from position: CGFloat, for animationStyle: TMTransitionStyle) -> CGFloat { switch animationStyle { case .snap, .none: return round(position) default: return position } } /// Make animation for an animation style. /// /// - Parameters: /// - style: Style of animation. /// - expected: Existing animation. /// - Returns: Animation relevant for style. private func makeAnimation(for style: TMTransitionStyle, expected: TMAnimation) -> TMAnimation { let isEnabled: Bool switch style { case .none: isEnabled = false case .progressive: isEnabled = expected.isEnabled case .snap: isEnabled = true } return TMAnimation(isEnabled: isEnabled, duration: expected.duration) } /// Make focus area. /// /// - Parameters: /// - position: Position. /// - capacity: Capacity. /// - Returns: Focus area. private func makeFocusArea(for position: CGFloat, capacity: Int) -> CGRect { let focusArea = barView.layoutGrid.convert(barView.layout.focusArea(for: position, capacity: capacity), from: barView.layout.view) self.focusArea = focusArea barView.layoutIfNeeded() return focusArea } }
mit
37c3f1169dd183f49a3706cb5560bf58
34
126
0.590417
5.382044
false
false
false
false
alexfeng/BubbleTransition
Source/BubbleTransition.swift
2
5052
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. */ public class BubbleTransition: NSObject, UIViewControllerAnimatedTransitioning { /** The point that originates the bubble. */ public var startingPoint = CGPointZero { didSet { if let bubble = bubble { bubble.center = startingPoint } } } /** The transition duration. */ public var duration = 0.5 /** The transition direction. Either `.Present` or `.Dismiss.` */ public var transitionMode: BubbleTransitionMode = .Present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ public var bubbleColor: UIColor = .whiteColor() private var bubble: UIView? // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() if transitionMode == .Present { let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let originalCenter = presentedControllerView.center let originalSize = presentedControllerView.frame.size bubble = UIView(frame: frameForBubble(originalCenter, size: originalSize, start: startingPoint)) bubble?.layer.cornerRadius = bubble!.frame.size.height / 2 bubble?.center = startingPoint bubble?.transform = CGAffineTransformMakeScale(0.001, 0.001) bubble?.backgroundColor = bubbleColor containerView.addSubview(bubble!) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animateWithDuration(duration, animations: { self.bubble?.transform = CGAffineTransformIdentity presentedControllerView.transform = CGAffineTransformIdentity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter }) { (_) in transitionContext.completeTransition(true) } } else { let key = (transitionMode == .Pop) ? UITransitionContextToViewKey : UITransitionContextFromViewKey let returningControllerView = transitionContext.viewForKey(key)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size if let bubble = bubble { bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = startingPoint } UIView.animateWithDuration(duration, animations: { self.bubble?.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.transform = CGAffineTransformMakeScale(0.001, 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 if self.transitionMode == .Pop { containerView.insertSubview(returningControllerView, belowSubview: returningControllerView) containerView.insertSubview(self.bubble!, belowSubview: returningControllerView) } }) { (_) in returningControllerView.removeFromSuperview() self.bubble?.removeFromSuperview() transitionContext.completeTransition(true) } } } /** The possible directions of the transition */ @objc public enum BubbleTransitionMode: Int { case Present, Dismiss, Pop } } private extension BubbleTransition { private func frameForBubble(originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x); let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2; let size = CGSize(width: offset, height: offset) return CGRect(origin: CGPointZero, size: size) } }
mit
9b697defa0101d98d267a82daf8a6af2
37.564885
111
0.645091
6
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat.ShareExtension/Rooms/SERoomsViewController.swift
1
3969
// // SERoomsViewController.swift // Rocket.Chat.ShareExtension // // Created by Matheus Cardoso on 2/28/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import Social final class SERoomsViewController: SEViewController { private var viewModel = SERoomsViewModel.emptyState { didSet { title = viewModel.title navigationItem.searchController?.searchBar.text = viewModel.searchText navigationItem.searchController?.searchBar.showsCancelButton = viewModel.showsCancelButton tableView.reloadData() } } @IBOutlet weak var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self tableView.register(SERoomCell.self) tableView.register(SEServerCell.self) } } override func viewDidLoad() { super.viewDidLoad() let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.delegate = self searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false navigationItem.searchController = searchController tableView.keyboardDismissMode = .interactive } override func stateUpdated(_ state: SEState) { super.stateUpdated(state) viewModel = SERoomsViewModel(state: state) } @IBAction func cancelButtonPressed(_ sender: Any) { store.dispatch(.finish) } } // MARK: UISearchBarDelegate extension SERoomsViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { store.dispatch(.setSearchRooms(.started)) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { store.dispatch(.setSearchRooms(.none)) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { store.dispatch(.setSearchRooms(.none)) return } store.dispatch(.setSearchRooms(.searching(searchText))) } } // MARK: UITableViewDataSource extension SERoomsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRowsInSection(section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellModel = viewModel.cellForRowAt(indexPath) let cell: UITableViewCell if let cellModel = cellModel as? SEServerCellModel { let serverCell = tableView.dequeue(SEServerCell.self, forIndexPath: indexPath) serverCell.cellModel = cellModel cell = serverCell } else if let cellModel = cellModel as? SERoomCellModel { let roomCell = tableView.dequeue(SERoomCell.self, forIndexPath: indexPath) roomCell.cellModel = cellModel cell = roomCell } else { return UITableViewCell(style: .default, reuseIdentifier: cellModel.reuseIdentifier) } cell.accessoryType = .disclosureIndicator return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(viewModel.heightForRowAt(indexPath)) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForHeaderInSection(section) } } // MARK: UITableViewDelegate extension SERoomsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { viewModel.didSelectRowAt(indexPath) tableView.deselectRow(at: indexPath, animated: true) } }
mit
92232b0eadaf3116a9a69e6fea1685f5
31
102
0.690524
5.488243
false
false
false
false
AllenConquest/emonIOS
emonIOS/ViewController.swift
1
8412
// // DetailViewController.swift // emonIOS // // Created by Allen Conquest on 25/07/2015. // Copyright (c) 2015 Allen Conquest. All rights reserved. // import UIKit import SwiftyJSON import InAppSettingsKit import Charts class ViewController: UICollectionViewController, UIPopoverPresentationControllerDelegate, UIGestureRecognizerDelegate { var account: EmonAccount! var feedViews = [FeedView]() var feeds = [Feed]() var timer = NSTimer() var appSettingsViewController: IASKAppSettingsViewController! var names = [String]() var values = [Double]() @IBAction func displaySettings(sender: UIBarButtonItem) { print("This will display the settings window") _ = UINavigationController(rootViewController: appSettingsViewController) self.navigationController?.pushViewController(appSettingsViewController, animated:true) } @IBAction func addButton(sender: UIBarButtonItem) { } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return feedViews.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FeedCell", forIndexPath: indexPath) as! FeedCollectionViewCell cell.title.text = feedViews[indexPath.row].label.text! cell.value.text = "\(feedViews[indexPath.row].value.text!)" cell.backgroundColor = UIColor.whiteColor() return cell } func processFeeds(json: JSON, error: NSError?) { if error != nil { // TODO: improve error handling let alert = UIAlertController(title: "Error", message: "Could not load Data :( \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { print (json) if let feedArray = json.array { for item in feedArray { let feed = Feed(item: item) feeds.append(feed) if let unwrappedFeed = Persist.load(feed.name) as? Feed { let view = addFeedView() view.addCustomView(feed) feed.position = unwrappedFeed.position view.center = feed.position self.view.addSubview(view) self.feedViews.append(view) self.names.append(feed.name) self.values.append(Double(feed.value)) } } collectionView?.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. appSettingsViewController = IASKAppSettingsViewController(style: UITableViewStyle.Grouped) appSettingsViewController.showDoneButton = false appSettingsViewController.showCreditsFooter = false account = EmonAccount(completion: processFeeds) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleResetTapGesture:") tapGestureRecognizer.delegate = self view.addGestureRecognizer(tapGestureRecognizer) NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingDidChange:", name: kIASKAppSettingChanged, object: nil) } override func viewWillAppear(animated: Bool) { let timeInterval = IASKSettingsStoreUserDefaults().doubleForKey("refresh_preference") timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "updateInfo:", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } override func viewWillDisappear(animated: Bool) { timer.invalidate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: kIASKAppSettingChanged notification func settingDidChange(notification: NSNotification) { let key = notification.object as! String switch key { // case "refresh_preference": // let timeInterval = IASKSettingsStoreUserDefaults().doubleForKey("refresh_preference") // timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: "updateInfo:", userInfo: nil, repeats: true) default: print("Change key: \(key)") } } func updateInfo(timer: NSTimer) { for view in feedViews { account.refreshFeed(view.viewFeed!.id, completion: { (json, error) in print("\(view.viewFeed?.name): \(json)") view.value.text = "\(json)" }) } collectionView?.reloadData() } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if touch.view == self.view { return true } return false } func handleResetTapGesture(sender: UIPanGestureRecognizer) { if sender.state == .Ended { for view in feedViews { view.stopJiggling() } } } func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) { //do some stuff from the popover print ("Popover closing", terminator: "") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showAddLabel" { if let controller = segue.destinationViewController as? UIViewController { if let content = controller.popoverPresentationController?.presentedViewController { if let contentVC = (content as! UINavigationController).topViewController as? AddLabelViewController { contentVC.account = account contentVC.feeds = feeds } } } } } @IBAction func unwindToVC(segue:UIStoryboardSegue) { if segue.sourceViewController .isKindOfClass(AddLabelViewController) { if let controller = segue.sourceViewController as? AddLabelViewController { controller.dismissViewControllerAnimated(true, completion: { if let feed = controller.pickedFeed { let view = self.addFeedView() view.addCustomView(feed) self.view.addSubview(view) self.feedViews.append(view) view.center = CGPointMake(40, 120) feed.position = view.center let success = Persist.save(feed.name, object: feed) print(success) } }) } } } // Add drop shadow effect on custom view func addFeedView() -> FeedView { let superview = FeedView(frame: CGRectMake(0, 0, 420, 80)) let shadowView = UIView(frame: CGRectMake(10, 10, 400, 60)) shadowView.layer.shadowColor = UIColor.blackColor().CGColor shadowView.layer.shadowOffset = CGSizeZero shadowView.layer.shadowOpacity = 0.5 shadowView.layer.shadowRadius = 5 let view = UIView(frame: shadowView.bounds) view.backgroundColor = UIColor.whiteColor() view.layer.cornerRadius = 10.0 view.layer.borderColor = UIColor.grayColor().CGColor view.layer.borderWidth = 0.5 view.clipsToBounds = true shadowView.addSubview(view) superview.addSubview(shadowView) return superview } }
gpl-2.0
830d20c1111fa9f98355ba249d2efc45
37.067873
169
0.60592
5.683784
false
false
false
false
walamoonbeam/SoundYak
SoundYak/SoundYak/YakPostObject.swift
1
1374
// // YakPostObject.swift // SoundYak // // Created by Michael Zuccarino on 11/25/14. // Copyright (c) 2014 Michael Zuccarino. All rights reserved. // import UIKit class YakPostObject: NSObject { var originalJSON:NSDictionary! var postName:NSString! var upvotes:NSInteger! var downvotes:NSInteger! var tags:NSArray! var timestamp:NSString! var songid:NSInteger! var posturl:NSString! } func initWithAJSONObject(jsonObj:NSDictionary!) -> YakPostObject { var yak:YakPostObject! = YakPostObject() NSLog("read JSON %@",jsonObj.valueForKey("postname")as NSString) NSLog("creating yak post object %@", jsonObj) yak.originalJSON = jsonObj NSLog("set original json") yak.postName = jsonObj.valueForKey("postname") as NSString NSLog("read postname") yak.upvotes = jsonObj.valueForKey("upvotes") as NSInteger NSLog("read upvotes") yak.downvotes = jsonObj.valueForKey("downvotes") as NSInteger NSLog("read downvotes") yak.tags = jsonObj.objectForKey("tags") as NSArray NSLog("read tags") yak.timestamp = jsonObj.valueForKey("timestamp") as NSString NSLog("read timestamp") yak.songid = jsonObj.valueForKey("songid") as NSInteger yak.posturl = jsonObj.valueForKey("posturl") as NSString NSLog("finished conforming json object, finalstruct:\n%@",yak) return yak }
apache-2.0
bbb04f3f1141a966868d1972f1d9c223
30.25
72
0.70524
3.806094
false
false
false
false
Senspark/ee-x
src/ios/ee/ads/ViewHelper.swift
1
2439
// // ViewHelper.swift // ee-x-366f64ba // // Created by eps on 6/24/20. // import Foundation class ViewHelper { private class func applyPosition(_ view: UIView, _ value: CGPoint) { Thread.runOnMainThread { var frame = view.frame frame.origin = value view.frame = frame } } private class func applySize(_ view: UIView, _ value: CGSize) { Thread.runOnMainThread { var frame = view.frame frame.size = value view.frame = frame } } private class func applyVisible(_ view: UIView, _ value: Bool) { Thread.runOnMainThread { view.isHidden = !value } } private var _view: UIView? private var _position = CGPoint(x: 0, y: 0) private var _size = CGSize(width: 0, height: 0) private var _visible = false init(_ initialPosition: CGPoint, _ initialSize: CGSize, _ initialVisible: Bool) { position = initialPosition size = initialSize isVisible = initialVisible } var view: UIView? { get { return _view } set(value) { _view = value if let view = value { ViewHelper.applyPosition(view, position) ViewHelper.applySize(view, size) ViewHelper.applyVisible(view, isVisible) } } } var isVisible: Bool { get { return _visible } set(value) { _visible = value if let view = view { ViewHelper.applyVisible(view, value) } } } var position: CGPoint { get { return _position } set(value) { let position = CGPoint(x: Double(Utils.convertPixelsToDp(Float(value.x))), y: Double(Utils.convertPixelsToDp(Float(value.y)))) _position = position if let view = view { ViewHelper.applyPosition(view, position) } } } var size: CGSize { get { return _size } set(value) { let size = CGSize(width: Double(Utils.convertPixelsToDp(Float(value.width))), height: Double(Utils.convertPixelsToDp(Float(value.height)))) _size = size if let view = view { ViewHelper.applySize(view, size) } } } }
mit
6906609e2c2f40d19831e6d962a24978
25.802198
91
0.519065
4.434545
false
false
false
false
grigaci/WallpapersCollectionView
WallpapersCollectionView/WallpapersCollectionView/Classes/AppDelegate.swift
1
6428
// // AppDelegate.swift // WallpapersCollectionView // // Created by Bogdan Iusco on 8/9/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.makeKeyAndVisible() self.window!.backgroundColor = UIColor.whiteColor() self.window!.rootViewController = UINavigationController(rootViewController: BITransylvaniaPhotosViewController()) return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.grigaci.WallpapersCollectionView" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("WallpapersCollectionView", withExtension: "momd") return NSManagedObjectModel(contentsOfURL: modelURL!)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("WallpapersCollectionView.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
c1b54f0ed14f70a27ab09641ea7696bc
55.385965
290
0.716553
5.822464
false
false
false
false
enstulen/ARKitAnimation
Pods/ARCharts/ARCharts/ARBarChart.swift
3
18555
// // ARBarChart.swift // ARBarCharts // // Created by Bobo on 7/15/17. // Copyright © 2017 Boris Emorine. All rights reserved. // import Foundation import SceneKit import SpriteKit public class ARBarChart: SCNNode { public var dataSource: ARBarChartDataSource? public var delegate: ARBarChartDelegate? public var size: SCNVector3! public var animationType: ARChartPresenter.AnimationType? { didSet { updatePresenter() } } public var animationDuration = 1.0 { didSet { updatePresenter() } } private var presenter: ARChartPresenter! private var highlighter: ARChartHighlighter! public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init() { super.init() } public func reloadGraph() { draw() } // TODO: Cache (with lazy?) private var numberOfSeries: Int? { get { return self.dataSource?.numberOfSeries(in: self) } } // TODO: Cache (with lazy?) private var maxNumberOfIndices: Int? { get { guard let numberOfSeries = self.numberOfSeries, let dataSource = self.dataSource else { return nil } return Array(0..<numberOfSeries).map({ dataSource.barChart(self, numberOfValuesInSeries: $0) }).max() } } // TODO: Cache (lazy?) private var minAndMaxChartValues: (minValue: Double, maxValue: Double)? { get { guard let dataSource = self.dataSource else { return nil } var minValue = Double.greatestFiniteMagnitude var maxValue = Double.leastNormalMagnitude var didProcessValue = false for series in 0 ..< dataSource.numberOfSeries(in: self) { for index in 0 ..< dataSource.barChart(self, numberOfValuesInSeries: series) { let value = dataSource.barChart(self, valueAtIndex: index, forSeries: series) minValue = min(minValue, value) maxValue = max(maxValue, value) didProcessValue = true } } guard didProcessValue == true else { return nil } return (minValue, maxValue) } } public var minValue: Double? public var maxValue: Double? /** * Render the chart in the `SCNView`. */ public func draw() { guard let dataSource = dataSource, let delegate = delegate, let numberOfSeries = self.numberOfSeries, let maxNumberOfIndices = self.maxNumberOfIndices, let size = self.size else { fatalError("Could not find values for dataSource, delegate, numberOfSeries, and maxNumberOfIndices.") } guard let minValue = self.minValue ?? self.minAndMaxChartValues?.minValue, let maxValue = self.maxValue ?? self.minAndMaxChartValues?.maxValue, minValue < maxValue else { fatalError("Invalid chart values detected (minValue >= maxValue)") } guard let spaceForSeriesLabels = self.delegate?.spaceForSeriesLabels(in: self), spaceForSeriesLabels >= 0.0 && spaceForSeriesLabels <= 1.0 else { fatalError("ARBarChartDelegate method spaceForSeriesLabels must return a value between 0.0 and 1.0") } guard let spaceForIndexLabels = self.delegate?.spaceForIndexLabels(in: self), spaceForIndexLabels >= 0.0 && spaceForIndexLabels <= 1.0 else { fatalError("ARBarChartDelegate method spaceForIndexLabels must return a value between 0.0 and 1.0") } let sizeAvailableForBars = SCNVector3(x: size.x * (1.0 - spaceForSeriesLabels), y: size.y, z: size.z * (1.0 - spaceForIndexLabels)) let biggestValueRange = maxValue - minValue let barLength = self.seriesSize(withNumberOfSeries: numberOfSeries, zSizeAvailableForBars: sizeAvailableForBars.z) let barWidth = self.indexSize(withNumberOfIndices: maxNumberOfIndices, xSizeAvailableForBars: sizeAvailableForBars.x) let maxBarHeight = sizeAvailableForBars.y / Float(biggestValueRange) let xShift = size.x * (spaceForSeriesLabels - 0.5) let zShift = size.z * (spaceForIndexLabels - 0.5) var previousZPosition: Float = 0.0 for series in 0..<numberOfSeries { let zPosition = self.zPosition(forSeries: series, previousZPosition, barLength) var previousXPosition: Float = 0.0 for index in 0..<dataSource.barChart(self, numberOfValuesInSeries: series) { let value = dataSource.barChart(self, valueAtIndex: index, forSeries: series) let barHeight = Float(value) * maxBarHeight let startingBarHeight = animationType == .grow || animationType == .progressiveGrow ? 0.0 : barHeight let barOpacity = delegate.barChart(self, opacityForBarAtIndex: index, forSeries: series) let startingBarOpacity = animationType == .fade || animationType == .progressiveFade ? 0.0 : opacity let barChamferRadius = min(barLength, barWidth) * delegate.barChart(self, chamferRadiusForBarAtIndex: index, forSeries: series) let barBox = SCNBox(width: CGFloat(barWidth), height: CGFloat(startingBarHeight), length: CGFloat(barLength), chamferRadius: CGFloat(barChamferRadius)) let barNode = ARBarChartBar(geometry: barBox, index: index, series: series, value: value, finalHeight: barHeight, finalOpacity: barOpacity) barNode.opacity = CGFloat(startingBarOpacity) let yPosition = 0.5 * Float(value) * Float(maxBarHeight) let startingYPosition = (animationType == .grow || animationType == .progressiveGrow) ? 0.0 : yPosition let xPosition = self.xPosition(forIndex: index, previousXPosition, barWidth) barNode.position = SCNVector3(x: xPosition + xShift, y: startingYPosition, z: zPosition + zShift) let barMaterial = delegate.barChart(self, materialForBarAtIndex: index, forSeries: series) barNode.geometry?.firstMaterial = barMaterial self.addChildNode(barNode) if series == 0 { self.addLabel(forIndex: index, atXPosition: xPosition + xShift, withMaxHeight: barWidth) } previousXPosition = xPosition presenter?.addAnimation(to: barNode, in: self) } self.addLabel(forSeries: series, atZPosition: zPosition + zShift, withMaxHeight: barLength) previousZPosition = zPosition } } /** * Highlight a bar at a specific index within a specific series. * - parameter index: The index location (X axis) of the bar to highlight. * - parameter series: The series location (Z axis) of the bar to highlight. * - parameter animationStyle: Style of animation to use during highlighting. * This same animation style will be used to reverse the highlighting. * - parameter animationDuration: Duration of highlighting animation. * This same duration will also be used to reverse the highlighting */ public func highlightBar(atIndex index: Int, forSeries series: Int, withAnimationStyle animationStyle: ARChartHighlighter.AnimationStyle, withAnimationDuration animationDuration: TimeInterval) { guard highlighter == nil else { return } highlighter = ARChartHighlighter(animationStyle: animationStyle, animationDuration: animationDuration) highlighter.highlight(self, atIndex: index, forSeries: series) } /** * Highlight all bars in a specific series. * - parameter series: The series location (Z axis) of the bars to highlight. * - parameter animationStyle: Style of animation to use during highlighting. * This same animation style will be used to reverse the highlighting. * - parameter animationDuration: Duration of highlighting animation. * This same duration will also be used to reverse the highlighting. */ public func highlightSeries(_ series: Int, withAnimationStyle animationStyle: ARChartHighlighter.AnimationStyle, withAnimationDuration animationDuration: TimeInterval) { guard highlighter == nil else { return } highlighter = ARChartHighlighter(animationStyle: animationStyle, animationDuration: animationDuration) highlighter.highlight(self, atIndex: nil, forSeries: series) } /** * Highlight all bars at a specific index. * - parameter series: The series location (Z axis) of the bars to highlight. * - parameter animationStyle: Style of animation to use during highlighting. * This same animation style will be used to reverse the highlighting. * - parameter animationDuration: Duration of highlighting animation. * This same duration will also be used to reverse the highlighting. */ public func highlightIndex(_ index: Int, withAnimationStyle animationStyle: ARChartHighlighter.AnimationStyle, withAnimationDuration animationDuration: TimeInterval) { guard highlighter == nil else { return } highlighter = ARChartHighlighter(animationStyle: animationStyle, animationDuration: animationDuration) highlighter.highlight(self, atIndex: index, forSeries: nil) } /** * Remove any highlighting currently active on this chart. */ public func unhighlight() { guard self.highlighter != nil else { return } self.highlighter.unhighlight(self) self.highlighter = nil } /** * Update the presenter to use the new animation type. Called on `didSet` for member `animationType`. */ private func updatePresenter() { if let animationType = self.animationType { if presenter != nil { presenter.animationType = animationType presenter.animationDuration = animationDuration } else { presenter = ARChartPresenter(animationType: animationType, animationDuration: animationDuration) } } } /** * Calculates the actual size available for one series on the graph. * - parameter numberOfSeries: The number of series on the graph. * - parameter availableZSize: The available size on the Z axis of the graph. * - returns: The actual size available for one series on the graph. */ private func seriesSize(withNumberOfSeries numberOfSeries: Int, zSizeAvailableForBars availableZSize: Float) -> Float { var totalGapCoefficient: Float = 0.0 if let delegate = self.delegate { totalGapCoefficient = Array(0 ..< numberOfSeries).reduce(0, { (total, current) -> Float in total + delegate.barChart(self, gapSizeAfterSeries: current) }) } return availableZSize / (Float(numberOfSeries) + totalGapCoefficient) } /** * Calculates the actual size available for one index on the graph. * - parameter numberOfIndices: The number of indices on the graph. * - parameter availableXSize: The available size on the X axis of the graph. * - returns: The actual size available for one index on the graph. */ private func indexSize(withNumberOfIndices numberOfIndices: Int, xSizeAvailableForBars availableXSize: Float) -> Float { var totalGapCoefficient: Float = 0.0 if let delegate = self.delegate { totalGapCoefficient = Array(0 ..< numberOfIndices).reduce(0, { (total, current) -> Float in total + delegate.barChart(self, gapSizeAfterIndex: current) }) } return availableXSize / (Float(numberOfIndices) + totalGapCoefficient) } /** * Calculates the X position (Series Axis) for a specific index. * - parameter series: The index that requires the X position. * - parameter previousIndexXPosition: The X position of the previous index. This is useful for optimization. * - parameter indexSize: The acutal size available for one index on the graph. * - returns: The X position for a given index. */ private func xPosition(forIndex index: Int, _ previousIndexXPosition: Float, _ indexSize: Float) -> Float { let gapSize: Float = index == 0 ? 0.0 : self.delegate?.barChart(self, gapSizeAfterIndex: index - 1) ?? 0.0 return previousIndexXPosition + indexSize + indexSize * gapSize } /** * Calculates the Z position (Series Axis) for a specific series. * - parameter series: The series that requires the Z position. * - parameter previousSeriesZPosition: The Z position of the previous series. This is useful for optimization. * - parameter seriesSize: The acutal size available for one series on the graph. * - returns: The Z position for a given series. */ private func zPosition(forSeries series: Int, _ previousSeriesZPosition: Float, _ seriesSize: Float) -> Float { let gapSize: Float = series == 0 ? 0.0 : self.delegate?.barChart(self, gapSizeAfterSeries: series - 1) ?? 0.0 return previousSeriesZPosition + seriesSize + seriesSize * gapSize } /** * Add a series label to the Z axis for a given series and at a given Z position. * - parameter series: The series to be labeled. * - parameter zPosition: The Z position of the center of the bars for the specified series. */ private func addLabel(forSeries series: Int, atZPosition zPosition: Float, withMaxHeight maxHeight: Float) { if let seriesLabelText = dataSource!.barChart(self, labelForSeries: series) { let seriesLabel = SCNText(string: seriesLabelText, extrusionDepth: 0.0) seriesLabel.truncationMode = kCATruncationNone seriesLabel.alignmentMode = kCAAlignmentCenter seriesLabel.font = UIFont.systemFont(ofSize: 10.0) seriesLabel.firstMaterial!.isDoubleSided = true seriesLabel.firstMaterial!.diffuse.contents = delegate!.barChart(self, colorForLabelForSeries: series) let backgroundColor = delegate!.barChart(self, backgroundColorForLabelForSeries: series) let seriesLabelNode = ARChartLabel(text: seriesLabel, type: .series, id: series, backgroundColor: backgroundColor) let unscaledLabelWidth = seriesLabelNode.boundingBox.max.x - seriesLabelNode.boundingBox.min.x let desiredLabelWidth = size.x * delegate!.spaceForSeriesLabels(in: self) let unscaledLabelHeight = seriesLabelNode.boundingBox.max.y - seriesLabelNode.boundingBox.min.y let labelScale = min(desiredLabelWidth / unscaledLabelWidth, maxHeight / unscaledLabelHeight) seriesLabelNode.scale = SCNVector3(labelScale, labelScale, labelScale) let zShift = 0.5 * maxHeight - (maxHeight - labelScale * unscaledLabelHeight) let position = SCNVector3(x: -0.5 * size.x, y: 0.0, z: zPosition + zShift) seriesLabelNode.position = position seriesLabelNode.eulerAngles = SCNVector3(-0.5 * Float.pi, 0.0, 0.0) self.addChildNode(seriesLabelNode) } } /** * Add an index label to the X axis for a given index and at a given X position. * - parameter index: The index (X axis) to be labeled. * - parameter zPosition: The Z position of the center of the bars for the specified series. */ private func addLabel(forIndex index: Int, atXPosition xPosition: Float, withMaxHeight maxHeight: Float) { if let indexLabelText = dataSource!.barChart(self, labelForValuesAtIndex: index) { let indexLabel = SCNText(string: indexLabelText, extrusionDepth: 0.0) indexLabel.truncationMode = kCATruncationNone indexLabel.alignmentMode = kCAAlignmentCenter indexLabel.font = UIFont.systemFont(ofSize: 10.0) indexLabel.firstMaterial!.isDoubleSided = true indexLabel.firstMaterial!.diffuse.contents = delegate!.barChart(self, colorForLabelForValuesAtIndex: index) let backgroundColor = delegate!.barChart(self, backgroundColorForLabelForValuesAtIndex: index) let indexLabelNode = ARChartLabel(text: indexLabel, type: .index, id: index, backgroundColor: backgroundColor) let unscaledLabelWidth = indexLabelNode.boundingBox.max.x - indexLabelNode.boundingBox.min.x let desiredLabelWidth = size.z * delegate!.spaceForIndexLabels(in: self) let unscaledLabelHeight = indexLabelNode.boundingBox.max.y - indexLabelNode.boundingBox.min.y let labelScale = min(desiredLabelWidth / unscaledLabelWidth, maxHeight / unscaledLabelHeight) indexLabelNode.scale = SCNVector3(labelScale, labelScale, labelScale) let xShift = (maxHeight - labelScale * unscaledLabelHeight) - 0.5 * maxHeight let position = SCNVector3(x: xPosition + xShift, y: 0.0, z: -0.5 * size.z) indexLabelNode.position = position indexLabelNode.eulerAngles = SCNVector3(-0.5 * Float.pi, -0.5 * Float.pi, 0.0) self.addChildNode(indexLabelNode) } } }
mit
f7ed2cc10894cfe0f5e43e079e059820
47.826316
143
0.623801
5.093055
false
false
false
false
cmidt-veasna/SwiftFlatbuffer
XCodeFlatbuffer/FlatbufferSwift/Sources/struct.swift
1
1495
// // struct.swift // FlatbufferSwift // // Created by Veasna Sreng on 2/14/17. // Copyright © 2017 Veasna Sreng. All rights reserved. // import Foundation public class Struct { var position: Int = 0 var data: Data? required public init() {} open func __init(at: Int, withData: inout Data) { self.position = at self.data = withData } open func __assign(at: Int, withData: inout Data) -> Struct { self.__init(at: at, withData: &withData) return self } open func __offset(virtualTableOffset: Int) -> Int { if data != nil, let val = (data?.getOffset(at: position)) { let vtable = position - val let result = virtualTableOffset < data!.getVirtualTaleOffset(at: vtable) ? data!.getVirtualTaleOffset(at: vtable + virtualTableOffset) : 0 return result } return 0 } open static func __offset(virtualTableOffset: Int, offset: Int, data: inout Data) -> Int { let vtable = data.count - offset; return data.getVirtualTaleOffset(at: vtable + virtualTableOffset - data.getVirtualTaleOffset(at: vtable)) + vtable } open func getStruct<T: Struct>(byOffset: Int) -> T { return getStruct(byOffset: byOffset, withPrevious: T()) } open func getStruct<T: Struct>(byOffset: Int, withPrevious: T) -> T { return withPrevious.__assign(at: position + byOffset, withData: &data!) as! T } }
apache-2.0
fdd362225bfa0fac25948d30cee680b8
28.88
150
0.609103
3.880519
false
false
false
false
away4m/Vendors
Vendors/Extensions/WKWebView.swift
1
3526
// // WKWebView.swift // Pods // // Created by away4m on 12/31/16. // // import Foundation import WebKit extension WKWebView { // for both Text Field and Text Area func javaScriptInjectionTextFieldBy(id: String, value: String, completionHandler: ((Any?, Error?) -> Void)?) { let js = "document.getElementById('" + id + "').value = '" + value + "'" evaluateJavaScript(js, completionHandler: completionHandler) } func labelTextBy(id: String, completion: @escaping (String?) -> Void) { let js = "document.getElementById('\(id)').textContent" evaluateJavaScript( js, completionHandler: { result, error in if error == nil, let text = result as? String { completion(text) } else { completion(nil) } } ) } func labelTextBy(name: String, completion: @escaping (String?) -> Void) { let js = "document.getElementsByName('\(name)')[0].textContent" evaluateJavaScript( js, completionHandler: { result, error in if error == nil, let text = result as? String { completion(text) } else { completion(nil) } } ) } func clickElememtBy(className name: String, completionHandler: ((Any?, Error?) -> Void)?) { let js = "document.getElementsByClassName('\(name)')[0];element.onclick = function() {};" evaluateJavaScript(js, completionHandler: completionHandler) } func clickButtonBy(id: String, completionHandler: ((Any?, Error?) -> Void)?) { let js = "document.getElementById('\(id)').click();" evaluateJavaScript(js, completionHandler: completionHandler) } func scrollToBottom(_ completion: ((Bool) -> Void)? = nil) { evaluateJavaScript( "document.body.offsetHeight", completionHandler: { value, error in guard let height = value as? Double else { return } let js = "window.scrollBy(0, \(Int(height)))" self.evaluateJavaScript( js, completionHandler: { _, error in completion?(error == nil) } ) } ) } func positionOfElementById(_ id: String, completion: @escaping (CGRect?) -> Void) { let js = "function f(){ var r = document.getElementById('\(id)').getBoundingClientRect(); return '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } f();" evaluateJavaScript( js, completionHandler: { result, error in guard error == nil else { completion(nil) return } guard let str = result as? String else { completion(nil) return } let rect = NSCoder.cgRect(for: str) completion(rect != CGRect.zero ? rect : nil) } ) } } extension HTTPCookieStorage { func deleteAll() { cookies?.forEach { deleteCookie($0) } } } @available(iOS 9.0, *) extension WKWebsiteDataStore { func removeAllData() { let types = WKWebsiteDataStore.allWebsiteDataTypes() let date = Date(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: date, completionHandler: {}) } }
mit
92cc07022d83b3dae577f07e0b95839c
29.396552
167
0.53772
4.797279
false
false
false
false
kylef/Starship
Starship/ViewControllers/ResourceViewController.swift
1
6565
// // ResourceViewController.swift // Starship // // Created by Kyle Fuller on 01/07/2015. // Copyright (c) 2015 Kyle Fuller. All rights reserved. // import UIKit import SVProgressHUD enum ResourceViewControllerSection { case Attributes case EmbeddedResources case Transitions } class ResourceViewController : UITableViewController { var viewModel:ResourceViewModel? { didSet { if isViewLoaded() { updateState() } } } var sections:[ResourceViewControllerSection] { var sections = [ResourceViewControllerSection]() if viewModel?.numberOfAttributes > 0 { sections.append(.Attributes) } if viewModel?.numberOfEmbeddedResources > 0 { sections.append(.EmbeddedResources) } if viewModel?.numberOfTransitions > 0 { sections.append(.Transitions) } return sections } override func viewDidLoad() { super.viewDidLoad() updateState() } func updateState() { if viewModel?.canReload ?? false { if refreshControl == nil { refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action:Selector("reload"), forControlEvents:.ValueChanged) } } else { refreshControl = nil } title = viewModel?.title ?? "Resource" tableView?.reloadData() } func reload() { if let viewModel = viewModel { viewModel.reload { result in self.refreshControl?.endRefreshing() self.updateState() } } else { refreshControl?.endRefreshing() } } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch sections[section] { case .Attributes: return "Attributes" case .EmbeddedResources: return "Embedded Resources" case .Transitions: return "Transitions" } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch sections[section] { case .Attributes: return viewModel?.numberOfAttributes ?? 0 case .EmbeddedResources: return viewModel?.numberOfEmbeddedResources ?? 0 case .Transitions: return viewModel?.numberOfTransitions ?? 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch sections[indexPath.section] { case .Attributes: return cellForAttribute(tableView, index: indexPath.row) case .EmbeddedResources: return cellForEmbeddedResource(tableView, index: indexPath.row) case .Transitions: return cellForTransition(tableView, index: indexPath.row) } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch sections[indexPath.section] { case .Attributes: let title = viewModel?.titleForAttribute(indexPath.row) let value = viewModel?.valueForAttribute(indexPath.row) let alertController = UIAlertController(title: title, message: value, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default) { action in tableView.deselectRowAtIndexPath(indexPath, animated: true) } alertController.addAction(action) presentViewController(alertController, animated: true, completion: nil) case .EmbeddedResources: let viewController = ResourceViewController(style: .Grouped) viewController.viewModel = viewModel?.viewModelForEmbeddedResource(indexPath.row) self.navigationController?.pushViewController(viewController, animated: true) case .Transitions: if !presentTransition(indexPath.row) { performTransition(indexPath.row) tableView.deselectRowAtIndexPath(indexPath, animated: true) } } } // MARK: UITableView func cellForAttribute(tableView:UITableView, index:Int) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Attribute") ?? UITableViewCell(style: .Value1, reuseIdentifier: "Attribute") cell.textLabel?.text = viewModel?.titleForAttribute(index) cell.detailTextLabel?.text = viewModel?.valueForAttribute(index) return cell } func cellForEmbeddedResource(tableView:UITableView, index:Int) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Resource") ?? UITableViewCell(style: .Value1, reuseIdentifier: "Resource") if let title = viewModel?.titleForEmbeddedResource(index) { cell.textLabel?.text = title cell.detailTextLabel?.text = viewModel?.relationForEmbeddedResource(index) } else { cell.textLabel?.text = viewModel?.relationForEmbeddedResource(index) cell.detailTextLabel?.text = nil } return cell } func cellForTransition(tableView:UITableView, index:Int) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Transition") ?? UITableViewCell(style: .Default, reuseIdentifier: "Transition") cell.textLabel?.text = viewModel?.titleForTransition(index) return cell } func presentTransition(index:Int) -> Bool { if let viewModel = viewModel?.viewModelForTransition(index) { let viewController = TransitionViewController(style: .Grouped) viewController.title = self.viewModel?.titleForTransition(index) viewController.viewModel = viewModel navigationController?.pushViewController(viewController, animated: true) return true } return false } func performTransition(index:Int) { SVProgressHUD.showWithMaskType(.Gradient) viewModel?.performTransition(index) { result in SVProgressHUD.dismiss() switch result { case .Success(let viewModel): let viewController = ResourceViewController(style: .Grouped) viewController.viewModel = viewModel self.navigationController?.pushViewController(viewController, animated: true) case .Refresh: self.updateState() case .Failure(let error): let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Re-try", style: .Default) { action in self.performTransition(index) }) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } } }
bsd-2-clause
f8ec9eec4324cc639cf99a88eff7b05e
31.339901
139
0.710434
5.07734
false
false
false
false
zzycami/firefox-ios
Token/TokenServerClient.swift
3
5225
/* 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 Alamofire public let PROD_TOKEN_SERVER_ENDPOINT = "https://token.services.mozilla.com/1.0/sync/1.5"; public let STAGE_TOKEN_SERVER_ENDPOINT = "https://token.stage.mozaws.net/1.0/sync/1.5"; public let TokenServerClientErrorDomain = "org.mozilla.token.error" public class TokenServerToken { public let id : String; public let key : String; public let api_endpoint : String; public let uid : UInt32; public init(id: String, key: String, api_endpoint: String, uid: UInt32) { self.id = id self.key = key self.api_endpoint = api_endpoint self.uid = uid } } public class TokenServerClient { public class var requestManager : Alamofire.Manager { struct Static { static let manager : Alamofire.Manager = Alamofire.Manager(configuration: Alamofire.Manager.sharedInstance.session.configuration) } Static.manager.startRequestsImmediately = false return Static.manager } public let url : String public init(endpoint: String? = nil) { self.url = endpoint ?? PROD_TOKEN_SERVER_ENDPOINT } public class func getAudienceForEndpoint(endpoint: String) -> String { let url = NSURL(string: endpoint)! if let port = url.port { return "\(url.scheme!)://\(url.host!):\(port)" } else { return "\(url.scheme!)://\(url.host!)" } } private class func validateJSON(json : JSON) -> Bool { return json["id"].isString && json["key"].isString && json["api_endpoint"].isString && json["uid"].isInt } private class func tokenFromJSON(json: JSON) -> TokenServerToken { let id = json["id"].asString! let key = json["key"].asString! let api_endpoint = json["api_endpoint"].asString! let uid = UInt32(json["uid"].asInt!) return TokenServerToken(id: id, key: key, api_endpoint: api_endpoint, uid: uid) } public class Request { public let queue: dispatch_queue_t private let request : Alamofire.Request private var successBlock: (TokenServerToken -> Void)?; public init(queue: dispatch_queue_t, request: Alamofire.Request) { self.queue = queue ?? dispatch_get_main_queue() self.request = request } public func onSuccess(block: TokenServerToken -> Void) -> Self { self.successBlock = block; return self } public func go(errorBlock: NSError -> Void) { if successBlock == nil { return dispatch_async(queue, { errorBlock(NSError(domain: TokenServerClientErrorDomain, code: -1, userInfo: ["message": "no success handler"])) }) } request.responseJSON { (request, response, json, error) in if let error = error { return dispatch_async(self.queue, { errorBlock(error) }) } if response == nil || json == nil { return dispatch_async(self.queue, { errorBlock(NSError(domain: TokenServerClientErrorDomain, code: -1, userInfo: ["message": "malformed JSON response"])) }) } let json = JSON(json!) let statusCode : Int = response!.statusCode if statusCode != 200 { return dispatch_async(self.queue, { errorBlock(NSError(domain: TokenServerClientErrorDomain, code: -1, userInfo: ["message": "bad response code", "code": statusCode, "body": json.toString(pretty: true)])) }) } if !TokenServerClient.validateJSON(json) { return dispatch_async(self.queue, { errorBlock(NSError(domain: TokenServerClientErrorDomain, code: -1, userInfo: ["message": "invalid token server response"])) }) } let token = TokenServerClient.tokenFromJSON(json) return dispatch_async(self.queue, { self.successBlock!(token) }) } } } public func tokenRequest(queue: dispatch_queue_t? = nil, assertion: String, clientState: String? = nil) -> Request { let URL = NSURL(string: url)! var mutableURLRequest = NSMutableURLRequest(URL: URL) mutableURLRequest.setValue("BrowserID " + assertion, forHTTPHeaderField: "Authorization") if let clientState = clientState { mutableURLRequest.setValue(clientState, forHTTPHeaderField: "X-Client-State") } let manager = TokenServerClient.requestManager let request = manager.request(mutableURLRequest) request.resume() return Request(queue: queue ?? dispatch_get_main_queue(), request: request) } }
mpl-2.0
db6f7a4c37e3b231649d584a4d00a669
36.056738
153
0.581627
4.728507
false
false
false
false
jakeheis/Shout
Tests/ShoutTests/SFTPTests.swift
1
5378
// // SFTPTests.swift // ShoutTests // // Created by Jake Heiser on 3/15/19. // import Shout import XCTest class SFTPTests: XCTestCase { func testDownload() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() let destinationUrl = URL(fileURLWithPath: "/tmp/shout_hostname") if try destinationUrl.checkResourceIsReachable() == true { try FileManager.default.removeItem(at: destinationUrl) } XCTAssertFalse(FileManager.default.fileExists(atPath: destinationUrl.path)) try sftp.download(remotePath: "/etc/hostname", localURL: destinationUrl) XCTAssertTrue(FileManager.default.fileExists(atPath: destinationUrl.path)) XCTAssertTrue(try String(contentsOf: destinationUrl).count > 0) try FileManager.default.removeItem(at: destinationUrl) } } func testUpload() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() try sftp.upload(localURL: URL(fileURLWithPath: String(#file)), remotePath: "/tmp/shout_upload_test.swift") let (status, contents) = try ssh.capture("cat /tmp/shout_upload_test.swift") XCTAssertEqual(status, 0) XCTAssertEqual(contents.components(separatedBy: "\n")[1], "// SFTPTests.swift") XCTAssertEqual(try ssh.execute("rm /tmp/shout_upload_test.swift", silent: false), 0) } } func testCreateDirectory() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() try sftp.createDirectory("/tmp/shout_folder_test") let (status, contents) = try ssh.capture("if test -d /tmp/shout_folder_test; then echo \"exists\"; fi") XCTAssertEqual(status, 0) XCTAssertEqual(contents.components(separatedBy: "\n")[0], "exists") XCTAssertEqual(try ssh.execute("rm -rf /tmp/shout_folder_test", silent: false), 0) } } func testRemoveDirectory() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() // First create directory try sftp.createDirectory("/tmp/shout_folder_test") let (statusC, contentsC) = try ssh.capture("if test -d /tmp/shout_folder_test; then echo \"exists\"; fi") XCTAssertEqual(statusC, 0) XCTAssertEqual(contentsC.components(separatedBy: "\n")[0], "exists") // Then delete try sftp.removeDirectory("/tmp/shout_folder_test") let (statusR, contentsR) = try ssh.capture("if test ! -d /tmp/shout_remove_test; then echo \"removed\"; fi") XCTAssertEqual(statusR, 0) XCTAssertEqual(contentsR.components(separatedBy: "\n")[0], "removed") } } func testRename() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() // Create dummy file let (statusC, _) = try ssh.capture("touch /tmp/shout_rename_test1") XCTAssertEqual(statusC, 0) // Then rename try sftp.rename(src: "/tmp/shout_rename_test1", dest: "/tmp/shout_rename_test2", override: true) // Check if old file is gone let (statusO, contentsO) = try ssh.capture("if test ! -f /tmp/shout_remove_test; then echo \"gone\"; fi") XCTAssertEqual(statusO, 0) XCTAssertEqual(contentsO.components(separatedBy: "\n")[0], "gone") // Check if new file is there let (statusN, contentsN) = try ssh.capture("if test -f /tmp/shout_rename_test2; then echo \"exists\"; fi") XCTAssertEqual(statusN, 0) XCTAssertEqual(contentsN.components(separatedBy: "\n")[0], "exists") XCTAssertEqual(try ssh.execute("rm /tmp/shout_rename_test2", silent: false), 0) } } func testRemove() throws { try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in let sftp = try ssh.openSftp() // Create dummy file let (statusC, _) = try ssh.capture("touch /tmp/shout_remove_test") XCTAssertEqual(statusC, 0) // Remove file try sftp.removeFile("/tmp/shout_remove_test") // Check if old file is gone let (statusR, contentsR) = try ssh.capture("if test ! -f /tmp/shout_remove_test; then echo \"removed\"; fi") XCTAssertEqual(statusR, 0) XCTAssertEqual(contentsR.components(separatedBy: "\n")[0], "removed") } } }
mit
3fb745ef33b2848ed1d0d67e4548d47e
42.370968
126
0.585906
4.422697
false
true
false
false
CosmicMind/MaterialKit
Sources/iOS/RadioButton.swift
1
4297
// // RadioButton.swift // Material // // Created by Orkhan Alikhanov on 12/22/18. // Copyright © 2017 CosmicMind. All rights reserved. // import UIKit open class RadioButton: BaseIconLayerButton { class override var iconLayer: BaseIconLayer { return RadioBoxLayer() } open override func prepare() { super.prepare() addTarget(self, action: #selector(didTap), for: .touchUpInside) } @objc private func didTap() { setSelected(true, animated: true) } } internal class RadioBoxLayer: BaseIconLayer { private let centerDot = CALayer() private let outerCircle = CALayer() override var selectedColor: UIColor { didSet { guard isSelected, isEnabled else { return } outerCircle.borderColor = selectedColor.cgColor centerDot.backgroundColor = selectedColor.cgColor } } override var normalColor: UIColor { didSet { guard !isSelected, isEnabled else { return } outerCircle.borderColor = normalColor.cgColor } } override var disabledColor: UIColor { didSet { guard !isEnabled else { return } outerCircle.borderColor = disabledColor.cgColor if isSelected { centerDot.backgroundColor = disabledColor.cgColor } } } override func prepare() { super.prepare() addSublayer(centerDot) addSublayer(outerCircle) } override func prepareForFirstAnimation() { outerCircle.borderColor = (isEnabled ? (isSelected ? selectedColor : normalColor) : disabledColor).cgColor if !isSelected { centerDot.backgroundColor = (isEnabled ? normalColor : disabledColor).cgColor } outerCircle.borderWidth = outerCircleBorderWidth } override func firstAnimation() { outerCircle.transform = outerCircleScaleToShrink let to = isSelected ? sideLength / 2.0 : outerCircleBorderWidth * percentageOfOuterCircleWidthToStart outerCircle.animate(#keyPath(CALayer.borderWidth), to: to) if !isSelected { centerDot.transform = centerDotScaleForMeeting } } override func prepareForSecondAnimation() { centerDot.transform = isSelected ? centerDotScaleForMeeting : .identity centerDot.backgroundColor = (isSelected ? (isEnabled ? selectedColor : disabledColor) : .clear).cgColor outerCircle.borderWidth = isSelected ? outerCircleBorderWidth * percentageOfOuterCircleWidthToStart : outerCircleFullBorderWidth } override func secondAnimation() { outerCircle.transform = .identity outerCircle.animate(#keyPath(CALayer.borderWidth), to: outerCircleBorderWidth) if isSelected { centerDot.transform = .identity } } override func layoutSublayers() { super.layoutSublayers() guard !isAnimating else { return } centerDot.frame = CGRect(x: centerDotDiameter / 2.0, y: centerDotDiameter / 2.0, width: centerDotDiameter, height: centerDotDiameter) outerCircle.frame.size = CGSize(width: sideLength, height: sideLength) centerDot.cornerRadius = centerDot.bounds.width / 2 outerCircle.cornerRadius = sideLength / 2 outerCircle.borderWidth = outerCircleBorderWidth } } private extension RadioBoxLayer { var percentageOfOuterCircleSizeToShrinkTo: CGFloat { return 0.9 } var percentageOfOuterCircleWidthToStart: CGFloat { return 1 } var outerCircleScaleToShrink: CATransform3D { let s = percentageOfOuterCircleSizeToShrinkTo return CATransform3DMakeScale(s, s, 1) } var centerDotScaleForMeeting: CATransform3D { let s = ((sideLength - 2 * percentageOfOuterCircleWidthToStart * outerCircleBorderWidth) * percentageOfOuterCircleSizeToShrinkTo) / centerDotDiameter return CATransform3DMakeScale(s, s, 1) } var outerCircleFullBorderWidth: CGFloat { return (self.sideLength / 2.0) * 1.1 //without multipling 1.1 a weird plus sign (+) appears sometimes. } var centerDotDiameter: CGFloat { return sideLength / 2.0 } var outerCircleBorderWidth: CGFloat { return sideLength * 0.11 } }
bsd-3-clause
4f347ee54f174baf31c53e03dfa10695
34.504132
157
0.670391
5.213592
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/MovieRecTests/RateTests/RecommendWireFrameTest.swift
1
1363
// // RecommendWireFrameTest.swift // MovieRecTests // // Created by Yujin Cho on 10/23/17. // Copyright © 2017 Yujin Cho. All rights reserved. // import XCTest @testable import MovieRec class RecommendWireFrameTest: XCTestCase { var recommendWireframe = RecommendWireframe() var recommendPresenter = RecommendPresenter() override func setUp() { super.setUp() recommendWireframe.recommendPresenter = recommendPresenter } override func tearDown() { super.tearDown() } func testPresentRecommendInterfaceFromViewController() { let window = UIWindow() let navController = UINavigationController() window.rootViewController = navController recommendWireframe.presentRecommendInterfaceFromViewController(navController) if let rootViewController = window.rootViewController as? UINavigationController { if let recommendViewController = rootViewController.viewControllers.first { XCTAssertNotNil(recommendViewController as? RecommendViewController, "must be a recommend view controller") } else { XCTFail("first view controller must be a view controller") } } else { XCTFail("window must have a rootViewController that is a navigation controller") } } }
mit
99998cf78a35e9d4ddfc57ccd932642e
30.674419
123
0.68649
5.698745
false
true
false
false
hooman/swift
test/Sema/enum_conformance_synthesis.swift
4
12072
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() enum Foo: CaseIterable { case A, B } func foo() { if Foo.A == .B { } var _: Int = Foo.A.hashValue Foo.A.hash(into: &hasher) _ = Foo.allCases Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} } enum Generic<T>: CaseIterable { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } func generic() { if Generic<Foo>.A == .B { } var _: Int = Generic<Foo>.A.hashValue Generic<Foo>.A.hash(into: &hasher) _ = Generic<Foo>.allCases } func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B func hash(into hasher: inout Hasher) {} } func ==(x: CustomHashable, y: CustomHashable) -> Bool { return true } func customHashable() { if CustomHashable.A == .B { } var _: Int = CustomHashable.A.hashValue CustomHashable.A.hash(into: &hasher) } // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { return "" } func invalidCustomHashable() { if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue _ = s var _: Int = InvalidCustomHashable.A.hashValue InvalidCustomHashable.A.hash(into: &hasher) } // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } func getFromOtherFile() -> AlsoFromOtherFile { return .A } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } func useEnumBeforeDeclaration() { // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue if .A == getFromOtherFile() {} if .A == overloadFromOtherFile() {} } // Complex enums are not automatically Equatable, Hashable, or CaseIterable. enum Complex { case A(Int) case B } func complex() { if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}} } // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } func enumWithEquatablePayload() { if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } func enumWithHashablePayload() { _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue EnumWithHashablePayload.A(1).hash(into: &hasher) EnumWithHashablePayload.B("x", 1).hash(into: &hasher) EnumWithHashablePayload.C.hash(into: &hasher) // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}} } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } func genericHashable() { if GenericHashable<String>.A("a") == .B { } var _: Int = GenericHashable<String>.A("a").hashValue } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}} case B } func genericNotHashable() { if GenericNotHashable<String>.A("a") == .B { } let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } // An enum with no cases should also derive conformance. enum NoCases: Hashable {} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} extension Instrument : CaseIterable {} enum UnusedGeneric<T> { case a, b, c } extension UnusedGeneric : CaseIterable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { return true } // No explicit conformance; but it can be derived, for the same-file cases. enum Complex2 { case A(Int) case B } extension Complex2 : Hashable {} extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}} extension FromOtherFile: CaseIterable {} // expected-error {{extension outside of file declaring enum 'FromOtherFile' prevents automatic synthesis of 'allCases' for protocol 'CaseIterable'}} extension CaseIterableAcrossFiles: CaseIterable { public static var allCases: [CaseIterableAcrossFiles] { return [ .A ] } } // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}} } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{extension outside of file declaring enum 'YetOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}} extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}} } // Conditional conformances should be able to be synthesized enum GenericDeriveExtension<T> { case A(T) } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work enum BadGenericDeriveExtension<T> { case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}} //expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}} } extension BadGenericDeriveExtension: Equatable {} // // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} enum UnusedGenericDeriveExtension<T> { case A(AlwaysHashable<T>) } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is disallowed for conditional cases just as it is for // non-conditional ones. extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{extension outside of file declaring generic enum 'GenericOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} enum ImpliedMain: ImplierMain { case a(Int) } extension ImpliedOther: ImplierMain {} // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
0ea0658d822442a8dc2c150c01b45f07
34.610619
209
0.73832
4.032064
false
false
false
false
maxadamski/swift-corelibs-foundation
Foundation/NSFileHandle.swift
5
11416
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public class NSFileHandle : NSObject, NSSecureCoding { internal var _fd: Int32 internal var _closeOnDealloc: Bool internal var _closed: Bool = false /*@NSCopying*/ public var availableData: NSData { NSUnimplemented() } public func readDataToEndOfFile() -> NSData { return readDataOfLength(Int.max) } public func readDataOfLength(length: Int) -> NSData { var statbuf = stat() var dynamicBuffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>() var total = 0 if _closed || fstat(_fd, &statbuf) < 0 { fatalError("Unable to read file") } if statbuf.st_mode & S_IFMT != S_IFREG { /* We get here on sockets, character special files, FIFOs ... */ var currentAllocationSize: size_t = 1024 * 8 dynamicBuffer = UnsafeMutablePointer<UInt8>(malloc(currentAllocationSize)) var remaining = length while remaining > 0 { let amountToRead = min(1024 * 8, remaining) // Make sure there is always at least amountToRead bytes available in the buffer. if (currentAllocationSize - total) < amountToRead { currentAllocationSize *= 2 dynamicBuffer = UnsafeMutablePointer<UInt8>(_CFReallocf(UnsafeMutablePointer<Void>(dynamicBuffer), currentAllocationSize)) if dynamicBuffer == nil { fatalError("unable to allocate backing buffer") } let amtRead = read(_fd, dynamicBuffer.advancedBy(total), amountToRead) if 0 > amtRead { free(dynamicBuffer) fatalError("read failure") } if 0 == amtRead { break // EOF } total += amtRead remaining -= amtRead if total == length { break // We read everything the client asked for. } } } } else { let offset = lseek(_fd, 0, L_INCR) if offset < 0 { fatalError("Unable to fetch current file offset") } if statbuf.st_size > offset { var remaining = size_t(statbuf.st_size - offset) remaining = min(remaining, size_t(length)) dynamicBuffer = UnsafeMutablePointer<UInt8>(malloc(remaining)) if dynamicBuffer == nil { fatalError("Malloc failure") } while remaining > 0 { let count = read(_fd, dynamicBuffer.advancedBy(total), remaining) if count < 0 { free(dynamicBuffer) fatalError("Unable to read from fd") } if count == 0 { break } total += count remaining -= count } } } if length == Int.max && total > 0 { dynamicBuffer = UnsafeMutablePointer<UInt8>(_CFReallocf(UnsafeMutablePointer<Void>(dynamicBuffer), total)) } if (0 == total) { free(dynamicBuffer) } if total > 0 { return NSData(bytesNoCopy: UnsafeMutablePointer<Void>(dynamicBuffer), length: total) } return NSData() } public func writeData(data: NSData) { data.enumerateByteRangesUsingBlock() { (bytes, range, stop) in do { try NSData.writeToFileDescriptor(self._fd, path: nil, buf: bytes, length: range.length) } catch { fatalError("Write failure") } } } // TODO: Error handling. public var offsetInFile: UInt64 { return UInt64(lseek(_fd, 0, L_INCR)) } public func seekToEndOfFile() -> UInt64 { return UInt64(lseek(_fd, 0, L_XTND)) } public func seekToFileOffset(offset: UInt64) { lseek(_fd, off_t(offset), L_SET) } public func truncateFileAtOffset(offset: UInt64) { if lseek(_fd, off_t(offset), L_SET) == 0 { ftruncate(_fd, off_t(offset)) } } public func synchronizeFile() { fsync(_fd) } public func closeFile() { if !_closed { close(_fd) _closed = true } } public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) { _fd = fd _closeOnDealloc = closeopt } internal init?(path: String, flags: Int32, createMode: Int) { _fd = _CFOpenFileWithMode(path, flags, mode_t(createMode)) _closeOnDealloc = true super.init() if _fd < 0 { return nil } } deinit { if _fd >= 0 && _closeOnDealloc && !_closed { close(_fd) } } public required init?(coder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } } extension NSFileHandle { internal static var _stdinFileHandle: NSFileHandle = { return NSFileHandle(fileDescriptor: STDIN_FILENO, closeOnDealloc: false) }() public class func fileHandleWithStandardInput() -> NSFileHandle { return _stdinFileHandle } internal static var _stdoutFileHandle: NSFileHandle = { return NSFileHandle(fileDescriptor: STDOUT_FILENO, closeOnDealloc: false) }() public class func fileHandleWithStandardOutput() -> NSFileHandle { return _stdoutFileHandle } internal static var _stderrFileHandle: NSFileHandle = { return NSFileHandle(fileDescriptor: STDERR_FILENO, closeOnDealloc: false) }() public class func fileHandleWithStandardError() -> NSFileHandle { return _stderrFileHandle } public class func fileHandleWithNullDevice() -> NSFileHandle { NSUnimplemented() } public convenience init?(forReadingAtPath path: String) { self.init(path: path, flags: O_RDONLY, createMode: 0) } public convenience init?(forWritingAtPath path: String) { self.init(path: path, flags: O_WRONLY, createMode: 0) } public convenience init?(forUpdatingAtPath path: String) { self.init(path: path, flags: O_RDWR, createMode: 0) } internal static func _openFileDescriptorForURL(url : NSURL, flags: Int32, reading: Bool) throws -> Int32 { if let path = url.path { let fd = _CFOpenFile(path, flags) if fd < 0 { throw _NSErrorWithErrno(errno, reading: reading, url: url) } return fd } else { throw _NSErrorWithErrno(ENOENT, reading: reading, url: url) } } public convenience init(forReadingFromURL url: NSURL) throws { let fd = try NSFileHandle._openFileDescriptorForURL(url, flags: O_RDONLY, reading: true) self.init(fileDescriptor: fd, closeOnDealloc: true) } public convenience init(forWritingToURL url: NSURL) throws { let fd = try NSFileHandle._openFileDescriptorForURL(url, flags: O_WRONLY, reading: false) self.init(fileDescriptor: fd, closeOnDealloc: true) } public convenience init(forUpdatingURL url: NSURL) throws { let fd = try NSFileHandle._openFileDescriptorForURL(url, flags: O_RDWR, reading: false) self.init(fileDescriptor: fd, closeOnDealloc: true) } } public let NSFileHandleOperationException: String = "" // NSUnimplemented public let NSFileHandleReadCompletionNotification: String = "" // NSUnimplemented public let NSFileHandleReadToEndOfFileCompletionNotification: String = "" // NSUnimplemented public let NSFileHandleConnectionAcceptedNotification: String = "" // NSUnimplemented public let NSFileHandleDataAvailableNotification: String = "" // NSUnimplemented public let NSFileHandleNotificationDataItem: String = "" // NSUnimplemented public let NSFileHandleNotificationFileHandleItem: String = "" // NSUnimplemented extension NSFileHandle { public func readInBackgroundAndNotifyForModes(modes: [String]?) { NSUnimplemented() } public func readInBackgroundAndNotify() { NSUnimplemented() } public func readToEndOfFileInBackgroundAndNotifyForModes(modes: [String]?) { NSUnimplemented() } public func readToEndOfFileInBackgroundAndNotify() { NSUnimplemented() } public func acceptConnectionInBackgroundAndNotifyForModes(modes: [String]?) { NSUnimplemented() } public func acceptConnectionInBackgroundAndNotify() { NSUnimplemented() } public func waitForDataInBackgroundAndNotifyForModes(modes: [String]?) { NSUnimplemented() } public func waitForDataInBackgroundAndNotify() { NSUnimplemented() } public var readabilityHandler: ((NSFileHandle) -> Void)? { NSUnimplemented() } public var writeabilityHandler: ((NSFileHandle) -> Void)? { NSUnimplemented() } } extension NSFileHandle { public convenience init(fileDescriptor fd: Int32) { self.init(fileDescriptor: fd, closeOnDealloc: false) } public var fileDescriptor: Int32 { return _fd } } public class NSPipe : NSObject { private let readHandle: NSFileHandle private let writeHandle: NSFileHandle public override init() { /// the `pipe` system call creates two `fd` in a malloc'ed area var fds = UnsafeMutablePointer<Int32>.alloc(2) defer { free(fds) } /// If the operating system prevents us from creating file handles, stop guard pipe(fds) == 0 else { fatalError("Could not open pipe file handles") } /// The handles below auto-close when the `NSFileHandle` is deallocated, so we /// don't need to add a `deinit` to this class /// Create the read handle from the first fd in `fds` self.readHandle = NSFileHandle(fileDescriptor: fds.memory, closeOnDealloc: true) /// Advance `fds` by one to create the write handle from the second fd self.writeHandle = NSFileHandle(fileDescriptor: fds.successor().memory, closeOnDealloc: true) super.init() } public var fileHandleForReading: NSFileHandle { return self.readHandle } public var fileHandleForWriting: NSFileHandle { return self.writeHandle } }
apache-2.0
998db949cef46ccd5689914352fdffb3
31.157746
142
0.587684
4.998249
false
false
false
false
Headmast/openfights
MoneyHelper/Models/Entity/DepositEntity.swift
1
1257
// // OrderEntity.swift // MoneyHelper // // Created by Kirill Klebanov on 17/09/2017. // Copyright © 2017 Surf. All rights reserved. // import Foundation import ObjectMapper public class DepositEntity: Mappable { // MARK: - Nested private struct Keys { public static let depositName = "DepositName" public static let depositMinSum = "DepositMinSum" public static let depositMinTermRate = "DepositMinTermRate" public static let depositMaxTermRate = "DepositMaxTermRate" public static let depositCapitalisation = "DepositCapitalisation" } // MARK: - Properties public var depositName: String? public var depositMinSum: String? public var depositMinTermRate: String? public var depositMaxTermRate: String? public var depositCapitalisation: String? public required convenience init?(map: Map) { self.init() } public func mapping(map: Map) { self.depositName <- map[Keys.depositName] self.depositMinSum <- map[Keys.depositMinSum] self.depositMinTermRate <- map[Keys.depositMinTermRate] self.depositMaxTermRate <- map[Keys.depositMaxTermRate] self.depositCapitalisation <- map[Keys.depositCapitalisation] } }
apache-2.0
282f1a68796ceac85352dac0c86bd882
28.209302
73
0.698248
4.186667
false
false
false
false
zyrx/eidolon
KioskTests/AppViewControllerTests.swift
6
1791
import Quick import Nimble import Nimble_Snapshots import ReactiveCocoa @testable import Kiosk class AppViewControllerTests: QuickSpec { override func spec() { it("looks right offline") { let subject = UIStoryboard.auction().viewControllerWithID(.NoInternetConnection) as UIViewController subject.loadViewProgrammatically() subject.view.backgroundColor = UIColor.blackColor() expect(subject).to(haveValidSnapshot()) } describe("view") { var subject: AppViewController! var fakeReachabilitySignal: RACSubject! beforeEach { subject = AppViewController.instantiateFromStoryboard(auctionStoryboard) fakeReachabilitySignal = RACSubject() subject.reachabilitySignal = fakeReachabilitySignal subject.apiPingerSignal = RACSignal.`return`(true).take(1) } it("shows the offlineBlockingView when offline signal is true"){ subject.loadViewProgrammatically() subject.offlineBlockingView.hidden = false fakeReachabilitySignal.sendNext(true) expect(subject.offlineBlockingView.hidden) == true } it("hides the offlineBlockingView when offline signal is false"){ subject.loadViewProgrammatically() subject.offlineBlockingView.hidden = true expect(subject.offlineBlockingView.hidden) == true fakeReachabilitySignal.sendNext(false) expect(subject.offlineBlockingView.hidden) == false } } } }
mit
00607fbcaffe93ca619722a2a077df59
32.792453
112
0.590173
6.396429
false
false
false
false
lemonkey/iOS
WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Common/AppConfiguration.swift
1
11475
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Handles application configuration logic and information. */ import Foundation public typealias StorageState = (storageOption: AppConfiguration.Storage, accountDidChange: Bool, cloudAvailable: Bool) public class AppConfiguration { // MARK: Types private struct Defaults { static let firstLaunchKey = "AppConfiguration.Defaults.firstLaunchKey" static let storageOptionKey = "AppConfiguration.Defaults.storageOptionKey" static let storedUbiquityIdentityToken = "AppConfiguration.Defaults.storedUbiquityIdentityToken" } // Keys used to store relevant list data in the userInfo dictionary of an NSUserActivity for continuation. public struct UserActivity { // The editing user activity is integrated into the ubiquitous UI/NSDocument architecture. public static let editing = "com.example.apple-samplecode.Lister.editing" // The watch user activity is used to continue activities started on the watch on other devices. public static let watch = "com.example.apple-samplecode.Lister.watch" public static let listURLPathUserInfoKey = "listURLPathUserInfoKey" public static let listColorUserInfoKey = "listColorUserInfoKey" } // Constants used in assembling and handling the custom lister:// URL scheme. public struct ListerScheme { public static let name = "lister" public static let colorQueryKey = "color" } /* The value of the `LISTER_BUNDLE_PREFIX` user-defined build setting is written to the Info.plist file of every target in Swift version of the Lister project. Specifically, the value of `LISTER_BUNDLE_PREFIX` is used as the string value for a key of `AAPLListerBundlePrefix`. This value is loaded from the target's bundle by the lazily evaluated static variable "prefix" from the nested "Bundle" struct below the first time that "Bundle.prefix" is accessed. This avoids the need for developers to edit both `LISTER_BUNDLE_PREFIX` and the code below. The value of `Bundle.prefix` is then used as part of an interpolated string to insert the user-defined value of `LISTER_BUNDLE_PREFIX` into several static string constants below. */ private struct Bundle { static var prefix = NSBundle.mainBundle().objectForInfoDictionaryKey("AAPLListerBundlePrefix") as! String } struct ApplicationGroups { static let primary = "group.\(Bundle.prefix).Lister.Documents" } #if os(OSX) public struct App { public static let bundleIdentifier = "\(Bundle.prefix).ListerOSX" } #endif public struct Extensions { #if os(iOS) public static let widgetBundleIdentifier = "\(Bundle.prefix).Lister.ListerToday" #elseif os(OSX) public static let widgetBundleIdentifier = "\(Bundle.prefix).Lister.ListerTodayOSX" #endif } public enum Storage: Int { case NotSet = 0, Local, Cloud } public class var sharedConfiguration: AppConfiguration { struct Singleton { static let sharedAppConfiguration = AppConfiguration() } return Singleton.sharedAppConfiguration } public class var listerUTI: String { return "com.example.apple-samplecode.Lister" } public class var listerFileExtension: String { return "list" } public class var defaultListerDraftName: String { return NSLocalizedString("List", comment: "") } public class var localizedTodayDocumentName: String { return NSLocalizedString("Today", comment: "The name of the Today list") } public class var localizedTodayDocumentNameAndExtension: String { return "\(localizedTodayDocumentName).\(listerFileExtension)" } private var applicationUserDefaults: NSUserDefaults { return NSUserDefaults(suiteName: ApplicationGroups.primary)! } public private(set) var isFirstLaunch: Bool { get { registerDefaults() return applicationUserDefaults.boolForKey(Defaults.firstLaunchKey) } set { applicationUserDefaults.setBool(newValue, forKey: Defaults.firstLaunchKey) } } private func registerDefaults() { #if os(iOS) let defaultOptions: [NSObject: AnyObject] = [ Defaults.firstLaunchKey: true, Defaults.storageOptionKey: Storage.NotSet.rawValue ] #elseif os(OSX) let defaultOptions: [NSObject: AnyObject] = [ Defaults.firstLaunchKey: true ] #endif applicationUserDefaults.registerDefaults(defaultOptions) } public func runHandlerOnFirstLaunch(firstLaunchHandler: Void -> Void) { if isFirstLaunch { isFirstLaunch = false firstLaunchHandler() } } public var isCloudAvailable: Bool { return NSFileManager.defaultManager().ubiquityIdentityToken != nil } #if os(iOS) public var storageState: StorageState { return (storageOption, hasAccountChanged(), isCloudAvailable) } public var storageOption: Storage { get { let value = applicationUserDefaults.integerForKey(Defaults.storageOptionKey) return Storage(rawValue: value)! } set { applicationUserDefaults.setInteger(newValue.rawValue, forKey: Defaults.storageOptionKey) } } // MARK: Ubiquity Identity Token Handling (Account Change Info) public func hasAccountChanged() -> Bool { var hasChanged = false let currentToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? = NSFileManager.defaultManager().ubiquityIdentityToken let storedToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? = storedUbiquityIdentityToken let currentTokenNilStoredNonNil = currentToken == nil && storedToken != nil let storedTokenNilCurrentNonNil = currentToken != nil && storedToken == nil // Compare the tokens. let currentNotEqualStored = currentToken != nil && storedToken != nil && !currentToken!.isEqual(storedToken!) if currentTokenNilStoredNonNil || storedTokenNilCurrentNonNil || currentNotEqualStored { persistAccount() hasChanged = true } return hasChanged } private func persistAccount() { var defaults = applicationUserDefaults if let token = NSFileManager.defaultManager().ubiquityIdentityToken { let ubiquityIdentityTokenArchive = NSKeyedArchiver.archivedDataWithRootObject(token) defaults.setObject(ubiquityIdentityTokenArchive, forKey: Defaults.storedUbiquityIdentityToken) } else { defaults.removeObjectForKey(Defaults.storedUbiquityIdentityToken) } } // MARK: Convenience private var storedUbiquityIdentityToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? { var storedToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? // Determine if the logged in iCloud account has changed since the user last launched the app. let archivedObject: AnyObject? = applicationUserDefaults.objectForKey(Defaults.storedUbiquityIdentityToken) if let ubiquityIdentityTokenArchive = archivedObject as? NSData { if let archivedObject = NSKeyedUnarchiver.unarchiveObjectWithData(ubiquityIdentityTokenArchive) as? protocol<NSCoding, NSCopying, NSObjectProtocol> { storedToken = archivedObject } } return storedToken } /** Returns a `ListCoordinator` based on the current configuration that queries based on `pathExtension`. For example, if the user has chosen local storage, a local `ListCoordinator` object will be returned. */ public func listCoordinatorForCurrentConfigurationWithPathExtension(pathExtension: String, firstQueryHandler: (Void -> Void)? = nil) -> ListCoordinator { if AppConfiguration.sharedConfiguration.storageOption != .Cloud { // This will be called if the storage option is either `.Local` or `.NotSet`. return LocalListCoordinator(pathExtension: pathExtension, firstQueryUpdateHandler: firstQueryHandler) } else { return CloudListCoordinator(pathExtension: pathExtension, firstQueryUpdateHandler: firstQueryHandler) } } /** Returns a `ListCoordinator` based on the current configuration that queries based on `lastPathComponent`. For example, if the user has chosen local storage, a local `ListCoordinator` object will be returned. */ public func listCoordinatorForCurrentConfigurationWithLastPathComponent(lastPathComponent: String, firstQueryHandler: (Void -> Void)? = nil) -> ListCoordinator { if AppConfiguration.sharedConfiguration.storageOption != .Cloud { // This will be called if the storage option is either `.Local` or `.NotSet`. return LocalListCoordinator(lastPathComponent: lastPathComponent, firstQueryUpdateHandler: firstQueryHandler) } else { return CloudListCoordinator(lastPathComponent: lastPathComponent, firstQueryUpdateHandler: firstQueryHandler) } } /** Returns a `ListsController` instance based on the current configuration. For example, if the user has chosen local storage, a `ListsController` object will be returned that uses a local list coordinator. `pathExtension` is passed down to the list coordinator to filter results. */ public func listsControllerForCurrentConfigurationWithPathExtension(pathExtension: String, firstQueryHandler: (Void -> Void)? = nil) -> ListsController { let listCoordinator = listCoordinatorForCurrentConfigurationWithPathExtension(pathExtension, firstQueryHandler: firstQueryHandler) return ListsController(listCoordinator: listCoordinator, delegateQueue: NSOperationQueue.mainQueue()) { lhs, rhs in return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == NSComparisonResult.OrderedAscending } } /** Returns a `ListsController` instance based on the current configuration. For example, if the user has chosen local storage, a `ListsController` object will be returned that uses a local list coordinator. `lastPathComponent` is passed down to the list coordinator to filter results. */ public func listsControllerForCurrentConfigurationWithLastPathComponent(lastPathComponent: String, firstQueryHandler: (Void -> Void)? = nil) -> ListsController { let listCoordinator = listCoordinatorForCurrentConfigurationWithLastPathComponent(lastPathComponent, firstQueryHandler: firstQueryHandler) return ListsController(listCoordinator: listCoordinator, delegateQueue: NSOperationQueue.mainQueue()) { lhs, rhs in return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == NSComparisonResult.OrderedAscending } } #endif }
mit
9fd8f438c5ad13e0cb1000c01a2069fd
41.496296
165
0.687004
5.596585
false
true
false
false
QuantumExplorer/breadwallet
WatchApp Extension/DWWatchDataManager.swift
1
11200
// // Created by Andrew Podkovyrin // Copyright © 2019 Dash Core Group. All rights reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // 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 WatchConnectivity import WatchKit enum WalletStatus { case unknown case hasSetup case notSetup } final class DWWatchDataManager: NSObject { static let ApplicationDataDidUpdateNotification = Notification.Name("ApplicationDataDidUpdateNotification") static let WalletStatusDidChangeNotification = Notification.Name("WalletStatusDidChangeNotification") static let WalletTxReceiveNotification = Notification.Name("WalletTxReceiveNotification") static let shared = DWWatchDataManager() static let applicationContextDataFileName = "applicationContextData.txt" let session = WCSession.default let timerFireInterval: TimeInterval = 7 // have iphone app sync with peer every 7 seconds var timer: Timer? private var appleWatchData: BRAppleWatchData? var balance: String? { return appleWatchData?.balance } var balanceInLocalCurrency: String? { return appleWatchData?.balanceInLocalCurrency } var receiveMoneyAddress: String? { return appleWatchData?.receiveMoneyAddress } var receiveMoneyQRCodeImage: UIImage? { return appleWatchData?.receiveMoneyQRCodeImage } var lastestTransction: String? { return appleWatchData?.lastestTransction } var transactionHistory: [BRAppleWatchTransactionData] { if let unwrappedAppleWatchData: BRAppleWatchData = appleWatchData { return unwrappedAppleWatchData.transactions } else { return [BRAppleWatchTransactionData]() } } var walletStatus: WalletStatus { guard let appleWatchData = appleWatchData else { return .unknown } return appleWatchData.hasWallet ? .hasSetup : .notSetup } lazy var dataFilePath: URL = { let filemgr = FileManager.default let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let docsDir = dirPaths[0] as String return URL(fileURLWithPath: docsDir).appendingPathComponent(DWWatchDataManager.applicationContextDataFileName) }() override init() { super.init() if appleWatchData == nil { unarchiveData() } session.delegate = self session.activate() } func setupTimerAndReloadIfActive() { if session.activationState == .activated { setupTimer() requestAllData() } } func requestQRCodeForBalance(_ bits: String, responseHandler: @escaping (_ qrImage: UIImage?, _ error: NSError?) -> Void) { if session.isReachable { let msg = [ AW_SESSION_REQUEST_TYPE: NSNumber(value: AWSessionRquestTypeFetchData.rawValue as UInt32), AW_SESSION_REQUEST_DATA_TYPE_KEY: NSNumber(value: AWSessionRquestDataTypeQRCodeBits.rawValue as UInt32), AW_SESSION_QR_CODE_BITS_KEY: bits, ] as [String: Any] session.sendMessage( msg, replyHandler: { ctx -> Void in if let dat = ctx[AW_QR_CODE_BITS_KEY], let datDat = dat as? Data, let img = UIImage(data: datDat) { responseHandler(img, nil) return } let error = NSError(domain: "", code: 500, userInfo: [ NSLocalizedDescriptionKey: "Unable to get new QR code", ]) responseHandler(nil, error) }, errorHandler: { _ in let error = NSError(domain: "", code: 500, userInfo: [ NSLocalizedDescriptionKey: NSLocalizedString("Unable to get new QR code", comment: ""), ]) responseHandler(nil, error) } ) } } func balanceAttributedString() -> NSAttributedString? { if let originalBalanceString = DWWatchDataManager.shared.balance { var balanceString = originalBalanceString.replacingOccurrences(of: "DASH", with: "") balanceString = balanceString.trimmingCharacters(in: CharacterSet.whitespaces) return attributedStringForBalance(balanceString) } return nil } func archiveData(_ appleWatchData: BRAppleWatchData) { try? NSKeyedArchiver.archivedData(withRootObject: appleWatchData).write(to: dataFilePath, options: [.atomic]) } func unarchiveData() { if let data = try? Data(contentsOf: dataFilePath) { appleWatchData = NSKeyedUnarchiver.unarchiveObject(with: data) as? BRAppleWatchData } } func setupTimer() { destroyTimer() let weakTimerTarget = BRAWWeakTimerTarget(initTarget: self, initSelector: #selector(DWWatchDataManager.requestAllData)) timer = Timer.scheduledTimer(timeInterval: timerFireInterval, target: weakTimerTarget, selector: #selector(BRAWWeakTimerTarget.timerDidFire), userInfo: nil, repeats: true) } func destroyTimer() { guard let timer = timer else { return } timer.invalidate() } // MARK: Private @objc private func requestAllData() { if Thread.current != .main { DispatchQueue.main.async { self.requestAllData() } return } if session.isReachable { // WKInterfaceDevice.currentDevice().playHaptic(WKHapticType.Click) let messageToSend = [ AW_SESSION_REQUEST_TYPE: NSNumber(value: AWSessionRquestTypeFetchData.rawValue as UInt32), AW_SESSION_REQUEST_DATA_TYPE_KEY: NSNumber(value: AWSessionRquestDataTypeApplicationContextData.rawValue as UInt32), ] session.sendMessage(messageToSend, replyHandler: { [unowned self] replyMessage in if let data = replyMessage[AW_SESSION_RESPONSE_KEY] as? Data { if let unwrappedAppleWatchData = NSKeyedUnarchiver.unarchiveObject(with: data) as? BRAppleWatchData { let previousAppleWatchData = self.appleWatchData let previousWalletStatus = self.walletStatus self.appleWatchData = unwrappedAppleWatchData let notificationCenter = NotificationCenter.default if previousAppleWatchData != self.appleWatchData { self.archiveData(unwrappedAppleWatchData) notificationCenter.post( name: DWWatchDataManager.ApplicationDataDidUpdateNotification, object: nil ) } if self.walletStatus != previousWalletStatus { notificationCenter.post( name: DWWatchDataManager.WalletStatusDidChangeNotification, object: nil ) } } } }, errorHandler: { error in print(error) }) } } private func attributedStringForBalance(_ balance: String?) -> NSAttributedString { let attributedString = NSMutableAttributedString() attributedString.append( NSAttributedString(string: "Đ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray]) ) attributedString.append( NSAttributedString(string: balance ?? "0", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) ) return attributedString } } extension DWWatchDataManager: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { // TODO: proper error handling setupTimerAndReloadIfActive() } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { if let applicationContextData = applicationContext[AW_APPLICATION_CONTEXT_KEY] as? Data { if let transferedAppleWatchData = NSKeyedUnarchiver.unarchiveObject(with: applicationContextData) as? BRAppleWatchData { let previousWalletStatus = walletStatus appleWatchData = transferedAppleWatchData archiveData(transferedAppleWatchData) let notificationCenter = NotificationCenter.default if walletStatus != previousWalletStatus { notificationCenter.post( name: DWWatchDataManager.WalletStatusDidChangeNotification, object: nil ) } notificationCenter.post( name: DWWatchDataManager.ApplicationDataDidUpdateNotification, object: nil ) } } } func session(_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @escaping ([String: Any]) -> Void) { print("Handle message from phone \(message)") if let noteV = message[AW_PHONE_NOTIFICATION_KEY], let noteStr = noteV as? String, let noteTypeV = message[AW_PHONE_NOTIFICATION_TYPE_KEY], let noteTypeN = noteTypeV as? NSNumber, noteTypeN.uint32Value == AWPhoneNotificationTypeTxReceive.rawValue { let note = Notification( name: DWWatchDataManager.WalletTxReceiveNotification, object: nil, userInfo: [ NSLocalizedDescriptionKey: noteStr, ] ) NotificationCenter.default.post(note) } } }
mit
85dd6b8b252240d59ecbd1e21894cb2c
38.850534
120
0.577692
5.745511
false
false
false
false
micchyboy1023/Today
Today iOS App/TodayKit iOS/AppGroupSharedData.swift
1
2257
// // AppGroupSharedData.swift // Today // // Created by UetaMasamichi on 2016/02/23. // Copyright © 2016年 Masamichi Ueta. All rights reserved. // import Foundation public let appGroupURLScheme = "Today" public final class AppGroupSharedData { public struct AppGroupSharedDataKey { public static let todayScore = "TodayScore" public static let todayDate = "TodayDate" public static let total = "Total" public static let longestStreak = "LongestStreak" public static let currentStreak = "CurrentStreak" } private static let defaults = UserDefaults(suiteName: "group.com.uetamasamichi.todaygroup") public static var shared = AppGroupSharedData() //MARK: - Values public var todayScore: Int { didSet { AppGroupSharedData.defaults?.set(todayScore, forKey: AppGroupSharedDataKey.todayScore) } } public var todayDate: Date { didSet { AppGroupSharedData.defaults?.set(todayDate, forKey: AppGroupSharedDataKey.todayDate) } } public var total: Int { didSet { AppGroupSharedData.defaults?.set(total, forKey: AppGroupSharedDataKey.total) } } public var longestStreak: Int { didSet { AppGroupSharedData.defaults?.set(longestStreak, forKey: AppGroupSharedDataKey.longestStreak) } } public var currentStreak: Int { didSet { AppGroupSharedData.defaults?.set(currentStreak, forKey: AppGroupSharedDataKey.currentStreak) } } public init() { todayScore = AppGroupSharedData.defaults?.integer(forKey: AppGroupSharedDataKey.todayScore) ?? 0 todayDate = AppGroupSharedData.defaults?.object(forKey: AppGroupSharedDataKey.todayDate) as? Date ?? Date() total = AppGroupSharedData.defaults?.integer(forKey: AppGroupSharedDataKey.total) ?? 0 longestStreak = AppGroupSharedData.defaults?.integer(forKey: AppGroupSharedDataKey.longestStreak) ?? 0 currentStreak = AppGroupSharedData.defaults?.integer(forKey: AppGroupSharedDataKey.currentStreak) ?? 0 } public static func clean() { AppGroupSharedData.defaults?.clean() } }
mit
b22bd1a3c15302a68fd56cc807e0e7aa
31.666667
115
0.671695
4.590631
false
false
false
false
zigdanis/Interactive-Transitioning
InteractiveTransitioning/Classes/TransitioningDelegate.swift
1
7487
// // TransitioningDelegate.swift // InteractiveTransitioning // // Created by Danis Ziganshin on 18/07/16. // Copyright © 2016 Zigdanis. All rights reserved. // import UIKit import Foundation class TransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { let animationController = AnimationController() func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return animationController } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return animationController } } class AnimationController: NSObject, UIViewControllerAnimatedTransitioning { let duration:TimeInterval = 1.0 let expandingMultiplier = 1/20.0 var fullDuration:TimeInterval { get { return duration + duration * expandingMultiplier } } var propertyAnimator: UIViewPropertyAnimator? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return fullDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresenting(transition: transitionContext) { propertyAnimator = propertyAnimatorForPresenting(using: transitionContext) } else { propertyAnimator = propertyAnimatorForDismissing(using: transitionContext) } propertyAnimator?.startAnimation() } private func propertyAnimatorForPresenting(using transitionContext: UIViewControllerContextTransitioning) -> UIViewPropertyAnimator? { //Prepare superview let fromVC = transitionContext.viewController(forKey: .from) as? ThumbImageViewController guard let originalRoundedView = fromVC?.thumbImageView else { return nil } let toView = transitionContext.view(forKey: .to)! let containerView = transitionContext.containerView containerView.addSubview(toView) toView.isHidden = true originalRoundedView.isHidden = true //Setup animatable view let copyRoundedView = RoundedImageView(image: originalRoundedView.image) copyRoundedView.expandingMultiplier = expandingMultiplier copyRoundedView.frame = originalRoundedView.frame containerView.addSubview(copyRoundedView) setupViewFullScreenConstraints(roundedView: copyRoundedView) let initialRect = originalRoundedView.bounds let destinationRect = toView.bounds // Create animator let timing = UICubicTimingParameters(animationCurve: .easeInOut) let animator = UIViewPropertyAnimator(duration: fullDuration, timingParameters: timing) let relativeStart = duration/fullDuration animator.addAnimations { UIView.animateKeyframes(withDuration: self.fullDuration, delay: 0, options: [.calculationModeLinear], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: relativeStart, animations: { containerView.layoutIfNeeded() }) }) copyRoundedView.animateImageViewWith(action: .Expand, initial: initialRect, destination: destinationRect, duration: self.duration, options: [.curveEaseInOut]) } animator.addCompletion { (position) in toView.isHidden = false originalRoundedView.isHidden = false copyRoundedView.removeFromSuperview() transitionContext.completeTransition(true) } return animator } private func propertyAnimatorForDismissing(using transitionContext: UIViewControllerContextTransitioning) -> UIViewPropertyAnimator? { //Prepare superview let fromNVC = transitionContext.viewController(forKey: .from) as? UINavigationController let fromVC = fromNVC?.viewControllers.first as? FullImageViewController let toVC = transitionContext.viewController(forKey: .to) as? ThumbImageViewController guard let originalFullView = fromVC?.fullImageView else { return nil } guard let originalRoundedView = toVC?.thumbImageView else { return nil } let fromView = transitionContext.view(forKey: .from)! let containerView = transitionContext.containerView originalFullView.isHidden = true originalRoundedView.isHidden = true //Setup animatable view let copyRoundedView = RoundedImageView(image: originalFullView.image) copyRoundedView.expandingMultiplier = expandingMultiplier copyRoundedView.frame = originalFullView.frame containerView.addSubview(copyRoundedView) alignConstraints(toView: copyRoundedView, fromView: originalRoundedView) let initialRect = originalFullView.bounds let destinationRect = originalRoundedView.bounds // Create animator let timing = UICubicTimingParameters(animationCurve: .easeInOut) let animator = UIViewPropertyAnimator(duration: fullDuration, timingParameters: timing) let relativeDuration = duration/fullDuration let relativeStart = 1 - relativeDuration animator.addAnimations { UIView.animateKeyframes(withDuration: self.fullDuration, delay: 0, options: [.calculationModeLinear], animations: { UIView.addKeyframe(withRelativeStartTime: relativeStart, relativeDuration: relativeDuration, animations: { containerView.layoutIfNeeded() }) }) copyRoundedView.animateImageViewWith(action: .Collapse, initial: initialRect, destination: destinationRect, duration: self.duration, options: [.curveEaseInOut]) } animator.addCompletion { (position) in copyRoundedView.removeFromSuperview() originalRoundedView.isHidden = false fromView.removeFromSuperview() transitionContext.completeTransition(true) } return animator } private func isPresenting(transition: UIViewControllerContextTransitioning) -> Bool { guard let toVC = transition.viewController(forKey: .from) else { return true } let isPresentingFull = toVC is ThumbImageViewController return isPresentingFull } // MARK: - Constraints setup private func setupViewFullScreenConstraints(roundedView: UIView) { let views = ["roundedView": roundedView] let horizont = NSLayoutConstraint.constraints(withVisualFormat: "H:|[roundedView]|", options:.alignAllBottom, metrics: nil, views: views) let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[roundedView]|", options:.alignAllBottom, metrics: nil, views: views) let constraints = horizont + vertical NSLayoutConstraint.activate(constraints) } private func alignConstraints(toView: UIView, fromView: UIView) { let constraints = [ toView.topAnchor.constraint(equalTo: fromView.topAnchor), toView.leadingAnchor.constraint(equalTo: fromView.leadingAnchor), toView.trailingAnchor.constraint(equalTo: fromView.trailingAnchor), toView.bottomAnchor.constraint(equalTo: fromView.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } }
mit
10b14893c16a8cdf0f5116d81ec18c9c
47.296774
172
0.707855
5.984013
false
false
false
false
bryanluby/XcodeTestProjects
SwiftScratchpad/SwiftScratchpad/Constants.swift
1
2168
// // Constants.swift // import Foundation // MARK: - TableView Cell Identifiers let BlueCellIdentifier = "BlueCellIdentifier" let LargeCellIdentifier = "LargeCellIdentifier" let DetailViewTableViewControllerCellIdentifier = "DetailViewTableViewControllerCellIdentifier" let MasterViewControllerCellIdentifier = "MasterViewControllerCellIdentifier" // MARK: - Font Sizes let DefaultFontSize = 14 // MARK: - Segue Identifiers let SegueToMasterViewController = "SegueToMasterViewController" let SegueToDetailViewController = "SegueToDetailViewController" enum CellIdentifiers: String { case Blue = "Blue" case Large = "Large" } enum FontSizes: Int { case Large = 14 case Small = 10 } enum AnimationDurations: NSTimeInterval { case Fast = 1.0 case Medium = 3.0 case Slow = 5.0 } enum Emojis: Character { case Happy = "😄" case Sad = "😢" } enum SegueIdentifiers: String { case Master = "MasterViewController" case Detail = "DetailViewController" } func tester() { print(Emojis.Happy.rawValue) print(Constants.Emojis.Happy) } struct CellIdentifiers2 { static let Blue = "Blue" static let Large = "Large" } struct FontSizes2 { static let Large = 14 static let Small = 10 } struct AnimationDurations2 { static let Fast: NSTimeInterval = 1.0 static let Slow: NSTimeInterval = 5.0 } struct Emojis2 { static let Happy = "😄" static let Sad = "😢" } struct SegueIdentifiers2 { static let Master = "MasterViewController" static let Detail = "DetailViewController" } struct Constants { struct CellIdentifiers { static let Blue = "Blue" static let Large = "Large" } struct FontSizes { static let Large = 14 static let Small = 10 } struct AnimationDurations { static let Fast: NSTimeInterval = 1.0 static let Slow: NSTimeInterval = 5.0 } struct Emojis { static let Happy = "😄" static let Sad = "😢" } struct SegueIdentifiers { static let Master = "MasterViewController" static let Detail = "DetailViewController" } }
mit
4a0c4eb913025486557f5a69a9bf489d
19.673077
95
0.676279
4.240631
false
false
false
false
wujunyang/swiftProject
SwiftProject/ModelController.swift
1
3127
// // ModelController.swift // SwiftProject // // Created by wujunyang on 2016/11/21. // Copyright © 2016年 wujunyang. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData: [String] = [] override init() { super.init() // Create the data model. let dateFormatter = DateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewController(withIdentifier: "DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(_ viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. return pageData.index(of: viewController.dataObject) ?? NSNotFound } // MARK: - Page View Controller Data Source func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { return nil } index -= 1 return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { return nil } index += 1 if index == self.pageData.count { return nil } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
apache-2.0
e92cda9546121dbc211535b7ceecc6ec
39.571429
225
0.710307
5.5097
false
false
false
false
huonw/swift
test/ClangImporter/objc_id_as_any.swift
15
1160
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s // REQUIRES: objc_interop import Foundation func assertTypeIsAny(_: Any.Protocol) {} func staticType<T>(_: T) -> T.Type { return T.self } let idLover = NSIdLover() let t1 = staticType(idLover.makesId()) assertTypeIsAny(t1) struct ArbitraryThing {} idLover.takesId(ArbitraryThing()) var x: AnyObject = NSObject() idLover.takesArray(ofId: &x) var xAsAny = x as Any idLover.takesArray(ofId: &xAsAny) // expected-error{{argument type 'Any' does not conform to expected type 'AnyObject'}} var y: Any = NSObject() idLover.takesArray(ofId: &y) // expected-error{{argument type 'Any' does not conform to expected type 'AnyObject'}} idLover.takesId(x) idLover.takesId(y) install_global_event_handler(idLover) // expected-error {{cannot convert value of type 'NSIdLover' to expected argument type 'event_handler?' (aka 'Optional<@convention(c) (Any) -> ()>')}} // FIXME: this should not type-check! // Function conversions are not legal when converting to a thin function type. let handler: @convention(c) (Any) -> () = { object in () } install_global_event_handler(handler)
apache-2.0
f682e96f08d5b398796df284821f0357
34.151515
188
0.727586
3.143631
false
false
false
false
jfkilian/DataBinding
DataBinding/ViewController.swift
1
3050
// // ViewController.swift // DataBinding // // Created by Jürgen F. Kilian on 06.07.17. // Copyright © 2017 Kilian IT-Consulting. All rights reserved. // import UIKit class ViewController: UIViewController, DataBindingContextOwner { let dataBindingContext = DataBindingContext() var viewModel: ViewModel? @IBOutlet weak var slider: UISlider! @IBOutlet weak var sliderValue: UITextField! @IBOutlet weak var state: UISwitch! @IBOutlet weak var name: UITextField! override func viewDidLoad() { super.viewDidLoad() initDataBinding() } func initDataBinding() { viewModel = ViewModel(delegate: self) if let viewModel = viewModel { dataBindingContext.bindValue(target: UIPropertyFactory.value(observedCtrl: slider), model: GenericProperty(observedItem: viewModel, getter: {return viewModel.value}, setter: {value in viewModel.value = value}) ) dataBindingContext.bindValue(target: UIPropertyFactory.text(observedCtrl: sliderValue), model: GenericProperty(observedItem: viewModel, getter: {return viewModel.valueAsString}, setter: {value in viewModel.valueAsString = value}) ) dataBindingContext.bindValue(target: UIPropertyFactory.bool(observedCtrl: state), model: GenericProperty(observedItem: viewModel, getter: {return viewModel.state}, setter: {value in viewModel.state = value}) ) dataBindingContext.bindValue(target: UIPropertyFactory.text(observedCtrl: name), model: GenericProperty(observedItem: viewModel, getter: {return viewModel.name}, setter: {value in viewModel.name = value}) ) dataBindingContext.bindValue(target: UIPropertyFactory.backgroundColor(observedCtrl: view), model: ReadOnlyProperty(observedItem: viewModel, getter: {return viewModel.backGroundColor}), updateValueStrategy: UpdateValueStrategy.model2Target ) } } }
mit
92fb3e6924c2ab0ed4f40d71437cd3b5
43.173913
108
0.458333
6.803571
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift
3
13605
//// CryptoSwift // // Copyright (C) 2014-2018 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // CCM mode combines the well known CBC-MAC with the well known counter mode of encryption. // https://tools.ietf.org/html/rfc3610 // https://csrc.nist.gov/publications/detail/sp/800-38c/final #if canImport(Darwin) import Darwin #else import Glibc #endif /// Counter with Cipher Block Chaining-Message Authentication Code public struct CCM: StreamMode { public enum Error: Swift.Error { /// Invalid IV case invalidInitializationVector case invalidParameter case fail } public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] private let nonce: Array<UInt8> private let additionalAuthenticatedData: Array<UInt8>? private let tagLength: Int private let messageLength: Int // total message length. need to know in advance // `authenticationTag` nil for encryption, known tag for decryption /// For encryption, the value is set at the end of the encryption. /// For decryption, this is a known Tag to validate against. public var authenticationTag: Array<UInt8>? /// Initialize CCM /// /// - Parameters: /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. /// - additionalAuthenticatedData: Additional authenticated data. public init(iv: Array<UInt8>, tagLength: Int, messageLength: Int, additionalAuthenticatedData: Array<UInt8>? = nil) { self.nonce = iv self.tagLength = tagLength self.additionalAuthenticatedData = additionalAuthenticatedData self.messageLength = messageLength // - tagLength } /// Initialize CCM /// /// - Parameters: /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. /// - authenticationTag: Authentication Tag value if not concatenated to ciphertext. /// - additionalAuthenticatedData: Additional authenticated data. public init(iv: Array<UInt8>, tagLength: Int, messageLength: Int, authenticationTag: Array<UInt8>, additionalAuthenticatedData: Array<UInt8>? = nil) { self.init(iv: iv, tagLength: tagLength, messageLength: messageLength, additionalAuthenticatedData: additionalAuthenticatedData) self.authenticationTag = authenticationTag } public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { if self.nonce.isEmpty { throw Error.invalidInitializationVector } return CCMModeWorker(blockSize: blockSize, nonce: self.nonce.slice, messageLength: self.messageLength, additionalAuthenticatedData: self.additionalAuthenticatedData, tagLength: self.tagLength, cipherOperation: cipherOperation) } } class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { typealias Counter = Int var counter = 0 let cipherOperation: CipherOperationOnBlock let blockSize: Int private let tagLength: Int private let messageLength: Int // total message length. need to know in advance private let q: UInt8 let additionalBufferSize: Int private var keystreamPosIdx = 0 private let nonce: Array<UInt8> private var last_y: ArraySlice<UInt8> = [] private var keystream: Array<UInt8> = [] // Known Tag used to validate during decryption private var expectedTag: Array<UInt8>? public enum Error: Swift.Error { case invalidParameter } init(blockSize: Int, nonce: ArraySlice<UInt8>, messageLength: Int, additionalAuthenticatedData: [UInt8]?, expectedTag: Array<UInt8>? = nil, tagLength: Int, cipherOperation: @escaping CipherOperationOnBlock) { self.blockSize = 16 // CCM is defined for 128 block size self.tagLength = tagLength self.additionalBufferSize = tagLength self.messageLength = messageLength self.expectedTag = expectedTag self.cipherOperation = cipherOperation self.nonce = Array(nonce) self.q = UInt8(15 - nonce.count) // n = 15-q let hasAssociatedData = additionalAuthenticatedData != nil && !additionalAuthenticatedData!.isEmpty self.processControlInformation(nonce: self.nonce, tagLength: tagLength, hasAssociatedData: hasAssociatedData) if let aad = additionalAuthenticatedData, hasAssociatedData { self.process(aad: aad) } } // For the very first time setup new IV (aka y0) from the block0 private func processControlInformation(nonce: [UInt8], tagLength: Int, hasAssociatedData: Bool) { let block0 = try! format(nonce: nonce, Q: UInt32(self.messageLength), q: self.q, t: UInt8(tagLength), hasAssociatedData: hasAssociatedData).slice let y0 = self.cipherOperation(block0)!.slice self.last_y = y0 } private func process(aad: [UInt8]) { let encodedAAD = format(aad: aad) for block_i in encodedAAD.batched(by: 16) { let y_i = self.cipherOperation(xor(block_i, self.last_y))!.slice self.last_y = y_i } } private func S(i: Int) throws -> [UInt8] { let ctr = try format(counter: i, nonce: nonce, q: q) return self.cipherOperation(ctr.slice)! } func seek(to position: Int) throws { self.counter = position self.keystream = try self.S(i: position) let offset = position % self.blockSize self.keystreamPosIdx = offset } func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> { var result = Array<UInt8>(reserveCapacity: plaintext.count) var processed = 0 while processed < plaintext.count { // Need a full block here to update keystream and do CBC if self.keystream.isEmpty || self.keystreamPosIdx == self.blockSize { // y[i], where i is the counter. Can encrypt 1 block at a time self.counter += 1 guard let S = try? S(i: counter) else { return Array(plaintext) } let plaintextP = addPadding(Array(plaintext), blockSize: blockSize) guard let y = cipherOperation(xor(last_y, plaintextP)) else { return Array(plaintext) } self.last_y = y.slice self.keystream = S self.keystreamPosIdx = 0 } let xored: Array<UInt8> = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) keystreamPosIdx += xored.count processed += xored.count result += xored } return result } func finalize(encrypt ciphertext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> { // concatenate T at the end guard let S0 = try? S(i: 0) else { return ciphertext } let computedTag = xor(last_y.prefix(self.tagLength), S0) as ArraySlice<UInt8> return ciphertext + computedTag } // Decryption is stream // CBC is block private var accumulatedPlaintext: [UInt8] = [] func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { var output = Array<UInt8>(reserveCapacity: ciphertext.count) do { var currentCounter = self.counter var processed = 0 while processed < ciphertext.count { // Need a full block here to update keystream and do CBC // New keystream for a new block if self.keystream.isEmpty || self.keystreamPosIdx == self.blockSize { currentCounter += 1 guard let S = try? S(i: currentCounter) else { return Array(ciphertext) } self.keystream = S self.keystreamPosIdx = 0 } let xored: Array<UInt8> = xor(ciphertext[ciphertext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) // plaintext keystreamPosIdx += xored.count processed += xored.count output += xored self.counter = currentCounter } } // Accumulate plaintext for the MAC calculations at the end. // It would be good to process it together though, here. self.accumulatedPlaintext += output // Shouldn't return plaintext until validate tag. // With incremental update, can't validate tag until all block are processed. return output } func finalize(decrypt plaintext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> { // concatenate T at the end let computedTag = Array(last_y.prefix(self.tagLength)) guard let expectedTag = self.expectedTag, expectedTag == computedTag else { throw CCM.Error.fail } return plaintext } @discardableResult func willDecryptLast(bytes ciphertext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> { // get tag of additionalBufferSize size // `ciphertext` contains at least additionalBufferSize bytes // overwrite expectedTag property used later for verification guard let S0 = try? S(i: 0) else { return ciphertext } self.expectedTag = xor(ciphertext.suffix(self.tagLength), S0) as [UInt8] return ciphertext[ciphertext.startIndex..<ciphertext.endIndex.advanced(by: -Swift.min(tagLength, ciphertext.count))] } func didDecryptLast(bytes plaintext: ArraySlice<UInt8>) throws -> ArraySlice<UInt8> { // Calculate Tag, from the last CBC block, for accumulated plaintext. var processed = 0 for block in self.accumulatedPlaintext.batched(by: self.blockSize) { let blockP = addPadding(Array(block), blockSize: blockSize) guard let y = cipherOperation(xor(last_y, blockP)) else { return plaintext } self.last_y = y.slice processed += block.count } self.accumulatedPlaintext.removeFirst(processed) return plaintext } } // Q - octet length of P // q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} // t - octet length of T (MAC length). An element of {4,6,8,10,12,14,16} private func format(nonce N: [UInt8], Q: UInt32, q: UInt8, t: UInt8, hasAssociatedData: Bool) throws -> [UInt8] { var flags0: UInt8 = 0 if hasAssociatedData { // 7 bit flags0 |= (1 << 6) } // 6,5,4 bit is t in 3 bits flags0 |= (((t - 2) / 2) & 0x07) << 3 // 3,2,1 bit is q in 3 bits flags0 |= ((q - 1) & 0x07) << 0 var block0: [UInt8] = Array<UInt8>(repeating: 0, count: 16) block0[0] = flags0 // N in 1...(15-q) octets, n = 15-q // n is an element of {7,8,9,10,11,12,13} let n = 15 - Int(q) guard (n + Int(q)) == 15 else { // n+q == 15 throw CCMModeWorker.Error.invalidParameter } block0[1...n] = N[0...(n - 1)] // Q in (16-q)...15 octets block0[(16 - Int(q))...15] = Q.bytes(totalBytes: Int(q)).slice return block0 } /// Formatting of the Counter Blocks. Ctr[i] /// The counter generation function. /// Q - octet length of P /// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} private func format(counter i: Int, nonce N: [UInt8], q: UInt8) throws -> [UInt8] { var flags0: UInt8 = 0 // bit 8,7 is Reserved // bit 4,5,6 shall be set to 0 // 3,2,1 bit is q in 3 bits flags0 |= ((q - 1) & 0x07) << 0 var block = Array<UInt8>(repeating: 0, count: 16) // block[0] block[0] = flags0 // N in 1...(15-q) octets, n = 15-q // n is an element of {7,8,9,10,11,12,13} let n = 15 - Int(q) guard (n + Int(q)) == 15 else { // n+q == 15 throw CCMModeWorker.Error.invalidParameter } block[1...n] = N[0...(n - 1)] // [i]8q in (16-q)...15 octets block[(16 - Int(q))...15] = i.bytes(totalBytes: Int(q)).slice return block } /// Resulting can be partitioned into 16-octet blocks private func format(aad: [UInt8]) -> [UInt8] { let a = aad.count switch Double(a) { case 0..<65280: // 2^16-2^8 // [a]16 return addPadding(a.bytes(totalBytes: 2) + aad, blockSize: 16) case 65280..<4_294_967_296: // 2^32 // [a]32 return addPadding([0xFF, 0xFE] + a.bytes(totalBytes: 4) + aad, blockSize: 16) case 4_294_967_296..<pow(2, 64): // 2^64 // [a]64 return addPadding([0xFF, 0xFF] + a.bytes(totalBytes: 8) + aad, blockSize: 16) default: // Reserved return addPadding(aad, blockSize: 16) } } // If data is not a multiple of block size bytes long then the remainder is zero padded // Note: It's similar to ZeroPadding, but it's not the same. private func addPadding(_ bytes: Array<UInt8>, blockSize: Int) -> Array<UInt8> { if bytes.isEmpty { return Array<UInt8>(repeating: 0, count: blockSize) } let remainder = bytes.count % blockSize if remainder == 0 { return bytes } let paddingCount = blockSize - remainder if paddingCount > 0 { return bytes + Array<UInt8>(repeating: 0, count: paddingCount) } return bytes }
gpl-3.0
f8542c327e1ae10079d360c7f241c41e
37.106443
230
0.689209
3.791527
false
false
false
false
renzeer/glimpse
Glimpse/TableViewController.swift
1
8824
// // TableViewController.swift // Glimpse // // Created by Renzee Reyes on 11/18/14. // Copyright (c) 2014 Renzee Reyes. All rights reserved. // import UIKit class TableViewController: UITableViewController { // Initialize array of custom cells var myCells: Array<(cellImage: UIImage, cellLikes: String, cellComments: String)> = [] // UIColor representing theme color let lightColor: UIColor = UIColor(red: 0.992, green: 0.89, blue: 0.655, alpha: 1) // Initialize UIRefreshControl var refresh:UIRefreshControl! // Initialize UITableView on laod override func viewDidLoad() { super.viewDidLoad() // Visual properties self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine self.tableView.backgroundColor = lightColor // Refresh properties self.refresh = UIRefreshControl() self.refresh.addTarget(self, action: "invokeRefresh", forControlEvents: UIControlEvents.ValueChanged) self.refresh.attributedTitle = NSAttributedString(string: "Pull to refersh") self.tableView.addSubview(refresh) // Seed data myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "32 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "28 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "19 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "32 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "28 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "19 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "32 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "28 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") myCells.append(cellImage: UIImage(named: "placeholder.png")!, cellLikes: "19 Likes", cellComments: "> Awesome pic! Where was this pic taken?\n> wow this looks really familiar\n> I think this is by my house") // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // On refresh, update refresh properties func invokeRefresh() { self.tableView.reloadData() var formatter = NSDateFormatter() formatter.dateFormat = "MMM d 'at' h:mm a" var lastUpdate = "Last update: \(formatter.stringFromDate(NSDate()))" let attriString = NSAttributedString(string:lastUpdate, attributes: [NSForegroundColorAttributeName: UIColor.blackColor()]) self.refresh.attributedTitle = attriString self.refresh.endRefreshing() } override func viewDidLayoutSubviews() { self.tableView.separatorInset = UIEdgeInsetsZero self.tableView.layoutMargins = UIEdgeInsetsZero } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source // Return number of sections within table override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. if (myCells.count > 0) { return 1; } else { var messageLabel = UILabel(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)) messageLabel.text = "No data currently available\nPull down to refresh" messageLabel.textAlignment = NSTextAlignment.Center messageLabel.numberOfLines = 0 messageLabel.font = UIFont (name: "Palatino-Italic", size: 20) self.tableView.backgroundView = messageLabel; self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None } return 0; } // Return number of rows in section override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return myCells.count } // Initialize cells for each row override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell // Configure the cell... //let cellID:String = "Cell" //var cell:UITableViewCell = tableView cell.separatorInset = UIEdgeInsetsZero cell.layoutMargins = UIEdgeInsetsZero cell.cellComments.numberOfLines = 0 cell.cellComments.font = UIFont(name: "Arial Unicode MS", size: 16) cell.cellLikes.font = UIFont(name: "Arial Unicode MS", size: 16) // Text properties var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 0 paragraphStyle.lineHeightMultiple = 0.8 // Comment properties var commentAttriString = NSMutableAttributedString(string: myCells[indexPath.row].cellComments as String) commentAttriString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, commentAttriString.length)) // Set values of cell cell.cellComments.attributedText = commentAttriString cell.cellLikes.text = myCells[indexPath.row].cellLikes as String cell.cellImage.image = myCells[indexPath.row].cellImage as UIImage return cell } func degToRad(deg: Int) -> Float { return Float(deg) * Float(M_PI / 180.0) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
apache-2.0
b4def621507c3c4c0c4f741864942c18
46.187166
215
0.680644
4.957303
false
false
false
false
SkylineCS/Frog-Team
frog app/AppDelegate.swift
1
2811
// // AppDelegate.swift // frog app // // Created by Mac User on 7/7/16. // Copyright © 2016 the juan and only. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) var storyboard = UIStoryboard(name: "Main", bundle: nil) var initialViewController = storyboard.instantiateViewControllerWithIdentifier("MainVC") self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() // Override point for customization after application launch. var pageController = UIPageControl.appearance() pageController.pageIndicatorTintColor = UIColor.lightGrayColor() pageController.currentPageIndicatorTintColor = UIColor.blackColor() pageController.backgroundColor = UIColor.whiteColor() 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:. } }
apache-2.0
4c6929c182ce242ed8b13f31ab632c3b
43.603175
285
0.733096
5.841996
false
false
false
false
tomasharkema/HoelangTotTrein.iOS
HoelangTotTrein/PickerCellView.swift
1
910
// // PickerCellView.swift // HoelangTotTrein // // Created by Tomas Harkema on 15-02-15. // Copyright (c) 2015 Tomas Harkema. All rights reserved. // import UIKit class PickerCellView : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) selectionStyle = UITableViewCellSelectionStyle.None } var station:Station! { didSet { nameLabel.text = station.name.lang } } override func setSelected(selected: Bool, animated: Bool) { nameLabel.textColor = selected ? UIColor.blackColor() : UIColor.whiteColor() contentView.backgroundColor = selected ? UIColor.whiteColor().colorWithAlphaComponent(0.5) : UIColor.clearColor() backgroundColor = UIColor.clearColor() super.setSelected(selected, animated: animated) } }
apache-2.0
0bde203b0e1797fbdd3d9c7539e9171e
27.4375
121
0.665934
4.619289
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/Ulises-Mendez/2.swift
1
452
import Glibc print("2) "); print("8.23 Una mujer arroja su libro de bolsillo desde lo alto de la torre de Sears (con 1451 pies de altura). Escribir un programa para determinar la velocidad de impacto al nivel del piso. Usart la formula V= sqrt2gh, donde la h es la altura de la torre y g = 32 pies/seg^2 es la constante gravitacional de la tierra"); var g: Double var h: Double var v: Double g=32; h=1451; v=sqrt(2*g*h) print(v,"pies/seg cuadrado");
gpl-3.0
023945e6b99a97b62cc38749a553de7e
36.666667
322
0.734513
2.658824
false
false
false
false
hooman/swift
test/decl/var/lazy_properties.swift
9
6674
// RUN: %target-typecheck-verify-swift -parse-as-library lazy func lazy_func() {} // expected-error {{'lazy' may only be used on 'var' declarations}} {{1-6=}} lazy var b = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{1-6=}} struct S { lazy static var lazy_global = 42 // expected-error {{'lazy' cannot be used on an already-lazy global}} {{3-8=}} } protocol SomeProtocol { lazy var x : Int // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}} // expected-error@-1 {{property in protocol must have explicit { get } or { get set } specifier}} {{19-19= { get <#set#> \}}} // expected-error@-2 {{lazy properties must have an initializer}} lazy var y : Int { get } // expected-error {{'lazy' cannot be used on a protocol requirement}} {{3-8=}} // expected-error@-1 {{'lazy' cannot be used on a computed property}} // expected-error@-2 {{lazy properties must have an initializer}} } class TestClass { lazy var a = 42 lazy var a1 : Int = 42 lazy let b = 42 // expected-error {{'lazy' cannot be used on a let}} {{3-8=}} lazy var c : Int { return 42 } // expected-error {{'lazy' cannot be used on a computed property}} {{3-8=}} // expected-error@-1 {{lazy properties must have an initializer}} lazy var d : Int // expected-error {{lazy properties must have an initializer}} {{3-8=}} lazy var (e, f) = (1,2) // expected-error 2{{'lazy' cannot destructure an initializer}} {{3-8=}} lazy var g = { 0 }() // single-expr closure lazy var h : Int = { 0 }() // single-expr closure lazy var i = { () -> Int in return 0 }()+1 // multi-stmt closure lazy var j : Int = { return 0 }()+1 // multi-stmt closure lazy var k : Int = { () -> Int in return 0 }()+1 // multi-stmt closure lazy var l : Int = 42 { // Okay didSet {} willSet {} } lazy var m : Int = 42 { // Okay didSet {} } lazy var n : Int = 42 { willSet {} // Okay } init() { lazy var localvar = 42 // Okay localvar += 1 _ = localvar } } struct StructTest { lazy var p1 : Int = 42 mutating func f1() -> Int { return p1 } // expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} func f2() -> Int { return p1 // expected-error {{cannot use mutating getter on immutable value: 'self' is immutable}} } static func testStructInits() { let a = StructTest() // default init let b = StructTest(p1: 42) // Override the lazily init'd value. _ = a; _ = b } } // <rdar://problem/16889110> capture lists in lazy member properties cannot use self class CaptureListInLazyProperty { lazy var closure1 = { [weak self] in return self!.i } lazy var closure2: () -> Int = { [weak self] in return self!.i } var i = 42 } // Crash when initializer expression is type-checked both to infer the // property type and also as part of the getter class WeShouldNotReTypeCheckStatements { lazy var firstCase = { _ = nil // expected-error{{'nil' requires a contextual type}} _ = () } lazy var secondCase = { _ = () _ = () } } protocol MyProtocol { func f() -> Int } struct MyStruct : MyProtocol { func f() -> Int { return 0 } } struct Outer { static let p: MyProtocol = MyStruct() struct Inner { lazy var x = p.f() lazy var y = {_ = 3}() // expected-warning@-1 {{variable 'y' inferred to have type '()', which may be unexpected}} // expected-note@-2 {{add an explicit type annotation to silence this warning}} {{15-15=: ()}} } } // https://bugs.swift.org/browse/SR-2616 struct Construction { init(x: Int, y: Int? = 42) { } } class Constructor { lazy var myQ = Construction(x: 3) } // Problems with self references class BaseClass { var baseInstanceProp = 42 static var baseStaticProp = 42 } class ReferenceSelfInLazyProperty : BaseClass { lazy var refs = (i, f()) lazy var trefs: (Int, Int) = (i, f()) lazy var qrefs = (self.i, self.f()) lazy var qtrefs: (Int, Int) = (self.i, self.f()) lazy var crefs = { (i, f()) }() lazy var ctrefs: (Int, Int) = { (i, f()) }() lazy var cqrefs = { (self.i, self.f()) }() lazy var cqtrefs: (Int, Int) = { (self.i, self.f()) }() lazy var mrefs = { () -> (Int, Int) in return (i, f()) }() lazy var mtrefs: (Int, Int) = { return (i, f()) }() lazy var mqrefs = { () -> (Int, Int) in (self.i, self.f()) }() lazy var mqtrefs: (Int, Int) = { return (self.i, self.f()) }() lazy var lcqrefs = { [unowned self] in (self.i, self.f()) }() lazy var lcqtrefs: (Int, Int) = { [unowned self] in (self.i, self.f()) }() lazy var lmrefs = { [unowned self] () -> (Int, Int) in return (i, f()) }() lazy var lmtrefs: (Int, Int) = { [unowned self] in return (i, f()) }() lazy var lmqrefs = { [unowned self] () -> (Int, Int) in (self.i, self.f()) }() lazy var lmqtrefs: (Int, Int) = { [unowned self] in return (self.i, self.f()) }() var i = 42 func f() -> Int { return 0 } lazy var refBaseClassProp = baseInstanceProp } class ReferenceStaticInLazyProperty { lazy var refs1 = i // expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var refs2 = f() // expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var trefs1: Int = i // expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var trefs2: Int = f() // expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} static var i = 42 static func f() -> Int { return 0 } } // Explicit access to the lazy variable storage class LazyVarContainer { lazy var foo: Int = { return 0 }() func accessLazyStorage() { $__lazy_storage_$_foo = nil // expected-error {{access to the underlying storage of a lazy property is not allowed}} print($__lazy_storage_$_foo!) // expected-error {{access to the underlying storage of a lazy property is not allowed}} _ = $__lazy_storage_$_foo == nil // expected-error {{access to the underlying storage of a lazy property is not allowed}} } } // Make sure we can still access a synthesized variable with the same name as a lazy storage variable // i.e. $__lazy_storage_$_{property_name} when using property wrapper where the property name is // '__lazy_storage_$_{property_name}'. @propertyWrapper struct Wrapper { var wrappedValue: Int { 1 } var projectedValue: Int { 1 } } struct PropertyWrapperContainer { @Wrapper var __lazy_storage_$_foo func test() { _ = $__lazy_storage_$_foo // This is okay. } }
apache-2.0
4286eb2e829e3db09522780f5fc52d1a
29.336364
127
0.623914
3.476042
false
false
false
false
vector-im/vector-ios
Riot/Modules/KeyVerification/Common/Verify/Scanning/KeyVerificationVerifyByScanningViewController.swift
1
14274
// File created from ScreenTemplate // $ createScreen.sh Verify KeyVerificationVerifyByScanning /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class KeyVerificationVerifyByScanningViewController: UIViewController { // MARK: - Constants // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var closeButton: UIButton! @IBOutlet private weak var titleView: UIView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var codeImageView: UIImageView! @IBOutlet private weak var scanCodeButton: UIButton! @IBOutlet private weak var cannotScanButton: UIButton! @IBOutlet private weak var qrCodeContainerView: UIView! @IBOutlet private weak var scanButtonContainerView: UIView! // MARK: Private private var viewModel: KeyVerificationVerifyByScanningViewModelType! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var cameraAccessAlertPresenter: CameraAccessAlertPresenter! private var cameraAccessManager: CameraAccessManager! private weak var qrCodeReaderViewController: QRCodeReaderViewController? private var alertPresentingViewController: UIViewController { return self.qrCodeReaderViewController ?? self } // MARK: - Setup class func instantiate(with viewModel: KeyVerificationVerifyByScanningViewModelType) -> KeyVerificationVerifyByScanningViewController { let viewController = StoryboardScene.KeyVerificationVerifyByScanningViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.cameraAccessAlertPresenter = CameraAccessAlertPresenter() self.cameraAccessManager = CameraAccessManager() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor if let themableCloseButton = self.closeButton as? Themable { themableCloseButton.update(theme: theme) } theme.applyStyle(onButton: self.scanCodeButton) theme.applyStyle(onButton: self.cannotScanButton) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.titleView.isHidden = self.navigationController != nil self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.title = VectorL10n.keyVerificationVerifyQrCodeTitle self.titleLabel.text = VectorL10n.keyVerificationVerifyQrCodeTitle self.informationLabel.text = VectorL10n.keyVerificationVerifyQrCodeInformation // Hide until we have the type of the verification request self.scanCodeButton.isHidden = true self.cannotScanButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeCannotScanAction, for: .normal) } private func render(viewState: KeyVerificationVerifyByScanningViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(viewData: let viewData): self.renderLoaded(viewData: viewData) case .error(let error): self.render(error: error) case .scannedCodeValidated(let isValid): self.renderScannedCode(valid: isValid) case .cancelled(let reason, let verificationKind): self.renderCancelled(reason: reason, verificationKind: verificationKind) case .cancelledByMe(let reason): self.renderCancelledByMe(reason: reason) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(viewData: KeyVerificationVerifyByScanningViewData) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) let hideQRCodeImage: Bool if let qrCodePayloadData = viewData.qrCodeData { hideQRCodeImage = false self.codeImageView.image = self.qrCodeImage(from: qrCodePayloadData) } else { hideQRCodeImage = true } self.title = viewData.verificationKind.verificationTitle self.titleLabel.text = viewData.verificationKind.verificationTitle self.qrCodeContainerView.isHidden = hideQRCodeImage self.scanButtonContainerView.isHidden = !viewData.showScanAction if viewData.qrCodeData == nil && viewData.showScanAction == false { // Update the copy if QR code scanning is not possible at all self.informationLabel.text = VectorL10n.keyVerificationVerifyQrCodeEmojiInformation self.cannotScanButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeStartEmojiAction, for: .normal) } else { let informationText: String switch viewData.verificationKind { case .user: informationText = VectorL10n.keyVerificationVerifyQrCodeInformation self.scanCodeButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeScanCodeAction, for: .normal) default: informationText = VectorL10n.keyVerificationVerifyQrCodeInformationOtherDevice self.scanCodeButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeScanCodeOtherDeviceAction, for: .normal) } self.scanCodeButton.isHidden = false self.informationLabel.text = informationText } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func qrCodeImage(from data: Data) -> UIImage? { let codeGenerator = QRCodeGenerator() return codeGenerator.generateCode(from: data, with: self.codeImageView.frame.size) } private func presentQRCodeReader(animated: Bool) { let qrCodeViewController = QRCodeReaderViewController.instantiate() qrCodeViewController.delegate = self self.present(qrCodeViewController, animated: animated, completion: nil) self.qrCodeReaderViewController = qrCodeViewController } private func renderScannedCode(valid: Bool) { if valid { self.stopQRCodeScanningIfPresented() self.presentCodeValidated(animated: true) { self.dismissQRCodeScanningIfPresented(animated: true, completion: { self.viewModel.process(viewAction: .acknowledgeMyUserScannedOtherCode) }) } } } private func renderCancelled(reason: MXTransactionCancelCode, verificationKind: KeyVerificationKind) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.stopQRCodeScanningIfPresented() // if we're verifying with someone else, let the user know they cancelled. // if we're verifying our own device, assume the user probably knows since it was them who // cancelled on their other device if verificationKind == .user { self.errorPresenter.presentError(from: self.alertPresentingViewController, title: "", message: VectorL10n.deviceVerificationCancelled, animated: true) { self.dismissQRCodeScanningIfPresented(animated: false) self.viewModel.process(viewAction: .cancel) } } else { self.dismissQRCodeScanningIfPresented(animated: false) self.viewModel.process(viewAction: .cancel) } } private func renderCancelledByMe(reason: MXTransactionCancelCode) { if reason.value != MXTransactionCancelCode.user().value { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: alertPresentingViewController, title: "", message: VectorL10n.deviceVerificationCancelledByMe(reason.humanReadable), animated: true) { self.dismissQRCodeScanningIfPresented(animated: false) self.viewModel.process(viewAction: .cancel) } } else { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } } private func presentCodeValidated(animated: Bool, completion: @escaping (() -> Void)) { let alert = UIAlertController(title: VectorL10n.keyVerificationVerifyQrCodeScanOtherCodeSuccessTitle, message: VectorL10n.keyVerificationVerifyQrCodeScanOtherCodeSuccessMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: VectorL10n.ok, style: .default, handler: { _ in completion() }) alert.addAction(okAction) if let qrCodeReaderViewController = self.qrCodeReaderViewController { qrCodeReaderViewController.present(alert, animated: animated, completion: nil) } } private func checkCameraAccessAndPresentQRCodeReader(animated: Bool) { guard self.cameraAccessManager.isCameraAvailable else { self.cameraAccessAlertPresenter.presentCameraUnavailableAlert(from: self, animated: animated) return } self.cameraAccessManager.askAndRequestCameraAccessIfNeeded { (granted) in if granted { self.presentQRCodeReader(animated: animated) } else { self.cameraAccessAlertPresenter.presentPermissionDeniedAlert(from: self, animated: animated) } } } private func stopQRCodeScanningIfPresented() { guard let qrCodeReaderViewController = self.qrCodeReaderViewController else { return } qrCodeReaderViewController.view.isUserInteractionEnabled = false qrCodeReaderViewController.stopScanning() } private func dismissQRCodeScanningIfPresented(animated: Bool, completion: (() -> Void)? = nil) { guard self.qrCodeReaderViewController?.presentingViewController != nil else { return } self.dismiss(animated: animated, completion: completion) } // MARK: - Actions @IBAction private func scanButtonAction(_ sender: Any) { self.checkCameraAccessAndPresentQRCodeReader(animated: true) } @IBAction private func cannotScanAction(_ sender: Any) { self.viewModel.process(viewAction: .cannotScan) } @IBAction private func closeButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .cancel) } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - KeyVerificationVerifyByScanningViewModelViewDelegate extension KeyVerificationVerifyByScanningViewController: KeyVerificationVerifyByScanningViewModelViewDelegate { func keyVerificationVerifyByScanningViewModel(_ viewModel: KeyVerificationVerifyByScanningViewModelType, didUpdateViewState viewSate: KeyVerificationVerifyByScanningViewState) { self.render(viewState: viewSate) } } // MARK: - QRCodeReaderViewControllerDelegate extension KeyVerificationVerifyByScanningViewController: QRCodeReaderViewControllerDelegate { func qrCodeReaderViewController(_ viewController: QRCodeReaderViewController, didFound payloadData: Data) { self.viewModel.process(viewAction: .scannedCode(payloadData: payloadData)) } func qrCodeReaderViewControllerDidCancel(_ viewController: QRCodeReaderViewController) { self.dismissQRCodeScanningIfPresented(animated: true) } }
apache-2.0
a6a5ab3e5ef91c4f68ddb9c5c56bb7fc
39.095506
185
0.688805
6.040626
false
false
false
false
manfengjun/KYMart
Section/Mine/Controller/KYAfterServiceViewController.swift
1
2465
// // KYProductContentViewController.swift // KYMart // // Created by Jun on 2017/6/10. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import WebKit class KYAfterServiceViewController: BaseViewController { /// 详情展示WebView fileprivate lazy var webView : WKWebView = { let webView = WKWebView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64)) webView.uiDelegate = self webView.navigationDelegate = self webView.scrollView.isScrollEnabled = true let urlStr = SJBRequestUrl.returnAfterServiceUrl() let url = URL(string: urlStr) webView.load(URLRequest(url: url!)) return webView }() override func viewDidLoad() { super.viewDidLoad() setBackButtonInNav() view.addSubview(webView) // Do any additional setup after loading the view. } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } // MARK: ------ WKUIDelegate extension KYAfterServiceViewController:WKUIDelegate,WKNavigationDelegate{ func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print("加载中") } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { print("内容开始返回") } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { print("加载完成") // autolayoutWebView() // if let allphoto = model?.images { // getImageFromDownloaderOrDiskByImageUrlArray(allphoto) // } // SVProgressHUD.dismiss() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("加载失败") } func filterHTML(_ string: String) -> String { return (string as NSString).replacingOccurrences(of: "<p>&nbsp;</p>", with: "") } }
mit
73cd47b9135a9c06a0b208855ee953be
30.842105
108
0.634298
4.938776
false
false
false
false
cristinasitaa/Bubbles
Bubbles/CSBubbleNode.swift
2
3886
// // BubbleNode.swift // Bubbles // // Created by Admin on 4/11/17. // Copyright © 2017 Admin. All rights reserved. // import Foundation import UIKit import SpriteKit //import CSFloatingCollection open class CSBubbleNode: CSFloatingNode { var labelNode = SKLabelNode(fontNamed: "Arial") var messageNode = SKLabelNode(fontNamed: "Arial") var message : String! var primaryColor : SKColor! { didSet { updatePrimaryColor() } } var secondaryColor : SKColor! { didSet { updateSecondaryColor() } } class func instantiateWithTitle(title: String) -> CSBubbleNode! { let node = CSBubbleNode(circleOfRadius: 30) configureNodeWithTitle(node,title: title) return node } class func configureNodeWithTitle(_ node: CSBubbleNode!, title: String) { let boundingBox = node.path?.boundingBox; let radius = (boundingBox?.size.width)! / 2.0; node.physicsBody = SKPhysicsBody(circleOfRadius: radius + 1.5) node.message = title } func updatePrimaryColor(){ self.labelNode.fontColor = self.primaryColor self.messageNode.fontColor = self.primaryColor self.labelNode.text = self.message self.labelNode.position = CGPoint.zero self.labelNode.fontColor = self.primaryColor self.labelNode.fontSize = 10 self.labelNode.isUserInteractionEnabled = false self.labelNode.verticalAlignmentMode = .center self.labelNode.horizontalAlignmentMode = .center self.messageNode = self.labelNode.multilined() self.messageNode.position = CGPoint.zero //CGPoint(x: frame.midX, y: frame.midY) self.messageNode.zPosition = 1001 // On top of all other nodes self.labelNode = self.messageNode self.addChild(self.messageNode) } func updateSecondaryColor() { self.fillColor = self.secondaryColor self.strokeColor = self.secondaryColor } override open func selectingAnimation() -> SKAction? { removeAction(forKey: CSBubbleNode.removingKey) for children in self.messageNode.children { if children.name == "innerLabel" { let childNodeLabel = children as! SKLabelNode childNodeLabel.fontColor = secondaryColor NotificationCenter.default.post(name: NSNotification.Name(rawValue: "BubbleWasSelected"), object: childNodeLabel.text) } } self.fillColor = self.primaryColor self.strokeColor = self.primaryColor return SKAction.scale(to: 2, duration: 0.2) } override open func normalizeAnimation() -> SKAction? { removeAction(forKey: CSBubbleNode.removingKey) for children in self.messageNode.children { if children.name == "innerLabel" { let childNodeLabel = children as! SKLabelNode childNodeLabel.fontColor = self.primaryColor NotificationCenter.default.post(name: NSNotification.Name(rawValue: "BubbleWasDeselected"), object: childNodeLabel.text) } } self.fillColor = secondaryColor self.strokeColor = secondaryColor return SKAction.scale(to: 1, duration: 0.2) } override open func removeAnimation() -> SKAction? { removeAction(forKey: CSBubbleNode.removingKey) return SKAction.fadeOut(withDuration: 0.2) } override open func removingAnimation() -> SKAction { let pulseUp = SKAction.scale(to: xScale + 0.13, duration: 0) let pulseDown = SKAction.scale(to: xScale, duration: 0.3) let pulse = SKAction.sequence([pulseUp, pulseDown]) let repeatPulse = SKAction.repeatForever(pulse) return repeatPulse } }
mit
8ef5500b10b007926c7d5aa77e5e6692
31.647059
136
0.639382
4.732034
false
false
false
false
LUSHDigital/LushKit-iOS
LushKit/LushKit/Constants.swift
1
1223
// // Constants.swift // LushKit // // Created by Ashley Cabico on 06/12/2016. // Copyright © 2016 Lush Ltd. All rights reserved. // import Foundation import UIKit // margins public let kDefaultMargin: CGFloat = 24.0 public let kDoubleMargin = kDefaultMargin * 2.0 public let kHalfMargin = kDefaultMargin / 2.0 public let kQuarterMargin = kHalfMargin / 2.0 // text let kDefaultTextMinimumScaleFactor: CGFloat = 0.8 let kLargeTextMinimumScaleFactor: CGFloat = 0.5 // buttons public let kDefaultButtonWidth: CGFloat = 44.0 public let kDefaultButtonHeight: CGFloat = 44.0 public let kButtonPading: CGFloat = 30.0 // picker views public let kDefaultPickerViewRowHeight: CGFloat = 50.0 // borders public let kHalfPixel: CGFloat = (1.0 / UIScreen.main.scale) public let kDefaultBorderWidth: CGFloat = 1.0 public let kDoubleBorderWidth: CGFloat = 2.0 public let kBorderViewDefaultHeight: CGFloat = kHalfPixel // shading let kOverlayAlpha: CGFloat = 0.26
apache-2.0
1eae60e31e177005e819ca391db70bae
32.027027
84
0.599836
4.318021
false
false
false
false
seaburg/IGIdenticon
Identicon/IconGenerator.swift
1
2154
// // IconGenerator.swift // IGIdenticonExample // // Created by Evgeniy Yurtaev on 19/11/2016. // Copyright © 2016 Evgeniy Yurtaev. All rights reserved. // import CoreGraphics #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(macOS) import AppKit #endif public protocol IconGenerator { func icon(from number: UInt32, size: CGSize) -> CGImage } #if os(iOS) || os(tvOS) public extension IconGenerator { func icon(from number: UInt32, size: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage { let scaledSize = CGSize(width: size.width * scale, height: size.height * scale) let cgImage: CGImage = icon(from: number, size: scaledSize) return UIImage(cgImage: cgImage, scale: scale, orientation: UIImage.Orientation.up) } func icon(from data: Data, size: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage { let hash = jenkinsHash(from: data) let image = icon(from: hash, size: size, scale: scale) return image } func icon(from string: String, size: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage? { guard let data = string.data(using: String.Encoding.utf8) else { return nil } let image = icon(from: data, size: size, scale: scale) return image } } #endif #if os(macOS) public extension IconGenerator { func icon(from number: UInt32, size: CGSize, scale: CGFloat) -> NSImage { let scaledSize = CGSize(width: size.width * scale, height: size.height * scale) let cgImage: CGImage = icon(from: number, size: scaledSize) return NSImage(cgImage: cgImage, size: size) } func icon(from data: Data, size: CGSize, scale: CGFloat) -> NSImage { let hash = jenkinsHash(from: data) let image = icon(from: hash, size: size, scale: scale) return image } func icon(from string: String, size: CGSize, scale: CGFloat) -> NSImage? { guard let data = string.data(using: String.Encoding.utf8) else { return nil } let image = icon(from: data, size: size, scale: scale) return image } } #endif
mit
adc5442cc3213b3758f9ae391a03f683
30.661765
100
0.643753
3.757417
false
false
false
false
iMemon/ISYSSnapStoryViewController
Example/ISYSSnapStoryViewController/SnapTimer/SnapTimer/SnapTimerView.swift
1
4966
// // SnapTimerView.swift // SnapTimer // // Created by Andres on 8/18/16. // Copyright © 2016 Andres. All rights reserved. // import UIKit @IBDesignable open class SnapTimerView: UIView { static let startAngle = 3/2 * CGFloat(M_PI) static let endAngle = 7/2 * CGFloat(M_PI) internal var mainCircleLayer: SnapTimerCircleLayer! internal var centerLayer: SnapTimerCircleLayer! internal var borderLayer: SnapTimerBorderLayer! internal var animationsPaused = false @IBInspectable var mainBackgroundColor: UIColor = UIColor.darkGray { didSet { self.mainCircleLayer.circleColor = self.mainBackgroundColor.cgColor } } @IBInspectable var centerBackgroundColor: UIColor = UIColor.lightGray { didSet { self.centerLayer.circleColor = self.centerBackgroundColor.cgColor } } @IBInspectable var borderBackgroundColor: UIColor = UIColor.white { didSet { self.borderLayer.circleColor = borderBackgroundColor.cgColor } } fileprivate var outerProperty: CGFloat = 0 fileprivate var innerProperty: CGFloat = 0 @IBInspectable var outerValue: CGFloat { set { CATransaction.begin() CATransaction.setDisableActions(true) self.animateOuterValue(newValue) CATransaction.commit() } get { return self.outerProperty } } @IBInspectable var innerValue: CGFloat { set { CATransaction.begin() CATransaction.setDisableActions(true) self.animateInnerValue(newValue) CATransaction.commit() } get { return self.innerProperty } } open func animateOuterValue(_ value: CGFloat) { self.outerProperty = SnapTimerView.sanitizeValue(value) self.borderLayer.startAngle = SnapTimerView.radianForValue(self.outerProperty) } open func animateInnerValue(_ value: CGFloat) { self.innerProperty = SnapTimerView.sanitizeValue(value) self.centerLayer.startAngle = SnapTimerView.radianForValue(self.innerProperty) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } required override public init(frame: CGRect) { super.init(frame: frame) commonInit() } override open func prepareForInterfaceBuilder() { commonInit() } override open func layoutSubviews() { super.layoutSubviews() let radius = min(bounds.width, bounds.height) * 0.5 self.mainCircleLayer.radius = radius self.mainCircleLayer.frame = self.bounds self.centerLayer.radius = radius/2 self.centerLayer.frame = self.bounds self.borderLayer.radius = radius * 0.75 self.borderLayer.width = radius * 0.33 self.borderLayer.frame = self.bounds } fileprivate func commonInit() { self.mainCircleLayer = SnapTimerCircleLayer() self.mainCircleLayer.circleColor = self.mainBackgroundColor.cgColor self.mainCircleLayer.contentsScale = UIScreen.main.scale self.layer.addSublayer(mainCircleLayer) self.centerLayer = SnapTimerCircleLayer() self.centerLayer.circleColor = self.centerBackgroundColor.cgColor self.centerLayer.startAngle = SnapTimerView.radianForValue(self.innerProperty) self.centerLayer.contentsScale = UIScreen.main.scale self.layer.addSublayer(centerLayer) self.borderLayer = SnapTimerBorderLayer() self.borderLayer.circleColor = self.borderBackgroundColor.cgColor self.borderLayer.startAngle = SnapTimerView.radianForValue(self.outerProperty) self.borderLayer.contentsScale = UIScreen.main.scale self.layer.addSublayer(borderLayer) } open func animateOuterToValue(_ value: CGFloat, duration: TimeInterval, completion: (() -> Void)?) { CATransaction.begin() CATransaction.setAnimationDuration(duration) CATransaction.setCompletionBlock(completion) self.animateOuterValue(value) CATransaction.commit() } open func animateInnerToValue(_ value: CGFloat, duration: TimeInterval, completion: (() -> Void)?) { CATransaction.begin() CATransaction.setAnimationDuration(duration) CATransaction.setCompletionBlock(completion) self.animateInnerValue(value) CATransaction.commit() } open func pauseAnimation() { self.animationsPaused = true let pausedTime = self.layer.convertTime(CACurrentMediaTime(), from: nil) self.layer.speed = 0.0 self.layer.timeOffset = pausedTime } open func resumeAnimation() { if !self.animationsPaused { return } self.animationsPaused = false let pausedTime = self.layer.timeOffset self.layer.speed = 1.0 self.layer.timeOffset = 0.0 self.layer.beginTime = 0.0 let timeSincePause = self.layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime self.layer.beginTime = timeSincePause } internal class func sanitizeValue(_ value: CGFloat) -> CGFloat { var realValue = value if value < 0 { realValue = 0 } else if value > 100 { realValue = 100 } return realValue } internal class func radianForValue(_ value: CGFloat) -> CGFloat { let realValue = SnapTimerView.sanitizeValue(value) return (realValue * 4/2 * CGFloat(M_PI) / 100) + SnapTimerView.startAngle } }
mit
4008118c58be6d01f7622d8ed6c5ab66
27.210227
101
0.748842
3.819231
false
false
false
false
swixbase/filesystem
Tests/FilesystemTests/FileOutputStreamerTests.swift
1
2142
/// Copyright 2017 Sergei Egorov /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. import XCTest import Foundation @testable import Filesystem class FileOutputStreamerTests: XCTestCase { let fsManager = FileSystem.default let fileHandler = FileHandler.default static var allTests : [(String, (FileOutputStreamerTests) -> () throws -> Void)] { return [ ("testWriteData", testWriteData) ] } // MARK: - Helpers func createTestFile(atPath path: String) { let content = "abcdefghijklmnopqrstuvwxyz".data(using: .utf8)! fsManager.createFile(atPath: path, content: content) } func deleteTestFile(atPath path: String) { do { try fsManager.deleteObject(atPath: path) } catch let error as FileSystemError { XCTFail(error.description) } catch { XCTFail("Unhandled error") } } // MARK: - Tests func testWriteData() throws { let testfilePath = "\(fsManager.workPath)/\(UUID().uuidString)" let fileOutStreamer: FileOutputStreamer = try FileOutputStreamer(file: testfilePath) let writeData = "abcdefghijklmnopqrstuvwxyz".data(using: .utf8)! let count = fileOutStreamer.write(content: writeData) fileOutStreamer.synchronize() let data = try fileHandler.readWholeFile(atPath: testfilePath) let content = String(data: data, encoding: .utf8)! XCTAssertEqual(content, "abcdefghijklmnopqrstuvwxyz") XCTAssertEqual(Int(count), writeData.count) deleteTestFile(atPath: testfilePath) } }
apache-2.0
0801dbf759240a84f311ead33b9ddc3c
31.454545
92
0.672736
4.728477
false
true
false
false
KokerWang/PDEXChart
PDEXChart/Lib/PDChartAxesComponent.swift
2
11642
// // AppDelegate.swift // PDEXChart // // Created by KokerWang on 15/3/17. // Copyright (c) 2015年 KokerWang. All rights reserved. // import UIKit class PDChartAxesComponentDataItem: NSObject { //required var targetView: UIView! var featureH: CGFloat! var featureW: CGFloat! var xMax: CGFloat! var xInterval: CGFloat! var yMax: CGFloat! var yInterval: CGFloat! var xAxesDegreeTexts: [String]? var yAxesDegreeTexts: [String]? //optional default var showAxes: Bool = true var showXDegree: Bool = true var showYDegree: Bool = true var axesColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴颜色 var axesTipColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴刻度值颜色 var xAxesLeftMargin: CGFloat = 50 //坐标系左边margin var xAxesRightMargin: CGFloat = 26 //坐标系右边margin var yAxesBottomMargin: CGFloat = 30 //坐标系下面margin var yAxesTopMargin: CGFloat = 30 //坐标系上方marign var axesWidth: CGFloat = 1.0 //坐标轴的粗细 var arrowHeight: CGFloat = 5.0 var arrowWidth: CGFloat = 5.0 var arrowBodyLength: CGFloat = 10.0 var degreeLength: CGFloat = 5.0 //坐标轴刻度直线的长度 var degreeTipFontSize: CGFloat = 10.0 var degreeTipMarginHorizon: CGFloat = 1.0 var degreeTipMarginVertical: CGFloat = 5.0 override init() { } } class PDChartAxesComponent: NSObject { var dataItem: PDChartAxesComponentDataItem! init(dataItem: PDChartAxesComponentDataItem) { self.dataItem = dataItem } func getYAxesHeight() -> CGFloat {//heigth between 0~yMax var basePoint: CGPoint = self.getBasePoint() var yAxesHeight = basePoint.y - dataItem.arrowHeight - dataItem.yAxesTopMargin - dataItem.arrowBodyLength return yAxesHeight } func getXAxesWidth() -> CGFloat {//width between 0~xMax var basePoint: CGPoint = self.getBasePoint() var xAxesWidth = dataItem.featureW - basePoint.x - dataItem.arrowHeight - dataItem.xAxesRightMargin - dataItem.arrowBodyLength return xAxesWidth } func getBasePoint() -> CGPoint { var neededAxesWidth: CGFloat! if dataItem.showAxes { neededAxesWidth = CGFloat(dataItem.axesWidth) } else { neededAxesWidth = 0 } var basePoint: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin + neededAxesWidth / 2.0, y: dataItem.featureH - (dataItem.yAxesBottomMargin + neededAxesWidth / 2.0)) return basePoint } func getXDegreeInterval() -> CGFloat { var xAxesWidth: CGFloat = self.getXAxesWidth() var xDegreeInterval: CGFloat = dataItem.xInterval / dataItem.xMax * xAxesWidth return xDegreeInterval } func getYDegreeInterval() -> CGFloat { var yAxesHeight: CGFloat = self.getYAxesHeight() var yDegreeInterval: CGFloat = dataItem.yInterval / dataItem.yMax * yAxesHeight return yDegreeInterval } func getAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat, textAlignment: NSTextAlignment, textColor: UIColor) -> UILabel { var label: UILabel = UILabel(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size)) label.text = tipText label.center = center label.textAlignment = textAlignment label.textColor = textColor label.backgroundColor = UIColor.clearColor() label.adjustsFontSizeToFitWidth = true label.font = UIFont.systemFontOfSize(fontSize) return label } func getXAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel { return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.Center, textColor: dataItem.axesTipColor) } func getYAxesDegreeTipLabel(tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel { return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.Right, textColor: dataItem.axesTipColor) } func strokeAxes(context: CGContextRef?) { var xAxesWidth: CGFloat = self.getXAxesWidth() var yAxesHeight: CGFloat = self.getYAxesHeight() var basePoint: CGPoint = self.getBasePoint() if dataItem.showAxes { CGContextSetStrokeColorWithColor(context, dataItem.axesColor.CGColor) CGContextSetFillColorWithColor(context, dataItem.axesColor.CGColor) var axesPath: UIBezierPath = UIBezierPath() axesPath.lineWidth = dataItem.axesWidth axesPath.lineCapStyle = kCGLineCapRound axesPath.lineJoinStyle = kCGLineJoinRound //x axes-------------------------------------- axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y)) axesPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y)) //degrees in x axes var xDegreeNum: Int = Int((dataItem.xMax - (dataItem.xMax % dataItem.xInterval)) / dataItem.xInterval) var xDegreeInterval: CGFloat = self.getXDegreeInterval() if dataItem.showXDegree { for var i = 0; i < xDegreeNum; i++ { var degreeX: CGFloat = basePoint.x + xDegreeInterval * CGFloat(i + 1) axesPath.moveToPoint(CGPoint(x: degreeX, y: basePoint.y)) axesPath.addLineToPoint(CGPoint(x: degreeX, y: basePoint.y - dataItem.degreeLength)) } } //x axes arrow //arrow body axesPath.moveToPoint(CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y)) axesPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y)) //arrow head var arrowPath: UIBezierPath = UIBezierPath() arrowPath.lineWidth = dataItem.axesWidth arrowPath.lineCapStyle = kCGLineCapRound arrowPath.lineJoinStyle = kCGLineJoinRound var xArrowTopPoint: CGPoint = CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength + dataItem.arrowHeight, y: basePoint.y) arrowPath.moveToPoint(xArrowTopPoint) arrowPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y - dataItem.arrowWidth / 2)) arrowPath.addLineToPoint(CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y + dataItem.arrowWidth / 2)) arrowPath.addLineToPoint(xArrowTopPoint) //y axes-------------------------------------- axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y)) axesPath.addLineToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight)) //degrees in y axes var yDegreesNum: Int = Int((dataItem.yMax - (dataItem.yMax % dataItem.yInterval)) / dataItem.yInterval) var yDegreeInterval: CGFloat = self.getYDegreeInterval() if dataItem.showYDegree { for var i = 0; i < yDegreesNum; i++ { var degreeY: CGFloat = basePoint.y - yDegreeInterval * CGFloat(i + 1) axesPath.moveToPoint(CGPoint(x: basePoint.x, y: degreeY)) axesPath.addLineToPoint(CGPoint(x: basePoint.x + dataItem.degreeLength, y: degreeY)) } } //y axes arrow //arrow body axesPath.moveToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight)) axesPath.addLineToPoint(CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) //arrow head var yArrowTopPoint: CGPoint = CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength - dataItem.arrowHeight) arrowPath.moveToPoint(yArrowTopPoint) arrowPath.addLineToPoint(CGPoint(x: basePoint.x - dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) arrowPath.addLineToPoint(CGPoint(x: basePoint.x + dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) arrowPath.addLineToPoint(yArrowTopPoint) axesPath.stroke() arrowPath.stroke() //axes tips------------------------------------ //func getXAxesDegreeTipLabel(tipText: String, frame: CGRect, fontSize: CGFloat) -> UILabel { if (dataItem.xAxesDegreeTexts != nil) { for var i = 0; i < dataItem.xAxesDegreeTexts!.count; i++ { var size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) var center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2) var label: UILabel = self.getXAxesDegreeTipLabel(dataItem.xAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } else { for var i = 0; i < xDegreeNum; i++ { var size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) var center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2) var label: UILabel = self.getXAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.xInterval)", center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } if (dataItem.yAxesDegreeTexts != nil) { for var i = 0; i < dataItem.yAxesDegreeTexts!.count; i++ { var size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) var center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1)) var label: UILabel = self.getYAxesDegreeTipLabel(dataItem.yAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } else { for var i = 0; i < yDegreesNum; i++ { var size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) var center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1)) var label: UILabel = self.getYAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.yInterval)", center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } } } }
mit
1692cd71a80021d6a6fff1d9508b65b8
48.536481
176
0.621383
4.435819
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Trivial - 不需要看的题目/标准库实现题/706_Design HashMap.swift
1
4092
// 706_Design HashMap // https://leetcode.com/problems/design-hashmap/ // // Created by Honghao Zhang on 10/12/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Design a HashMap without using any built-in hash table libraries. // //To be specific, your design should include these functions: // //put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value. //get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. //remove(key) : Remove the mapping for the value key if this map contains the mapping for the key. // //Example: // //MyHashMap hashMap = new MyHashMap(); //hashMap.put(1, 1); //hashMap.put(2, 2); //hashMap.get(1); // returns 1 //hashMap.get(3); // returns -1 (not found) //hashMap.put(2, 1); // update the existing value //hashMap.get(2); // returns 1 //hashMap.remove(2); // remove the mapping for 2 //hashMap.get(2); // returns -1 (not found) // //Note: // //All keys and values will be in the range of [0, 1000000]. //The number of operations will be in the range of [1, 10000]. //Please do not use the built-in HashMap library. // import Foundation class Num706 { // https://leetcode.com/problems/design-hashmap/discuss/225312/hashmaparraylinkedlistcollision // Make custom hash function // Handle collision // Swift explanation: https://medium.com/@stevenpcurtis.sc/implement-a-dictionary-in-swift-5e06052aa120 class MyHashMap { private static let loadFactor = 0.75 class Node { var key: Int var value: Int var next: Node? init(key: Int, value: Int, next: Node?) { self.key = key self.value = value self.next = next } } var buckets: [Node?] = Array(repeating: nil, count: 100005) // 100005 works var size: Int = 5 /** value will always be non-negative. */ func put(_ key: Int, _ value: Int) { let index = hash(key: key) var head = buckets[index] // If found a existing node in the list, update the value and early return while head != nil { if head!.key == key { head!.value = value return } head = head!.next } // Otherwise, insert a new node at the beginning buckets[index] = Node(key: key, value: value, next: buckets[index]) size += 1 let loadFactor = Double(size) / Double(buckets.count) if loadFactor > MyHashMap.loadFactor { rehash() } } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ func get(_ key: Int) -> Int { let index = hash(key: key) var head = buckets[index] while head != nil { if head!.key == key { return head!.value } head = head!.next } return -1 } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ func remove(_ key: Int) { let index = hash(key: key) var prev = Node(key: -1, value: -1, next: buckets[index]) var current = prev.next while current != nil { if current!.key == key { prev.next = current!.next buckets[index] = prev.next size -= 1 return } prev = current! current = current!.next } } private func hash(key: Int) -> Int { return key % buckets.count } private func rehash() { let temp = buckets buckets = Array(repeating: nil, count: temp.count * 2) size = 0 for head in temp { var node = head while node != nil { put(node!.key, node!.value) node = node!.next } } } } // // /** // * Your MyHashMap object will be instantiated and called as such: // * let obj = MyHashMap() // * obj.put(key, value) // * let ret_2: Int = obj.get(key) // * obj.remove(key) // */ }
mit
b7f85756920bb684440c203b55631697
28.014184
126
0.588609
3.712341
false
false
false
false
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/UPnP Foundation/SSDPType.swift
1
3712
// // SSDPType.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public enum SSDPTypeConstant: String { // General case All = "ssdp:all" case RootDevice = "upnp:rootdevice" // UPnP A/V profile case MediaServerDevice1 = "urn:schemas-upnp-org:device:MediaServer:1" case MediaRendererDevice1 = "urn:schemas-upnp-org:device:MediaRenderer:1" case ContentDirectory1Service = "urn:schemas-upnp-org:service:ContentDirectory:1" case ConnectionManager1Service = "urn:schemas-upnp-org:service:ConnectionManager:1" case RenderingControl1Service = "urn:schemas-upnp-org:service:RenderingControl:1" case AVTransport1Service = "urn:schemas-upnp-org:service:AVTransport:1" } enum SSDPType: RawRepresentable { case all case rootDevice case uuid(String) case device(String) case service(String) typealias RawValue = String init?(rawValue: RawValue) { if rawValue == "ssdp:all" { self = .all } else if rawValue == "upnp:rootdevice" { self = .rootDevice } else if rawValue.range(of: "uuid:") != nil { self = .uuid(rawValue) } else if rawValue.range(of: ":device:") != nil { self = .device(rawValue) } else if rawValue.range(of: ":service:") != nil { self = .service(rawValue) } else { return nil } } init?(typeConstant: SSDPTypeConstant) { self.init(rawValue: typeConstant.rawValue) } var rawValue: RawValue { switch self { case .all: return "ssdp:all" case .rootDevice: return "upnp:rootdevice" case .uuid(let rawValue): return rawValue case .device(let rawValue): return rawValue case .service(let rawValue): return rawValue } } } extension SSDPType: CustomStringConvertible { var description: String { return self.rawValue } } extension SSDPType: Hashable { var hashValue: Int { return self.rawValue.hashValue } } func ==(lhs: SSDPType, rhs: SSDPType) -> Bool { switch (lhs, rhs) { case (.all, .all): return true case (.rootDevice, .rootDevice): return true case (.uuid(let lhsRawValue), .uuid(let rhsRawValue)): return lhsRawValue == rhsRawValue case (.device(let lhsRawValue), .device(let rhsRawValue)): return lhsRawValue == rhsRawValue case (.service(let lhsRawValue), .service(let rhsRawValue)): return lhsRawValue == rhsRawValue default: return false } }
apache-2.0
0a6e7e27937911838ae7c4d3622584e7
32.745455
87
0.655172
4.070175
false
false
false
false
jonkykong/SideMenu
Pod/Classes/SideMenuPresentationStyle.swift
1
6024
// // SideMenuPresentStyle.swift // SideMenu // // Created by Jon Kent on 7/2/19. // import UIKit @objcMembers open class SideMenuPresentationStyle: InitializableClass { /// Background color behind the views and status bar color open var backgroundColor: UIColor = .black /// The starting alpha value of the menu before it appears open var menuStartAlpha: CGFloat = 1 /// Whether or not the menu is on top. If false, the presenting view is on top. Shadows are applied to the view on top. open var menuOnTop: Bool = false /// The amount the menu is translated along the x-axis. Zero is stationary, negative values are off-screen, positive values are on screen. open var menuTranslateFactor: CGFloat = 0 /// The amount the menu is scaled. Less than one shrinks the view, larger than one grows the view. open var menuScaleFactor: CGFloat = 1 /// The color of the shadow applied to the top most view. open var onTopShadowColor: UIColor = .black /// The radius of the shadow applied to the top most view. open var onTopShadowRadius: CGFloat = 5 /// The opacity of the shadow applied to the top most view. open var onTopShadowOpacity: Float = 0 /// The offset of the shadow applied to the top most view. open var onTopShadowOffset: CGSize = .zero /// The ending alpha of the presenting view when the menu is fully displayed. open var presentingEndAlpha: CGFloat = 1 /// The amount the presenting view is translated along the x-axis. Zero is stationary, negative values are off-screen, positive values are on screen. open var presentingTranslateFactor: CGFloat = 0 /// The amount the presenting view is scaled. Less than one shrinks the view, larger than one grows the view. open var presentingScaleFactor: CGFloat = 1 /// The strength of the parallax effect on the presenting view once the menu is displayed. open var presentingParallaxStrength: CGSize = .zero required public init() {} /// This method is called just before the presentation transition begins. Use this to setup any animations. The super method does not need to be called. open func presentationTransitionWillBegin(to presentedViewController: UIViewController, from presentingViewController: UIViewController) {} /// This method is called during the presentation animation. Use this to animate anything alongside the menu animation. The super method does not need to be called. open func presentationTransition(to presentedViewController: UIViewController, from presentingViewController: UIViewController) {} /// This method is called when the presentation transition ends. Use this to finish any animations. The super method does not need to be called. open func presentationTransitionDidEnd(to presentedViewController: UIViewController, from presentingViewController: UIViewController, _ completed: Bool) {} /// This method is called just before the dismissal transition begins. Use this to setup any animations. The super method does not need to be called. open func dismissalTransitionWillBegin(to presentedViewController: UIViewController, from presentingViewController: UIViewController) {} /// This method is called during the dismissal animation. Use this to animate anything alongside the menu animation. The super method does not need to be called. open func dismissalTransition(to presentedViewController: UIViewController, from presentingViewController: UIViewController) {} /// This method is called when the dismissal transition ends. Use this to finish any animations. The super method does not need to be called. open func dismissalTransitionDidEnd(to presentedViewController: UIViewController, from presentingViewController: UIViewController, _ completed: Bool) {} } public extension SideMenuPresentationStyle { /// Menu slides in over the existing view. static var menuSlideIn: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuOnTop = true $0.menuTranslateFactor = -1 } } /// The existing view slides out to reveal the menu underneath. static var viewSlideOut: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.presentingTranslateFactor = 1 } } /// The existing view slides out while the menu slides in. static var viewSlideOutMenuIn: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuTranslateFactor = -1 $0.presentingTranslateFactor = 1 } } /// The menu dissolves in over the existing view. static var menuDissolveIn: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuStartAlpha = 0 $0.menuOnTop = true } } /// The existing view slides out while the menu partially slides in. static var viewSlideOutMenuPartialIn: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuTranslateFactor = -0.5 $0.presentingTranslateFactor = 1 } } /// The existing view slides out while the menu slides out from under it. static var viewSlideOutMenuOut: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuTranslateFactor = 1 $0.presentingTranslateFactor = 1 } } /// The existing view slides out while the menu partially slides out from under it. static var viewSlideOutMenuPartialOut: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.menuTranslateFactor = 0.5 $0.presentingTranslateFactor = 1 } } /// The existing view slides out and shrinks to reveal the menu underneath. static var viewSlideOutMenuZoom: SideMenuPresentationStyle { return SideMenuPresentationStyle { $0.presentingTranslateFactor = 1 $0.menuScaleFactor = 0.95 $0.menuOnTop = true } } }
mit
56cc6442c94215186671b3581ff85829
52.785714
168
0.723108
5.197584
false
false
false
false
Somnibyte/MLKit
Example/Pods/Upsurge/Source/Complex/ComplexArraySlice.swift
1
5140
// Copyright © 2015 Venture Media Labs. // // 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. open class ComplexArraySlice<T: Real>: MutableLinearType { public typealias Index = Int public typealias Element = Complex<T> public typealias Slice = ComplexArraySlice var base: ComplexArray<T> open var startIndex: Index open var endIndex: Index open var step: Index open var span: Span { return Span(ranges: [startIndex ... endIndex - 1]) } open func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeBufferPointer(body) } open func withUnsafePointer<R>(_ body: (UnsafePointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafePointer(body) } open func withUnsafeMutableBufferPointer<R>(_ body: (UnsafeMutableBufferPointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeMutableBufferPointer(body) } open func withUnsafeMutablePointer<R>(_ body: (UnsafeMutablePointer<Element>) throws -> R) rethrows -> R { return try base.withUnsafeMutablePointer(body) } open var reals: ComplexArrayRealSlice<T> { get { return ComplexArrayRealSlice<T>(base: base, startIndex: startIndex, endIndex: 2*endIndex - 1, step: 2) } set { precondition(newValue.count == reals.count) for i in 0..<newValue.count { self.reals[i] = newValue[i] } } } open var imags: ComplexArrayRealSlice<T> { get { return ComplexArrayRealSlice<T>(base: base, startIndex: startIndex + 1, endIndex: 2*endIndex, step: 2) } set { precondition(newValue.count == imags.count) for i in 0..<newValue.count { self.imags[i] = newValue[i] } } } public required init(base: ComplexArray<T>, startIndex: Index, endIndex: Index, step: Int) { assert(base.startIndex <= startIndex && endIndex <= base.endIndex) self.base = base self.startIndex = startIndex self.endIndex = endIndex self.step = step } open subscript(index: Index) -> Element { get { precondition(0 <= index && index < count) return base[index] } set { precondition(0 <= index && index < count) base[index] = newValue } } open subscript(indices: [Int]) -> Element { get { assert(indices.count == 1) return self[indices[0]] } set { assert(indices.count == 1) self[indices[0]] = newValue } } open subscript(intervals: [IntervalType]) -> Slice { get { assert(intervals.count == 1) let start = intervals[0].start ?? startIndex let end = intervals[0].end ?? endIndex return Slice(base: base, startIndex: start, endIndex: end, step: step) } set { assert(intervals.count == 1) let start = intervals[0].start ?? startIndex let end = intervals[0].end ?? endIndex assert(startIndex <= start && end <= endIndex) for i in start..<end { self[i] = newValue[newValue.startIndex + i - start] } } } open func index(after i: Index) -> Index { return i + 1 } open func formIndex(after i: inout Index) { i += 1 } } // MARK: - Equatable public func ==<T: Real>(lhs: ComplexArraySlice<T>, rhs: ComplexArraySlice<T>) -> Bool { if lhs.count != rhs.count { return false } for (i, v) in lhs.enumerated() { if v != rhs[i] { return false } } return true } public func ==<T: Real>(lhs: ComplexArraySlice<T>, rhs: ComplexArray<T>) -> Bool { if lhs.count != rhs.count { return false } for i in 0..<lhs.count { if lhs[i] != rhs[i] { return false } } return true }
mit
67d19485877d81ab0be881b340472449
31.320755
122
0.604398
4.422547
false
false
false
false
jtbandes/swift
test/SILGen/protocol_resilience.swift
5
17074
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_protocol prefix operator ~~~ {} infix operator <*> {} infix operator <**> {} infix operator <===> {} public protocol P {} // Protocol is public -- needs resilient witness table public protocol ResilientMethods { associatedtype AssocType : P func defaultWitness() func anotherDefaultWitness(_ x: Int) -> Self func defaultWitnessWithAssociatedType(_ a: AssocType) func defaultWitnessMoreAbstractThanRequirement(_ a: AssocType, b: Int) func defaultWitnessMoreAbstractThanGenericRequirement<T>(_ a: AssocType, t: T) func noDefaultWitness() func defaultWitnessIsNotPublic() static func staticDefaultWitness(_ x: Int) -> Self } extension ResilientMethods { // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP14defaultWitnessyyF // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE14defaultWitnessyyF public func defaultWitness() {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessxSiF public func anotherDefaultWitness(_ x: Int) -> Self {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypey05AssocI0QzF public func defaultWitnessWithAssociatedType(_ a: AssocType) {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirementyqd___qd_0_1btr0_lF public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirementyqd___qd_0_1ttr0_lF public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessxSiFZ public static func staticDefaultWitness(_ x: Int) -> Self {} // CHECK-LABEL: sil private @_T019protocol_resilience16ResilientMethodsPAAE25defaultWitnessIsNotPublic{{.*}}F private func defaultWitnessIsNotPublic() {} } public protocol ResilientConstructors { init(noDefault: ()) init(default: ()) init?(defaultIsOptional: ()) init?(defaultNotOptional: ()) init(optionalityMismatch: ()) } extension ResilientConstructors { // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC // CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt7default_tcfC public init(default: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC // CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt17defaultIsOptional_tcfC public init?(defaultIsOptional: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt20defaultIsNotOptional_tcfC public init(defaultIsNotOptional: ()) { self.init(noDefault: ()) } // CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt19optionalityMismatch_tcfC public init?(optionalityMismatch: ()) { self.init(noDefault: ()) } } public protocol ResilientStorage { associatedtype T : ResilientConstructors var propertyWithDefault: Int { get } var propertyWithNoDefault: Int { get } var mutablePropertyWithDefault: Int { get set } var mutablePropertyNoDefault: Int { get set } var mutableGenericPropertyWithDefault: T { get set } subscript(x: T) -> T { get set } var mutatingGetterWithNonMutatingDefault: Int { mutating get set } } extension ResilientStorage { // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP19propertyWithDefaultSifg // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE19propertyWithDefaultSifg public var propertyWithDefault: Int { get { return 0 } } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifg // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSifg // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifs // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSifs // CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifm public var mutablePropertyWithDefault: Int { get { return 0 } set { } } public private(set) var mutablePropertyNoDefault: Int { get { return 0 } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfg // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzfg // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfs // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzfs // CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfm public var mutableGenericPropertyWithDefault: T { get { return T(default: ()) } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfg // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE9subscript1TQzAFcfg // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfs // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE9subscript1TQzAFcfs // CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfm public subscript(x: T) -> T { get { return x } set { } } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifg // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSifg // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifs // CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSifs // CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifmytfU_ // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifm public var mutatingGetterWithNonMutatingDefault: Int { get { return 0 } set { } } } public protocol ResilientOperators { associatedtype AssocType : P static prefix func ~~~(s: Self) static func <*><T>(s: Self, t: T) static func <**><T>(t: T, s: Self) -> AssocType static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType } // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ // CHECK-LABEL: sil @_T019protocol_resilience3tttopyxlF public prefix func ~~~<S>(s: S) {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ // CHECK-LABEL: sil @_T019protocol_resilience3lmgoiyq__xtr0_lF public func <*><T, S>(s: S, t: T) {} // Swap the generic parameters to make sure we don't mix up our DeclContexts // when mapping interface types in and out // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ // CHECK-LABEL: sil @_T019protocol_resilience4lmmgoi9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {} // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ // CHECK-LABEL: sil @_T019protocol_resilience5leeegoi9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {} public protocol ReabstractSelfBase { // No requirements } public protocol ReabstractSelfRefined : class, ReabstractSelfBase { // A requirement with 'Self' abstracted as a class instance var callback: (Self) -> Self { get set } } func id<T>(_ t: T) -> T {} extension ReabstractSelfBase { // A witness for the above requirement, but with 'Self' maximally abstracted public var callback: (Self) -> Self { get { return id } nonmutating set { } } } final class X : ReabstractSelfRefined {} func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocoly010resilient_A005OtherdE0_pzF func inoutResilientProtocol(_ x: inout OtherResilientProtocol) { // CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSifm inoutFunc(&x.propertyInExtension) } struct OtherConformingType : OtherResilientProtocol {} // CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocolyAA19OtherConformingTypeVzF func inoutResilientProtocol(_ x: inout OtherConformingType) { // CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSifm inoutFunc(&x.propertyInExtension) // CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE25staticPropertyInExtensionSifmZ inoutFunc(&OtherConformingType.staticPropertyInExtension) } // Protocol is not public -- make sure default witnesses have the right linkage protocol InternalProtocol { func noDefaultF() func defaultG() } extension InternalProtocol { // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16InternalProtocolP8defaultGyyF // CHECK: return func defaultG() {} } // CHECK-LABEL: sil_default_witness_table P { // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientMethods { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientMethods.defaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP14defaultWitnessyyF // CHECK-NEXT: method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF // CHECK-NEXT: method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF // CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF // CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientConstructors { // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC // CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientStorage { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.propertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP19propertyWithDefaultSifg // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifg // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifs // CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSifm // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfg // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfs // CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzfm // CHECK-NEXT: method #ResilientStorage.subscript!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfg // CHECK-NEXT: method #ResilientStorage.subscript!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfs // CHECK-NEXT: method #ResilientStorage.subscript!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP9subscript1TQzAFcfm // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifg // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifs // CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSifm // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ResilientOperators { // CHECK-NEXT: no_default // CHECK-NEXT: no_default // CHECK-NEXT: method #ResilientOperators."~~~"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ // CHECK-NEXT: method #ResilientOperators."<*>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ // CHECK-NEXT: method #ResilientOperators."<**>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ // CHECK-NEXT: method #ResilientOperators."<===>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined { // CHECK-NEXT: no_default // CHECK-NEXT: method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcfg // CHECK-NEXT: method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcfs // CHECK-NEXT: method #ReabstractSelfRefined.callback!materializeForSet.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcfm // CHECK-NEXT: } // CHECK-LABEL: sil_default_witness_table hidden InternalProtocol { // CHECK-NEXT: no_default // CHECK-NEXT: method #InternalProtocol.defaultG!1: {{.*}} : @_T019protocol_resilience16InternalProtocolP8defaultGyyF // CHECK-NEXT: }
apache-2.0
a600d4e1018b71dd5f1bfdd1d1ae7ac0
51.860681
221
0.79255
4.4568
false
false
false
false
Josscii/iOS-Demos
CycleScrollView/CycleScrollView/ViewController.swift
1
2757
// // ViewController.swift // CycleScrollView // // Created by josscii on 2018/4/10. // Copyright © 2018年 josscii. All rights reserved. // import UIKit class ViewController: UIViewController { var scrollView: UIScrollView! var colors: [UIColor] = [.red, .yellow, .green] var preView: UIView! var currentView: UIView! var nextView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. preView = UIView() preView.backgroundColor = .red preView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 300) currentView = UIView() currentView.backgroundColor = .yellow currentView.frame = CGRect(x: view.frame.width, y: 0, width: view.frame.width, height: 300) nextView = UIView() nextView.backgroundColor = .green nextView.frame = CGRect(x: view.frame.width * 2, y: 0, width: view.frame.width, height: 300) scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 200, width: view.frame.width, height: 300) scrollView.contentSize = CGSize(width: view.frame.width * 3, height: 300) scrollView.isPagingEnabled = true scrollView.delegate = self scrollView.contentOffset.x = view.frame.width scrollView.addSubview(preView) scrollView.addSubview(currentView) scrollView.addSubview(nextView) view.addSubview(scrollView) } var currentIndex = 0 } extension ViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.x >= view.frame.width * 2 { scrollView.contentOffset.x = view.frame.width preView.backgroundColor = currentView.backgroundColor currentView.backgroundColor = nextView.backgroundColor nextView.backgroundColor = nextCycleColor(color: nextView.backgroundColor!) } if scrollView.contentOffset.x <= 0 { scrollView.contentOffset.x = view.frame.width nextView.backgroundColor = currentView.backgroundColor currentView.backgroundColor = preView.backgroundColor preView.backgroundColor = preCycleColor(color: preView.backgroundColor!) } } func nextCycleColor(color: UIColor) -> UIColor { return colors[(colors.index(of: color)!+1) % 3] } func preCycleColor(color: UIColor) -> UIColor { var index = colors.index(of: color)!-1 if index < 0 { index = 1 } return colors[index % 3] } }
mit
ff37f9cf038c5f89059c767007399c8a
31.785714
100
0.625272
4.731959
false
false
false
false
rcobelli/GameOfficials
Game Officials/DocumentsViewController.swift
1
1654
// // DocumentsViewController.swift // Game Officials // // Created by Ryan Cobelli on 4/1/17. // Copyright © 2017 Rybel LLC. All rights reserved. // import UIKit import Eureka import Alamofire import MessageUI class DocumentsViewController: UIViewController { // @IBOutlet weak var tableView: UITableView! @IBOutlet weak var textArea: UITextView! var json : JSON = "" override func viewDidLoad() { super.viewDidLoad() // tableView.tableFooterView = UIView() // tableView.emptyDataSetDelegate = self // tableView.emptyDataSetSource = self // tableView.addPullToRefresh(actionHandler: { // self.reload() // }) // tableView.triggerPullToRefresh() let params : Parameters = ["username" : UserDefaults.standard.string(forKey: "username")!, "password": UserDefaults.standard.string(forKey: "password")!] Alamofire.request("http://rybel-llc.com:8080/~ryan/game-officials/viewIdentities.php", method: .post, parameters: params) .responseString { response in if response.result.isSuccess { print(response.result.value) if let dataFromString = response.result.value?.data(using: String.Encoding.utf8, allowLossyConversion: false) { self.json = JSON(data: dataFromString) } else { print("Can not encode") } } else { // self.tableView.pullToRefreshView.stopAnimating() let alert = UIAlertController(title: "Error:", message: "Could Not Load Data", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } }
mit
6151d3964490e15952dc1d86fbbf5365
30.188679
155
0.711434
3.853147
false
false
false
false
gregomni/swift
test/SILGen/errors.swift
5
50273
// RUN: %target-swift-emit-silgen -parse-stdlib -Xllvm -sil-print-debuginfo -verify -swift-version 5 -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s import Swift class Cat {} enum HomeworkError : Error { case TooHard case TooMuch case CatAteIt(Cat) case CatHidIt(Cat) } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // CHECK: sil hidden [ossa] @$s6errors10make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK: [[T0:%.*]] = function_ref @$s6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden [ossa] @$s6errors15dont_make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt // CHECK-NEXT: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: store [[BOX]] to [init] [[BOXBUF:%.*]] : // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: [[BOX2:%.*]] = load [take] [[BOXBUF]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: dealloc_stack [[BOXBUF]] // CHECK-NEXT: throw [[BOX2]] func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden [ossa] @$s6errors11dont_return{{.*}}F : $@convention(thin) <T> (@in_guaranteed T) -> (@out T, @error Error) { // CHECK: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt // CHECK-NEXT: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: store [[BOX]] to [init] [[BOXBUF:%.*]] : // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: [[BOX2:%.*]] = load [take] [[BOXBUF]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: dealloc_stack [[BOXBUF]] // CHECK-NEXT: throw [[BOX2]] func dont_return<T>(_ argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden [ossa] @$s6errors16all_together_nowyAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[RET_TEMP:%.*]] = alloc_stack $Cat // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @$s6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @$s6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]] // CHECK: [[DR_FN:%.*]] = function_ref @$s6errors11dont_return{{.*}} : // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: destroy_addr [[ARG_TEMP]] // CHECK-NEXT: dealloc_stack [[ARG_TEMP]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: [[COPIED_BORROWED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK-NEXT: store [[COPIED_BORROWED_ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0_ORIG:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: switch_enum [[T0_ORIG]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [lexical] [[T0]] // CHECK-NEXT: debug_value [[BORROWED_T0]] : $Cat // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]([[CATCHALL_ERROR:%.*]] : @owned $HomeworkError): // CHECK-NEXT: destroy_value [[CATCHALL_ERROR]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK: [[T0:%.*]] = function_ref @$s6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DR_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[CAT:%.*]] : // CHECK-NEXT: dealloc_stack [[CAT]] // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) func all_together_now(_ flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Make sure that if we catch an error in a throwing function we borrow the // error and only consume the error in the rethrow block. // // CHECK-LABEL: sil hidden [ossa] @$s6errors20all_together_now_twoyAA3CatCSgSbKF : $@convention(thin) (Bool) -> (@owned Optional<Cat>, @error Error) { // CHECK: bb0( // CHECK-NOT: bb1 // CHECK: try_apply {{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: [[COPIED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK: store [[COPIED_ERROR]] to [init] [[CAST_INPUT_MEM:%.*]] : $*Error // CHECK: checked_cast_addr_br copy_on_success Error in [[CAST_INPUT_MEM]] : $*Error to HomeworkError in [[CAST_OUTPUT_MEM:%.*]] : $*HomeworkError, [[CAST_YES_BB:bb[0-9]+]], [[CAST_NO_BB:bb[0-9]+]], // // CHECK: [[CAST_YES_BB]]: // CHECK: [[SUBERROR:%.*]] = load [take] [[CAST_OUTPUT_MEM]] // CHECK: switch_enum [[SUBERROR]] : $HomeworkError, case #HomeworkError.TooHard!enumelt: {{bb[0-9]+}}, default [[SWITCH_MATCH_FAIL_BB:bb[0-9]+]], // // CHECK: [[SWITCH_MATCH_FAIL_BB]]([[SUBERROR:%.*]] : @owned $HomeworkError): // CHECK: destroy_value [[SUBERROR]] // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB:bb[0-9]+]]([[ERROR]] : $Error) // // CHECK: [[CAST_NO_BB]]: // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB]]([[ERROR]] : $Error) // // CHECK: [[RETHROW_BB]]([[ERROR_FOR_RETHROW:%.*]] : @owned $Error): // CHECK: throw [[ERROR_FOR_RETHROW]] // CHECK: } // end sil function '$s6errors20all_together_now_twoyAA3CatCSgSbKF' func all_together_now_two(_ flag: Bool) throws -> Cat? { do { return try dont_return(Cat()) } catch HomeworkError.TooHard { return nil } } // Same as the previous test, but with multiple cases instead of just one. // // CHECK-LABEL: sil hidden [ossa] @$s6errors22all_together_now_threeyAA3CatCSgSbKF : $@convention(thin) (Bool) -> (@owned Optional<Cat>, @error Error) { // CHECK: bb0( // CHECK-NOT: bb1 // CHECK: try_apply {{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: [[COPIED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK: store [[COPIED_ERROR]] to [init] [[CAST_INPUT_MEM:%.*]] : $*Error // CHECK: checked_cast_addr_br copy_on_success Error in [[CAST_INPUT_MEM]] : $*Error to HomeworkError in [[CAST_OUTPUT_MEM:%.*]] : $*HomeworkError, [[CAST_YES_BB:bb[0-9]+]], [[CAST_NO_BB:bb[0-9]+]], // // CHECK: [[CAST_YES_BB]]: // CHECK: [[SUBERROR:%.*]] = load [take] [[CAST_OUTPUT_MEM]] // CHECK: switch_enum [[SUBERROR]] : $HomeworkError, case #HomeworkError.TooHard!enumelt: {{bb[0-9]+}}, case #HomeworkError.TooMuch!enumelt: {{bb[0-9]+}}, default [[SWITCH_MATCH_FAIL_BB:bb[0-9]+]], // // CHECK: [[SWITCH_MATCH_FAIL_BB]]([[SUBERROR:%.*]] : @owned $HomeworkError): // CHECK: destroy_value [[SUBERROR]] // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB:bb[0-9]+]]([[ERROR]] : $Error) // // CHECK: [[CAST_NO_BB]]: // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB]]([[ERROR]] : $Error) // // CHECK: [[RETHROW_BB]]([[ERROR_FOR_RETHROW:%.*]] : @owned $Error): // CHECK: throw [[ERROR_FOR_RETHROW]] // CHECK: } // end sil function '$s6errors22all_together_now_threeyAA3CatCSgSbKF' func all_together_now_three(_ flag: Bool) throws -> Cat? { do { return try dont_return(Cat()) } catch HomeworkError.TooHard { return nil } catch HomeworkError.TooMuch { return nil } } // Same as the previous test, but with a multi-pattern catch instead of two separate ones. // // CHECK-LABEL: sil hidden [ossa] @$s6errors21all_together_now_fouryAA3CatCSgSbKF : $@convention(thin) (Bool) -> (@owned Optional<Cat>, @error Error) { // CHECK: bb0( // CHECK-NOT: bb1 // CHECK: try_apply {{.*}}, normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: [[COPIED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK: store [[COPIED_ERROR]] to [init] [[CAST_INPUT_MEM:%.*]] : $*Error // CHECK: checked_cast_addr_br copy_on_success Error in [[CAST_INPUT_MEM]] : $*Error to HomeworkError in [[CAST_OUTPUT_MEM:%.*]] : $*HomeworkError, [[CAST_YES_BB:bb[0-9]+]], [[CAST_NO_BB:bb[0-9]+]], // // CHECK: [[CAST_YES_BB]]: // CHECK: [[SUBERROR:%.*]] = load [take] [[CAST_OUTPUT_MEM]] // CHECK: switch_enum [[SUBERROR]] : $HomeworkError, case #HomeworkError.TooHard!enumelt: [[TOO_HARD_BB:bb[0-9]+]], case #HomeworkError.TooMuch!enumelt: [[TOO_MUCH_BB:bb[0-9]+]], default [[SWITCH_MATCH_FAIL_BB:bb[0-9]+]], // // CHECK: [[TOO_HARD_BB]]: // CHECK: br [[CASE_BODY_BB:bb[0-9]+]] // // CHECK: [[TOO_MUCH_BB]]: // CHECK: br [[CASE_BODY_BB]] // // CHECK: [[CASE_BODY_BB]] // CHECK: [[RETVAL:%.*]] = enum $Optional<Cat> // CHECK: destroy_value [[ERROR]] // CHECK: br bb2([[RETVAL]] : $Optional<Cat>) // // CHECK: [[SWITCH_MATCH_FAIL_BB]]([[SUBERROR:%.*]] : @owned $HomeworkError): // CHECK: destroy_value [[SUBERROR]] // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB:bb[0-9]+]]([[ERROR]] : $Error) // // CHECK: [[CAST_NO_BB]]: // CHECK: end_borrow [[BORROWED_ERROR]] // CHECK: br [[RETHROW_BB]]([[ERROR]] : $Error) // // CHECK: [[RETHROW_BB]]([[ERROR_FOR_RETHROW:%.*]] : @owned $Error): // CHECK: throw [[ERROR_FOR_RETHROW]] // CHECK: } // end sil function '$s6errors21all_together_now_fouryAA3CatCSgSbKF' func all_together_now_four(_ flag: Bool) throws -> Cat? { do { return try dont_return(Cat()) } catch HomeworkError.TooHard, HomeworkError.TooMuch { return nil } } // A multi-pattern catch with associated value bindings. // // CHECK-LABEL: sil hidden [ossa] @$s6errors21all_together_now_fiveyAA3CatCSbKF : $@convention(thin) (Bool) -> (@owned Cat, @error Error) { // Return block. // CHECK: [[RETURN:bb[0-9]+]]([[RETVAL:%.*]] : @owned $Cat): // CHECK-NEXT: return [[RETVAL]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: [[COPIED_BORROWED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK-NEXT: store [[COPIED_BORROWED_ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0_ORIG:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: switch_enum [[T0_ORIG]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt: [[MATCH_ATE:bb[0-9]+]], case #HomeworkError.CatHidIt!enumelt: [[MATCH_HID:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH_ATE]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: [[T0_BORROW:%.*]] = begin_borrow [lexical] [[T0]] // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0_BORROW]] // CHECK-NEXT: end_borrow [[T0_BORROW]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: br [[EXTRACT:bb[0-9]+]]([[T0_COPY]] : $Cat) // Catch HomeworkError.CatHidIt. // CHECK: [[MATCH_HID]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: [[T0_BORROW:%.*]] = begin_borrow [lexical] [[T0]] // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0_BORROW]] // CHECK-NEXT: end_borrow [[T0_BORROW]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: br [[EXTRACT]]([[T0_COPY]] : $Cat) // CHECK: [[EXTRACT]]([[CAT:%.*]] : @owned $Cat): // CHECK-NEXT: debug_value [[CAT]] : $Cat, let, name "theCat" // CHECK-NEXT: [[BORROWED_CAT:%.*]] = begin_borrow [[CAT]] : $Cat // CHECK-NEXT: [[COPIED_CAT:%.*]] = copy_value [[BORROWED_CAT]] : $Cat // CHECK-NEXT: end_borrow [[BORROWED_CAT]] : $Cat // CHECK-NEXT: destroy_value [[CAT]] : $Cat // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[COPIED_CAT]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]([[CATCHALL_ERROR:%.*]] : @owned $HomeworkError): // CHECK-NEXT: destroy_value [[CATCHALL_ERROR]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: br [[RETHROW:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] // CHECK-NEXT: br [[RETHROW]] // Rethrow // CHECK: [[RETHROW]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: throw [[ERROR]] : $Error func all_together_now_five(_ flag: Bool) throws -> Cat { do { return try dont_return(Cat()) } catch HomeworkError.CatAteIt(let theCat), HomeworkError.CatHidIt(let theCat) { return theCat } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden [ossa] @$s6errors11catch_a_catAA3CatCyF : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK: [[F:%.*]] = function_ref @$s6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @$s6errors15HasThrowingInit{{.*}}c : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : @owned $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: throw [[ERROR]] // CHECK-LABEL: sil hidden [ossa] @$s6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %0 to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] // CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit enum ColorError : Error { case Red, Green, Blue } //CHECK-LABEL: sil hidden [ossa] @$s6errors6IThrows5Int32VyKF //CHECK: builtin "willThrow" //CHECK-NEXT: dealloc_stack //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden [ossa] @$s6errors12DoesNotThrows5Int32VyKF //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { _ = try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s6errors12DoomedStructVAA0B0A2aDP5checkyyKFTW : // CHECK: [[SELF:%.*]] = load [trivial] %0 : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @$s6errors12DoomedStructV5checkyyKF : $@convention(method) (DoomedStruct) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: throw [[T0]] : $Error struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s6errors11DoomedClassCAA0B0A2aDP5checkyyKFTW : // CHECK: [[BORROWED_SELF:%.*]] = load_borrow %0 // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: end_borrow [[BORROWED_SELF]] // CHECK: throw [[T0]] : $Error class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s6errors11HappyStructVAA6DoomedA2aDP5checkyyKFTW : // CHECK: [[T0:%.*]] = function_ref @$s6errors11HappyStructV5checkyyF : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]](%1) // CHECK: [[T1:%.*]] = tuple () // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s6errors10HappyClassCAA6DoomedA2aDP5checkyyKFTW : // CHECK: [[SELF:%.*]] = load_borrow %0 : $*HappyClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: end_borrow [[SELF]] // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(_ fn: () throws -> T) throws -> T { return try fn() } func testThunk(_ fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSis5Error_pIgdzo_SisAA_pIegrzo_TR : $@convention(thin) (@noescape @callee_guaranteed () -> (Int, @error Error)) -> (@out Int, @error Error) // CHECK: bb0(%0 : $*Int, %1 : $@noescape @callee_guaranteed () -> (Int, @error Error)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to [trivial] %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: throw [[T0]] : $Error func createInt(_ fn: () -> Int) throws {} func testForceTry(_ fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden [ossa] @$s6errors12testForceTryyySiyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> () // CHECK: bb0([[ARG:%.*]] : $@noescape @callee_guaranteed () -> Int): // CHECK: [[FUNC:%.*]] = function_ref @$s6errors9createIntyySiyXEKF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> @error Error // CHECK: try_apply [[FUNC]]([[ARG]]) // CHECK: return // CHECK: function_ref @swift_unexpectedError // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden [ossa] @$s6errors20testForceTryMultipleyyF // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat) // CHECK: [[FN_2:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat) // CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : @owned $Error): // CHECK: [[UNEXPECTED_ERROR:%.+]] = function_ref @swift_unexpectedError // CHECK-NEXT: apply [[UNEXPECTED_ERROR]]([[ERROR]] // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$s6errors20testForceTryMultipleyyF' // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden [ossa] @$s6errors7feedCatSiyKF : $@convention(thin) () -> (Int, @error Error) // CHECK: debug_value undef : $Error, var, name "$error", argno 1 // CHECK: %1 = function_ref @$s6errors13preferredFoodAA03CatC0OyKF : $@convention(thin) () -> (CatFood, @error Error) // CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : @owned $Error) // CHECK: throw [[ERROR]] : $Error // Throwing statements inside cases. func getHungryCat(_ food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden [ossa] @$s6errors12getHungryCatyAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error) // CHECK: bb0(%0 : $CatFood): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @$s6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @$s6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : @owned $Error): // CHECK: br bb8([[ERROR:%.*]] : $Error) // CHECK: bb7([[ERROR:%.*]] : @owned $Error): // CHECK: br bb8([[ERROR]] : $Error) // CHECK: bb8([[ERROR:%.*]] : @owned $Error): // CHECK: throw [[ERROR]] : $Error func take_many_cats(_ cats: Cat...) throws {} func test_variadic(_ cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden [ossa] @$s6errors13test_variadicyyAA3CatCKF : $@convention(thin) (@guaranteed Cat) -> @error Error { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Cat): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @$ss27_allocateUninitializedArray{{.*}}F // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: ([[ARRAY:%.*]], [[T2:%.*]]) = destructure_tuple [[T1]] // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @$s6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$s6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$s6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]] // Complete the call and return. // CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF // CHECK: [[FIN_ARRAY:%.*]] = apply [[FIN_FN]]<Cat>([[ARRAY]]) // CHECK: [[TAKE_FN:%.*]] = function_ref @$s6errors14take_many_catsyyAA3CatCd_tKF : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error // CHECK-NEXT: try_apply [[TAKE_FN]]([[FIN_ARRAY]]) : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: destroy_value [[FIN_ARRAY]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : @owned $Error): // CHECK-NOT: end_borrow // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[FIN_ARRAY]] // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s6errors13test_variadicyyAA3CatCKF' // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden [ossa] @$s6errors16BaseThrowingInit{{.*}}c : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error) // CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit } // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]] // CHECK: [[BOX_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_BOX]] // CHECK: [[PB:%.*]] = project_box [[BOX_LIFETIME]] // Initialize subField. // CHECK: [[T0:%.*]] = load_borrow [[PB]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %1 to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[T0]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load [take] [[PB]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK: [[T3:%[0-9]+]] = function_ref @$s6errors15HasThrowingInitC5valueACSi_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { associatedtype Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(_ b: inout B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden [ossa] @$s6errors21supportFirstStructure{{.*}}F : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error { // CHECK: [[MODIFY:%.*]] = witness_method $B, #Buildable.firstStructure!modify : // CHECK: ([[T1:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]<B>([[BASE:%[0-9]*]]) // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support : // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T1]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: end_apply [[TOKEN]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK: abort_apply [[TOKEN]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s6errors21supportFirstStructure{{.*}}F' func supportStructure<B: Buildable>(_ b: inout B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden [ossa] @$s6errors16supportStructure_4nameyxz_SStKAA9BuildableRzlF : $@convention(thin) <B where B : Buildable> (@inout B, @guaranteed String) -> @error Error { // CHECK: bb0({{.*}}, [[INDEX:%.*]] : @guaranteed $String): // CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX]] : $String // CHECK: [[BORROWED_INDEX_COPY:%.*]] = begin_borrow [[INDEX_COPY]] // CHECK: [[MODIFY:%.*]] = witness_method $B, #Buildable.subscript!modify : // CHECK: ([[T1:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]<B>([[BORROWED_INDEX_COPY]], [[BASE:%[0-9]*]]) // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support : // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T1]]) : $@convention(witness_method: Supportable) <τ_0_0 where τ_0_0 : Supportable> (@inout τ_0_0) -> @error Error, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: end_apply [[TOKEN]] // CHECK: end_borrow [[BORROWED_INDEX_COPY]] // CHECK: destroy_value [[INDEX_COPY]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK: abort_apply [[TOKEN]] // CHECK: end_borrow [[BORROWED_INDEX_COPY]] // CHECK: destroy_value [[INDEX_COPY]] : $String // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s6errors16supportStructure{{.*}}F' struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(_ b: inout Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden [ossa] @$s6errors16supportStructure_4nameyAA6BridgeVz_SStKF : $@convention(thin) (@inout Bridge, @guaranteed String) -> @error Error { // CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : @guaranteed $String): // CHECK: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Bridge // CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load_borrow [[WRITE]] : $*Bridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @$s6errors6BridgeVyAA5PylonVSScig : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]]) // CHECK-NEXT: store [[T0]] to [init] [[TEMP]] // CHECK-NEXT: end_borrow [[BASE]] // CHECK: [[SUPPORT:%.*]] = function_ref @$s6errors5PylonV7supportyyKF // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s6errors6BridgeVyAA5PylonVSScis : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[WRITE]]) // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s6errors6BridgeVyAA5PylonVSScis : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[WRITE]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY // CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s6errors16supportStructure_4nameyAA6BridgeVz_SStKF' // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(_ f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden [ossa] @$s6errors15testOptionalTryyyF // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<Cat>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[CLEANUPS:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: } // end sil function '$s6errors15testOptionalTryyyF' func testOptionalTry() { _ = try? make_a_cat() } func sudo_make_a_cat() {} // CHECK-LABEL: sil hidden [ossa] @{{.*}}testOptionalTryThatNeverThrows func testOptionalTryThatNeverThrows() { guard let _ = try? sudo_make_a_cat() else { // expected-warning{{no calls to throwing}} return } } // CHECK-LABEL: sil hidden [ossa] @$s6errors18testOptionalTryVaryyF // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> } // CHECK-NEXT: [[LIFETIME:%.+]] = begin_borrow [lexical] [[BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[LIFETIME]] // CHECK: [[FN:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat) // CHECK-NEXT: [[CAT_ENUM:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt // CHECK-NEXT: store [[CAT_ENUM]] to [init] [[PB]] : $*Optional<Cat> // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[CLEANUPS:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: } // end sil function '$s6errors18testOptionalTryVaryyF' func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden [ossa] @$s6errors26testOptionalTryAddressOnly{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt // CHECK: [[FN:%.+]] = function_ref @$s6errors11dont_return{{.*}}F // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: } // end sil function '$s6errors26testOptionalTryAddressOnlyyyxlF' func testOptionalTryAddressOnly<T>(_ obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden [ossa] @$s6errors29testOptionalTryAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK: [[LIFETIME:%.+]] = begin_borrow [lexical] [[BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[LIFETIME]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt // CHECK: [[FN:%.+]] = function_ref @$s6errors11dont_return{{.*}}F // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: } // end sil function '$s6errors29testOptionalTryAddressOnlyVaryyxlF' func testOptionalTryAddressOnlyVar<T>(_ obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden [ossa] @$s6errors23testOptionalTryMultipleyyF // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat) // CHECK: [[FN_2:%.+]] = function_ref @$s6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<(Cat, Cat)>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$s6errors23testOptionalTryMultipleyyF' func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden [ossa] @$s6errors25testOptionalTryNeverFailsyyF // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '$s6errors25testOptionalTryNeverFailsyyF' func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden [ossa] @$s6errors28testOptionalTryNeverFailsVaryyF // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> } // CHECK-NEXT: [[LIFETIME:%.+]] = begin_borrow [lexical] [[BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[LIFETIME]] // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: [[ENUM:%.+]] = enum $Optional<()>, #Optional.some!enumelt, [[VALUE]] // CHECK-NEXT: store [[ENUM]] to [trivial] [[PB]] : // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '$s6errors28testOptionalTryNeverFailsVaryyF' func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}} } // CHECK-LABEL: sil hidden [ossa] @$s6errors36testOptionalTryNeverFailsAddressOnly{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '$s6errors36testOptionalTryNeverFailsAddressOnlyyyxlF' func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden [ossa] @$s6errors39testOptionalTryNeverFailsAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[LIFETIME:%.+]] = begin_borrow [lexical] [[BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[LIFETIME]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '$s6errors13OtherErrorSubCACycfC' func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } class SomeErrorClass : Error { } // CHECK-LABEL: sil_vtable SomeErrorClass // CHECK-NEXT: #SomeErrorClass.init!allocator: {{.*}} : @$s6errors14SomeErrorClassCACycfC // CHECK-NEXT: #SomeErrorClass.deinit!deallocator: @$s6errors14SomeErrorClassCfD // CHECK-NEXT: } class OtherErrorSub : OtherError { } // CHECK-LABEL: sil_vtable OtherErrorSub { // CHECK-NEXT: #OtherError.init!allocator: {{.*}} : @$s6errors13OtherErrorSubCACycfC [override] // CHECK-NEXT: #OtherErrorSub.deinit!deallocator: @$s6errors13OtherErrorSubCfD // OtherErrorSub.__deallocating_deinit // CHECK-NEXT:}
apache-2.0
582d1b0142d3f698a014d2f484a302e8
47.227447
234
0.608103
3.140813
false
false
false
false
sachin004/firefox-ios
Client/Frontend/Browser/Authenticator.swift
3
5776
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Authentication prompt cancel button") private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button") class Authenticator { private static let MaxAuthenticationAttempts = 3 static func handleAuthRequest(viewController: UIViewController, challenge: NSURLAuthenticationChallenge, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> { // If there have already been too many login attempts, we'll just fail. if challenge.previousFailureCount >= Authenticator.MaxAuthenticationAttempts { return deferMaybe(LoginDataError(description: "Too many attempts to open site")) } var credential = challenge.proposedCredential // If we were passed an initial set of credentials from iOS, try and use them. if let proposed = credential { if !(proposed.user?.isEmpty ?? true) { if challenge.previousFailureCount == 0 { return deferMaybe(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace)) } } else { credential = nil } } // If we have some credentials, we'll show a prompt with them. if let credential = credential { return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper) } // Otherwise, try to look them up and show the prompt. if let loginsHelper = loginsHelper { return loginsHelper.getLoginsForProtectionSpace(challenge.protectionSpace).bindQueue(dispatch_get_main_queue()) { res in let credentials = res.successValue?[0]?.credentials return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper) } } // No credentials, so show an empty prompt. return self.promptForUsernamePassword(viewController, credentials: nil, protectionSpace: challenge.protectionSpace, loginsHelper: nil) } private static func promptForUsernamePassword(viewController: UIViewController, credentials: NSURLCredential?, protectionSpace: NSURLProtectionSpace, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> { if protectionSpace.host.isEmpty { print("Unable to show a password prompt without a hostname") return deferMaybe(LoginDataError(description: "Unable to show a password prompt without a hostname")) } let deferred = Deferred<Maybe<LoginData>>() let alert: UIAlertController let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title") if !(protectionSpace.realm?.isEmpty ?? true) { let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string") let formatted = NSString(format: msg, protectionSpace.host, protectionSpace.realm ?? "") as String alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert) } else { let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site") let formatted = NSString(format: msg, protectionSpace.host) as String alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert) } // Add a button to log in. let action = UIAlertAction(title: LogInButtonTitle, style: UIAlertActionStyle.Default) { (action) -> Void in guard let user = alert.textFields?[0].text, pass = alert.textFields?[1].text else { deferred.fill(Maybe(failure: LoginDataError(description: "Username and Password required"))); return } let login = Login.createWithCredential(NSURLCredential(user: user, password: pass, persistence: .ForSession), protectionSpace: protectionSpace) deferred.fill(Maybe(success: login)) loginsHelper?.setCredentials(login) } alert.addAction(action) // Add a cancel button. let cancel = UIAlertAction(title: CancelButtonTitle, style: UIAlertActionStyle.Cancel) { (action) -> Void in deferred.fill(Maybe(failure: LoginDataError(description: "Save password cancelled"))) } alert.addAction(cancel) // Add a username textfield. alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt") textfield.text = credentials?.user } // Add a password textfield. alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt") textfield.secureTextEntry = true textfield.text = credentials?.password } viewController.presentViewController(alert, animated: true) { () -> Void in } return deferred } }
mpl-2.0
fffc646348327e3db83ed617fa0e6919
54.538462
227
0.689924
5.602328
false
false
false
false
jhurray/SQLiteModel-Example-Project
iOS+SQLiteModel/Blogz4Dayz/NewImageCell.swift
1
1065
// // NewImageCell.swift // Blogz4Dayz // // Created by Jeff Hurray on 4/9/16. // Copyright © 2016 jhurray. All rights reserved. // import UIKit class NewImageCell: UICollectionViewCell { let label = UILabel() let view = UIView() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() label.text = "+" label.font = UIFont.systemFontOfSize(48.0) label.textColor = color label.textAlignment = .Center label.clipsToBounds = true view.backgroundColor = UIColor.whiteColor() view.layer.cornerRadius = 30.0 self.contentView.addSubview(view) view.addSubview(label) } override func layoutSubviews() { super.layoutSubviews() view.anchorInCenter(width: 60, height: 60) label.fillSuperview(left: 0, right: 0, top: 0, bottom: 8) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b697803adb6627e4d10f646c1a92c037
23.744186
65
0.609962
4.256
false
false
false
false
nguyenantinhbk77/practice-swift
Views/TableViews/TableView/SimpleTable/SimpleTable/ViewController.swift
2
3582
// // ViewController.swift // SimpleTable // // Created by Domenico on 22.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { private let dwarves = [ "Sleepy", "Sneezy", "Bashful", "Happy", "Doc", "Grumpy", "Dopey", "Thorin", "Dorin", "Nori", "Ori", "Balin", "Dwalin", "Fili", "Kili", "Oin", "Gloin", "Bifur", "Bofur", "Bombur" ] let simpleTableIdentifier = "SimpleTableIdentifier" 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. } //- MARK: UITableViewDataSource /// Number of row in a section func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dwarves.count } /// It is called by the table view when it needs to draw one of its rows. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Reuse a cell of the specified type var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell if cell == nil{ // Create a new cell if it does not exist cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: simpleTableIdentifier) } // Adding the images let image = UIImage(named: "star") let highlitedImage = UIImage(named: "star2") cell!.imageView?.image = image cell!.imageView?.highlightedImage = highlitedImage // Adding detailed text if indexPath.row < 7 { cell!.detailTextLabel?.text = "Mr Disney" } else { cell!.detailTextLabel?.text = "Mr Tolkien" } cell!.textLabel!.text = dwarves[indexPath.row] cell!.textLabel!.font = UIFont.boldSystemFontOfSize(50) return cell! } //- MARK: UITableViewDelegate func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int { return indexPath.row % 4 } // Before the row is selected func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.row == 0 { return nil } else { return indexPath } } // After the row is selected func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let rowValue = dwarves[indexPath.row] let message = "You selected \(rowValue)" let controller = UIAlertController(title: "Row Selected", message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "Yes I Did", style: .Default, handler: nil) controller.addAction(action) presentViewController(controller, animated: true, completion: nil) } // Customizing the row height func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return indexPath.row == 0 ? 120 : 70 } }
mit
6e8d804691aff9840719ec92b9d5236e
31.862385
112
0.607482
4.981919
false
false
false
false
gottesmm/swift
test/stmt/if_while_var.swift
5
5393
// RUN: %target-typecheck-verify-swift struct NonOptionalStruct {} enum NonOptionalEnum { case foo } func foo() -> Int? { return .none } func nonOptionalStruct() -> NonOptionalStruct { fatalError() } func nonOptionalEnum() -> NonOptionalEnum { fatalError() } func use(_ x: Int) {} func modify(_ x: inout Int) {} if let x = foo() { use(x) modify(&x) // expected-error{{cannot pass immutable value as inout argument: 'x' is a 'let' constant}} } use(x) // expected-error{{unresolved identifier 'x'}} if var x = foo() { use(x) modify(&x) } use(x) // expected-error{{unresolved identifier 'x'}} if let x = nonOptionalStruct() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}} if let x = nonOptionalEnum() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}} guard let _ = nonOptionalStruct() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}} guard let _ = nonOptionalEnum() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}} if case let x? = nonOptionalStruct() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalStruct'}} if case let x? = nonOptionalEnum() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalEnum'}} class B {} // expected-note * {{did you mean 'B'?}} class D : B {}// expected-note * {{did you mean 'D'?}} // TODO poor recovery in these cases if let {} // expected-error {{expected '{' after 'if' condition}} expected-error {{pattern matching in a condition requires the 'case' keyword}} if let x = {} // expected-error{{'{' after 'if'}} expected-error {{variable binding in a condition requires an initializer}} expected-error{{initializer for conditional binding must have Optional type, not '() -> ()'}} if let x = foo() { } else { // TODO: more contextual error? "x is only available on the true branch"? use(x) // expected-error{{unresolved identifier 'x'}} } if let x = foo() { use(x) } else if let y = foo() { // expected-note {{did you mean 'y'?}} use(x) // expected-error{{unresolved identifier 'x'}} use(y) } else { use(x) // expected-error{{unresolved identifier 'x'}} use(y) // expected-error{{unresolved identifier 'y'}} } var opt: Int? = .none if let x = opt {} if var x = opt {} // <rdar://problem/20800015> Fix error message for invalid if-let let someInteger = 1 if let y = someInteger {} // expected-error {{initializer for conditional binding must have Optional type, not 'Int'}} if case let y? = someInteger {} // expected-error {{'?' pattern cannot match values of type 'Int'}} // Test multiple clauses on "if let". if let x = opt, let y = opt, x != y, let a = opt, var b = opt { } // Leading boolean conditional. if 1 != 2, let x = opt, y = opt, // expected-error {{expected 'let' in conditional}} {{4-4=let }} x != y, let a = opt, var b = opt { } // <rdar://problem/20457938> typed pattern is not allowed on if/let condition if 1 != 2, let x : Int? = opt {} // expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{20-26=Int}} if 1 != 2, case let x? : Int? = 42 {} // expected-warning @-1 {{non-optional expression of type 'Int' used in a check for optionals}} // Test error recovery. // <rdar://problem/19939746> Improve error recovery for malformed if statements if 1 != 2, { // expected-error {{'() -> ()' is not convertible to 'Bool'}} } // expected-error {{expected '{' after 'if' condition}} if 1 != 2, 4 == 57 {} if 1 != 2, 4 == 57, let x = opt {} // Test that these don't cause the parser to crash. if true { if a == 0; {} } // expected-error {{expected '{' after 'if' condition}} expected-error 3{{}} if a == 0, where b == 0 {} // expected-error 4{{}} expected-note {{}} {{25-25=_ = }} func testIfCase(_ a : Int?) { if case nil = a, a != nil {} if case let (b?) = a, b != 42 {} if let case (b?) = a, b != 42 {} // expected-error {{pattern matching binding is spelled with 'case let', not 'let case'}} {{6-10=}} {{14-14= let}} if a != nil, let c = a, case nil = a { _ = c} if let p? = a {_ = p} // expected-error {{pattern matching in a condition implicitly unwraps optionals}} {{11-12=}} if let .some(x) = a {_ = x} // expected-error {{pattern matching in a condition requires the 'case' keyword}} {{6-6=case }} if case _ = a {} // expected-warning {{'if' condition is always true}} while case _ = a {} // expected-warning {{'while' condition is always true}} } // <rdar://problem/20883147> Type annotation for 'let' condition still expected to be optional func testTypeAnnotations() { if let x: Int = Optional(1) {_ = x} if let x: Int = .some(1) {_ = x} if case _ : Int8 = 19 {} // expected-warning {{'if' condition is always true}} } func testShadowing(_ a: Int?, b: Int?, c: Int?, d: Int?) { guard let a = a, let b = a > 0 ? b : nil else { return } _ = b if let c = c, let d = c > 0 ? d : nil { _ = d } } func useInt(_ x: Int) {} func testWhileScoping(_ a: Int?) {// expected-note {{did you mean 'a'?}} while let x = a { } useInt(x) // expected-error{{use of unresolved identifier 'x'}} }
apache-2.0
e650e04fbb592e3a47bbc1ed9b271017
36.451389
218
0.640274
3.497406
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Authentication/TeamsDataDeserializerSpec.swift
1
4462
import XCTest import Quick import Nimble import RxSwift @testable import FrequentFlyer class TeamsDataDeserializerSpec: QuickSpec { override func spec() { describe("TeamsDataDeserializer") { var subject: TeamsDataDeserializer! let publishSubject = PublishSubject<String>() var result: StreamResult<String>! var teams: [String] { get { return result.elements } } beforeEach { subject = TeamsDataDeserializer() } describe("Deserializing teams data that is all valid") { beforeEach { let validDataJSONArray = [ [ "name": "puppy_team" ], [ "name": "crab_team" ] ] let validData = try! JSONSerialization.data(withJSONObject: validDataJSONArray, options: .prettyPrinted) result = StreamResult(subject.deserialize(validData)) } it("returns a team name for each JSON team entry") { if teams.count != 2 { fail("Expected to return 2 team names, returned \(teams.count)") return } expect(teams[0]).to(equal("puppy_team")) expect(teams[1]).to(equal("crab_team")) } it("returns no error") { expect(result.error).to(beNil()) } } describe("Deserializing team data where some of the data is invalid") { context("Missing required 'name' field") { beforeEach { let partiallyValidDataJSONArray = [ [ "name" : "puppy_team", ], [ "somethingelse" : "value", ] ] let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted) result = StreamResult(subject.deserialize(partiallyValidData)) } it("emits a team name for each valid JSON team entry") { expect(teams).to(equal(["puppy_team"])) } it("emits completed") { expect(result.completed).to(beTrue()) } } context("'name' field is not a string") { beforeEach { let partiallyValidDataJSONArray = [ [ "name" : "crab_team" ], [ "name" : 1 ] ] let partiallyValidData = try! JSONSerialization.data(withJSONObject: partiallyValidDataJSONArray, options: .prettyPrinted) result = StreamResult(subject.deserialize(partiallyValidData)) } it("emits a team name for each valid JSON team entry") { expect(teams).to(equal(["crab_team"])) } it("emits completed") { expect(result.completed).to(beTrue()) } } } describe("Given data cannot be interpreted as JSON") { beforeEach { let teamsDataString = "some string" let invalidTeamsData = teamsDataString.data(using: String.Encoding.utf8) result = StreamResult(subject.deserialize(invalidTeamsData!)) } it("emits no team names") { expect(teams).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
d7d6c248066acc0f5867deb5bb843e33
35.276423
180
0.432541
6.494905
false
false
false
false
manuelescrig/SwiftSkeleton
SwiftSkeleton/Classes/Utils.swift
1
4223
// // Utils.swift // Pods // // Created by Manuel on 10/28/16. // // import Foundation import SystemConfiguration // MARK: Logging func log(message: String, function: String = #function, file: String = #file, line: Int = #line) { print("Message \"\(message)\" (File: \(file), Function: \(function), Line: \(line))") } // MARK: Information func appDisplayName() -> String { if let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String { return bundleDisplayName } else if let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String { return bundleName } return "" } func appVersion() -> String { return (Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String)! } func appBuild() -> String { return (Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String)! } func appVersionAndBuild() -> String { if appVersion() == appBuild() { return "v\(appVersion)" } else { return "v\(appVersion)(\(appBuild))" } } func appBundleID() -> String { return Bundle.main.bundleIdentifier! } func platform() -> String { var sysinfo = utsname() uname(&sysinfo) // ignore return value return NSString(bytes: &sysinfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)! as String } func deviceVersion() -> String { var size: Int = 0 sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](repeating: 0, count: Int(size)) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String(cString: machine) } func isDebug() -> Bool { #if DEBUG return true #else return false #endif } func isRelease() -> Bool { #if DEBUG return false #else return true #endif } // MARK: Util methods func delay(_ delay:Double, closure:@escaping ()->()) { let when = DispatchTime.now() + delay DispatchQueue.main.asyncAfter(deadline: when, execute: closure) } func runOnMain(_ block: @escaping ()->()) { DispatchQueue.main.async(execute: block) } func runOnBackground(_ block: @escaping () -> ()) { DispatchQueue.global(qos: .default).async(execute: block) } func runEvery(seconds: TimeInterval, startAfterSeconds: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer { let fireDate = startAfterSeconds + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes) return timer! } // MARK: Reachabela func isInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } public extension DispatchQueue { private static var _onceTracker = [String]() /** Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID - parameter block: Block to execute once */ public class func once(token: String, block:(Void)->Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } }
mit
d53e3511de214804b1eddbe76982d82c
25.559748
126
0.655221
4.326844
false
false
false
false
nghialv/Hakuba
Hakuba/Extension/ArrayExt.swift
1
2737
// // ArrayExt.swift // Example // // Created by Le VanNghia on 3/4/16. // // import Foundation extension Array { var isNotEmpty: Bool { return !isEmpty } func hasIndex(at index: Int) -> Bool { return indices ~= index } func getSafeIndex(at index: Int) -> Int { let mIndex = Swift.max(0, index) return Swift.min(count, mIndex) } func getSafeRange(range: Range<Int>) -> Range<Int>? { let start = Swift.max(0, range.lowerBound) let end = Swift.min(count, range.upperBound) return start <= end ? start..<end : nil } func get(at index: Int) -> Element? { return hasIndex(at: index) ? self[index] : nil } @discardableResult mutating func append(_ newArray: Array) -> Range<Int> { let range = count..<(count + newArray.count) self += newArray return .init(range) } @discardableResult mutating func insert(_ newArray: Array, at index: Int) -> Range<Int> { let mIndex = Swift.max(0, index) let start = Swift.min(count, mIndex) let end = start + newArray.count let left = self[0..<start] let right = self[start..<count] self = left + newArray + right return start..<end } @discardableResult mutating func move(from fromIndex: Int, to toIndex: Int) -> Bool { if !hasIndex(at: fromIndex) || !hasIndex(at: toIndex) || fromIndex == toIndex { return false } if let fromItem = get(at: fromIndex) { remove(fromIndex) insert(fromItem, at: toIndex) return true } return false } @discardableResult mutating func remove(_ index: Int) -> Range<Int>? { if !hasIndex(at: index) { return nil } remove(at: index) return .init(index..<(index + 1)) } @discardableResult mutating func remove(range: Range<Int>) -> Range<Int>? { if let sr = getSafeRange(range: range) { return remove(range: sr) } return nil } mutating func remove<T: AnyObject> (element: T) { let anotherSelf = self removeAll(keepingCapacity: true) anotherSelf.each { (index: Int, current: Element) in if (current as! T) !== element { self.append(current) } } } @discardableResult mutating func removeLast() -> Range<Int>? { return remove(count - 1) } func each(exe: (Int, Element) -> ()) { for (index, item) in enumerated() { exe(index, item) } } }
mit
7a25ead4da3cfd9a7d9791a38e3994c8
24.579439
87
0.5327
4.165906
false
false
false
false
ahoppen/swift
test/ClangImporter/simd.swift
14
3705
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name main -typecheck -verify %s import c_simd let char2_value: char2 = makes_char2() let char64_value: char64 = makes_char64() let uchar3_value: uchar3 = makes_uchar3() let uchar32_value: uchar32 = makes_uchar32() let short3_value: short3 = makes_short3() let short8_value: short8 = makes_short8() let ushort1_value: ushort1 = makes_ushort1() let ushort16_value: ushort16 = makes_ushort16() let int3_value: int3 = makes_int3() let int32_value: int32 = makes_int32() let uint4_value: uint4 = makes_uint4() let uint2_value: uint2 = makes_uint2() let long2_value: long2 = makes_long2() let long8_value: long8 = makes_long8() let ulong4_value: ulong4 = makes_ulong4() let ulong1_value: ulong1 = makes_ulong1() let ll3_value: ll3 = makes_ll3() let ll8_value: ll8 = makes_ll8() let ull4_value: ull4 = makes_ull4() let ull16_value: ull16 = makes_ull16() #if !(os(macOS) && arch(x86_64)) let half2_value: half2 = makes_half2() let half3_value: half3 = makes_half3() let half4_value: half4 = makes_half4() let half8_value: half8 = makes_half8() let half16_value: half16 = makes_half16() let half32_value: half32 = makes_half32() #endif let float2_value: float2 = makes_float2() let float3_value: float3 = makes_float3() let float4_value: float4 = makes_float4() let float8_value: float8 = makes_float8() let float16_value: float16 = makes_float16() let double2_value: double2 = makes_double2() let double3_value: double3 = makes_double3() let double4_value: double4 = makes_double4() let double8_value: double8 = makes_double8() takes_char2(char2_value) takes_char64(char64_value) takes_uchar3(uchar3_value) takes_uchar32(uchar32_value) takes_short3(short3_value) takes_short8(short8_value) takes_ushort1(ushort1_value) takes_ushort16(ushort16_value) takes_int3(int3_value) takes_int32(int32_value) takes_uint4(uint4_value) takes_uint2(uint2_value) takes_long2(long2_value) takes_long8(long8_value) takes_ulong4(ulong4_value) takes_ulong1(ulong1_value) takes_ll3(ll3_value) takes_ll8(ll8_value) takes_ull4(ull4_value) takes_ull16(ull16_value) #if !(os(macOS) && arch(x86_64)) takes_half2(half2_value) takes_half3(half3_value) takes_half4(half4_value) takes_half8(half8_value) takes_half16(half16_value) takes_half32(half32_value) #endif takes_float2(float2_value) takes_float3(float3_value) takes_float4(float4_value) takes_float8(float8_value) takes_float16(float16_value) takes_double2(double2_value) takes_double3(double3_value) takes_double4(double4_value) takes_double8(double8_value) // These shouldn't be imported, since there's no type to map them to. let char17_value = makes_char17() // expected-error{{cannot find 'makes_char17' in scope}} let uchar21_value = makes_uchar21() // expected-error{{cannot find 'makes_uchar21' in scope}} let short5_value = makes_short5() // expected-error{{cannot find 'makes_short5' in scope}} let ushort6_value = makes_ushort6() // expected-error{{cannot find 'makes_ushort6' in scope}} let int128_value = makes_int128() // expected-error{{cannot find 'makes_int128' in scope}} let uint20_value = makes_uint20() // expected-error{{cannot find 'makes_uint20' in scope}} takes_char17(char17_value) // expected-error{{cannot find 'takes_char17' in scope}} takes_uchar21(uchar21_value) // expected-error{{cannot find 'takes_uchar21' in scope}} takes_short5(short5_value) // expected-error{{cannot find 'takes_short5' in scope}} takes_ushort6(ushort6_value) // expected-error{{cannot find 'takes_ushort6' in scope}} takes_int128(int128_value) // expected-error{{cannot find 'takes_int128' in scope}} takes_uint20(uint20_value) // expected-error{{cannot find 'takes_uint20' in scope}}
apache-2.0
e203b0b18ed44f77e9a76bc2df46df4a
38
101
0.746019
2.68673
false
false
false
false
google/swift-structural
Sources/StructuralExamples/MyDebugString.swift
1
3520
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import StructuralCore /// A duplicate protocol, similar to MyDebugStringConvertible public protocol MyDebugString { var debugString: String { get } } // Inductive cases. extension StructuralStruct: MyDebugString where Properties: MyDebugString { public var debugString: String { let name: String if let type = self.representedType { name = String(describing: type) } else { name = "" } return "\(name)(\(body.debugString))" } } extension StructuralCons: MyDebugString where Value: MyDebugString, Next: MyDebugString { public var debugString: String { let valueString = self.value.debugString let nextString = self.next.debugString if nextString == "" { return valueString } else { return "\(valueString), \(nextString)" } } } extension StructuralProperty: MyDebugString where Value: MyDebugString { public var debugString: String { if self.name.description == "" { return self.value.debugString } else { return "\(self.name): \(self.value.debugString)" } } } extension StructuralEnum: MyDebugString where Cases: MyDebugString { public var debugString: String { let name: String if let type = self.representedType { name = String(describing: type) } else { name = "" } return "\(name).\(self.body.debugString)" } } extension StructuralEither: MyDebugString where Left: MyDebugString, Right: MyDebugString { public var debugString: String { switch self { case .left(let left): return left.debugString case .right(let right): return right.debugString } } } extension StructuralCase: MyDebugString where AssociatedValues: MyDebugString { public var debugString: String { let valuesString = associatedValues.debugString if valuesString == "" { return name.description } else { return "\(name)(\(valuesString))" } } } // Base cases. extension StructuralEmpty: MyDebugString { public var debugString: String { return "" } } extension String: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Int: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Float: MyDebugString { public var debugString: String { return String(reflecting: self) } } extension Double: MyDebugString { public var debugString: String { return String(reflecting: self) } } // Sugar extension MyDebugString where Self: Structural, Self.StructuralRepresentation: MyDebugString { public var debugString: String { return self.structuralRepresentation.debugString } }
apache-2.0
5ecbc36d2676a47f0a73a7bb7d58ae06
24.693431
75
0.651136
4.444444
false
false
false
false
pmlbrito/cookiecutter-ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Presentation/SignIn/SignInViewController.swift
1
7197
// // SignInViewController.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on 06/09/2017. // Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved. // import UIKit import Anchorage import Swiftilities protocol SignInViewControllerProtocol: BaseViewControllerProtocol { func configureLoadedState(model: SignInViewModel) } // MARK: SignInViewController class SignInViewController: BaseViewController, OnboardingViewControllerProtocol { fileprivate let headerLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 32) label.textColor = ColorSchemes.darkGray label.textAlignment = .center return label }() fileprivate let bodyLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 20) label.textColor = ColorSchemes.darkGray label.textAlignment = .center label.numberOfLines = 0 return label }() fileprivate let usernameTextView: FloatingLabelTextFieldView = { let textinput = FloatingLabelTextFieldView() textinput.font = UIFont.systemFont(ofSize: 12) textinput.textColor = ColorSchemes.darkGray textinput.textAlignment = .left textinput.placeholder = "Username" textinput.borderStyle = .line textinput.layer.borderColor = UIColor.lightGray.cgColor return textinput }() fileprivate let passwordTextView: FloatingLabelTextFieldView = { let textinput = FloatingLabelTextFieldView() textinput.font = UIFont.systemFont(ofSize: 12) textinput.textColor = ColorSchemes.darkGray textinput.textAlignment = .left textinput.placeholder = "Password" textinput.isSecureTextEntry = true textinput.borderStyle = .line textinput.layer.borderColor = UIColor.lightGray.cgColor return textinput }() fileprivate let loginButton: UIButton = { let button = UIButton() button.setTitle("PROCEED", for: .normal) //TODO: localization button.setTitleColor(UIColor.white, for: .normal) button.setTitleColor(UIColor.gray, for: .highlighted) button.backgroundColor = UIColor.blue button.titleLabel?.font = UIFont.systemFont(ofSize: 17) return button }() fileprivate let registerButton: UIButton = { let button = UIButton() button.setTitle("REGISTER", for: .normal) //TODO: localization button.setTitleColor(ColorSchemes.darkGray, for: .normal) button.setTitleColor(ColorSchemes.darkGray.highlighted, for: .highlighted) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.layer.borderColor = UIColor.darkGray.cgColor button.layer.borderWidth = 0.5 return button }() override func viewDidLoad() { super.viewDidLoad() configureView() configureLayout() (self.presenter as? SignInPresenterProtocol)?.loadSavedState() } } // MARK: Private private extension SignInViewController { func configureView() { view.backgroundColor = .white headerLabel.text = "Sign In" //TODO localization bodyLabel.text = "Please use your User Account credentials to login with the system" //TODO localization view.addSubview(headerLabel) view.addSubview(bodyLabel) view.addSubview(usernameTextView) view.addSubview(passwordTextView) loginButton.addTarget(self, action: #selector(signInTapped), for: .touchUpInside) view.addSubview(loginButton) registerButton.addTarget(self, action: #selector(registerTapped), for: .touchUpInside) view.addSubview(registerButton) } struct Layout { static let viewMarginInset = CGFloat(20) static let buttonHeight = CGFloat(55) static let inputHeight = CGFloat(45) static let headerLabelTopInset = CGFloat(100) static let bodyLabelTopSpace = CGFloat(20) static let usernameInputSideSpace = CGFloat(40) static let usernameInputTopSpace = CGFloat(40) static let passwordInputTopSpace = CGFloat(20) static let loginButtonVerticalSpace = CGFloat(30) static let registerButtonInVerticalSpace = CGFloat(18) } func configureLayout() { headerLabel.topAnchor == view.topAnchor + Layout.headerLabelTopInset headerLabel.centerXAnchor == view.centerXAnchor bodyLabel.topAnchor == headerLabel.bottomAnchor + Layout.bodyLabelTopSpace bodyLabel.centerXAnchor == view.centerXAnchor bodyLabel.leadingAnchor == view.leadingAnchor + Layout.viewMarginInset bodyLabel.trailingAnchor == view.trailingAnchor - Layout.viewMarginInset usernameTextView.topAnchor == bodyLabel.bottomAnchor + Layout.usernameInputTopSpace usernameTextView.centerXAnchor == view.centerXAnchor usernameTextView.leadingAnchor == view.leadingAnchor + Layout.usernameInputSideSpace usernameTextView.trailingAnchor == view.trailingAnchor - Layout.usernameInputSideSpace usernameTextView.heightAnchor == Layout.inputHeight passwordTextView.topAnchor == usernameTextView.bottomAnchor + Layout.passwordInputTopSpace passwordTextView.centerXAnchor == view.centerXAnchor passwordTextView.leadingAnchor == view.leadingAnchor + Layout.usernameInputSideSpace passwordTextView.trailingAnchor == view.trailingAnchor - Layout.usernameInputSideSpace passwordTextView.heightAnchor == Layout.inputHeight loginButton.leadingAnchor == view.leadingAnchor + Layout.usernameInputSideSpace loginButton.trailingAnchor == view.trailingAnchor - Layout.usernameInputSideSpace loginButton.topAnchor == passwordTextView.bottomAnchor + Layout.loginButtonVerticalSpace loginButton.heightAnchor == Layout.buttonHeight registerButton.leadingAnchor == view.leadingAnchor + Layout.usernameInputSideSpace registerButton.trailingAnchor == view.trailingAnchor - Layout.usernameInputSideSpace registerButton.topAnchor == loginButton.bottomAnchor + Layout.registerButtonInVerticalSpace registerButton.heightAnchor == Layout.buttonHeight } } // MARK: Actions Handling private extension SignInViewController { @objc func signInTapped() { //TODO: validate fields and show alert? let username = usernameTextView.text let password = passwordTextView.text if !String.isNilOrEmpty(username) && !String.isNilOrEmpty(password) { let userLogin = SignInUserCredentials(userName: username, password: password) (self.presenter as? SignInPresenterProtocol)?.doSignInUser(userCredentials: userLogin) } } @objc func registerTapped() { (self.presenter as? SignInPresenterProtocol)?.goToRegister() } } extension SignInViewController: SignInViewControllerProtocol { func configureLoadedState(model: SignInViewModel) { usernameTextView.text = model.userCredentials?.userName passwordTextView.text = model.userCredentials?.password } }
mit
4bc3eea7131e7ecbcbf8b741899256ef
38.977778
112
0.710256
5.310701
false
false
false
false
manuelescrig/SuggestionsBox
SuggestionsBox/Classes/Comment.swift
1
1574
// // Comment.swift // SuggestionsBox // An iOS library to aggregate users feedback about suggestions, // features or comments in order to help you build a better product. // // https://github.com/manuelescrig/SuggestionsBox // // Created by Manuel Escrig Ventura on 30/04/16. // Licence: MIT-Licence /** * Comment public class that represents the model for comments for each suggestion. */ open class Comment { /// An string representing the ID of the suggestion. open var suggestionId: String /// An string representing the ID of the comment. open var commentId: String /// An string representing the description of the comment describing what is about with more details. open var description: String /// An string representing the user that requested/created the comment. open var user: String /// A date representing the date when the suggestion was created. open var createdAt: Date /// Class initializer. public init(suggestionId: String, commentId: String, description: String, user: String, createdAt: Date) { self.suggestionId = suggestionId self.commentId = commentId self.description = description self.user = user self.createdAt = createdAt } open func dateString() -> String { let format = SuggestionsBoxTheme.detailDateFormat let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: createdAt) } }
mit
dbc2e5461f56e4fc12a0efc46b26a602
29.269231
105
0.670902
4.828221
false
false
false
false
mlilback/rc2SwiftClient
Networking/Session.swift
1
27295
// // Session.swift // // Copyright © 2016 Mark Lilback. This file is licensed under the ISC license. // #if os(OSX) import AppKit #endif import Rc2Common import Foundation import MJLLogger import ReactiveSwift import Starscream import Model public extension Rc2Error { var isSessionError: Bool { return nestedError is SessionError } } public enum ExecuteType: String { case run = "run", source = "source", none = "" } /// for interested parties to observe when these events happen public struct SessionEvent: Codable, Hashable { public enum EventType: String, Codable, CaseIterable, CustomStringConvertible { case execScript case execRmd case sessionError public var description: String { return rawValue } } public let type: EventType public let properties: [String: String] init(_ type: EventType, props: [String: String] = [:]) { self.type = type self.properties = props } } private enum CloseSource: String { case websocket case websocketError case error case server } public class Session { // MARK: properties ///connection information public let conInfo: ConnectionInfo //the workspace this session represents public let workspace: AppWorkspace ///abstraction of file handling public let fileCache: FileCache public let imageCache: ImageCache /// all calls to the delegate will be made on the main thread public weak var delegate: SessionDelegate? /// status of compute engine public private(set) var computeStatus: SessionResponse.ComputeStatus = .initializing public var computeIsRunning: Bool { return computeStatus == .running } // swiftlint:disable:next force_try public var project: AppProject { return try! conInfo.project(withId: workspace.projectId) } ///regex used to catch user entered calls to help so we can hijack and display through our mechanism var helpRegex: NSRegularExpression = { // (hard coded, should never fail) // swiftlint:disable:next force_try return try! NSRegularExpression(pattern: "(help\\(\\\"?([\\w\\d]+)\\\"?\\))\\s*;?\\s?", options: [.dotMatchesLineSeparators]) }() private let webSocketWorker: SessionWebSocketWorker fileprivate var openObserver: Signal<Double, Rc2Error>.Observer? public fileprivate(set) var connectionOpen: Bool = false public let eventSignal: Signal<SessionEvent, Never> private let eventObserver: Signal<SessionEvent, Never>.Observer ///if we are getting variable updates from the server private var watchingVariables: Bool = false ///queue used for delegate calls private let delegateQueue: DispatchQueue /// queue used for serializing app server outgoing messages private let appOutgoingQueue: DispatchQueue /// outgoing messages to send once status is running private var preRunningRequests: [SessionCommand]? = [] private let (sessionLifetime, sessionToken) = Lifetime.make() public var lifetime: Lifetime { return sessionLifetime } public weak var previewDelegate: SessionPreviewDelegate? private typealias PendingTransactionHandler = (PendingTransaction, SessionResponse, Rc2Error?) -> Void let debugJsonOutputRegex = try! NSRegularExpression(pattern: "<img src=\\\\\\\"data:image.*\\\\\\\"", options: [.anchorsMatchLines]) private struct PendingTransaction { let transId: String let command: SessionCommand let handler: PendingTransactionHandler init(transId: String, command: SessionCommand, handler: @escaping PendingTransactionHandler) { self.transId = transId self.command = command self.handler = handler } } ///a dictionary of transaction ids mapped to closures called when the server says the transaction is complete private var pendingTransactions: [String: PendingTransaction] = [:] // MARK: - init/open/close /// without a super class, can't use self in designated initializer. So use a private init, and a convenience init for outside use private init(connectionInfo: ConnectionInfo, workspace: AppWorkspace, fileCache: FileCache, imageCache: ImageCache, wsWorker: SessionWebSocketWorker?, queue: DispatchQueue) { self.workspace = workspace self.conInfo = connectionInfo self.fileCache = fileCache self.imageCache = imageCache self.delegateQueue = queue self.appOutgoingQueue = DispatchQueue(label: "session.appserver.outgoing", qos: .userInteractive, target: .global(qos: .userInteractive)) var ws = wsWorker if nil == ws { ws = SessionWebSocketWorker(conInfo: connectionInfo, wspaceId: workspace.wspaceId) } webSocketWorker = ws! (eventSignal, eventObserver) = Signal<SessionEvent, Never>.pipe() } /// Create a session object /// /// - Parameters: /// - connectionInfo: the connection info used for creating REST calls /// - workspace: the workspace to use for the session /// - delegate: a delegate to handle certain tasks /// - fileCache: the file cache to use. Default is to create one /// - wsWorker: the websocket to use. Defaults to a sensible implementation /// - queue: the queue to perform delegate calls on. If not a serial queue, activites aren't guaranted to be in order. Defaults to main queue public convenience init(connectionInfo: ConnectionInfo, workspace: AppWorkspace, delegate: SessionDelegate? = nil, fileCache: FileCache? = nil, wsWorker: SessionWebSocketWorker? = nil, queue: DispatchQueue? = nil) { //create a file cache if one wasn't provided var fc = fileCache if nil == fc { fc = DefaultFileCache(workspace: workspace, baseUrl: connectionInfo.host.url!, config: connectionInfo.urlSessionConfig) } let rc = Rc2RestClient(connectionInfo, fileManager: fc!.fileManager) let ic = ImageCache(restClient: rc, hostIdentifier: connectionInfo.host.name) self.init(connectionInfo: connectionInfo, workspace: workspace, fileCache: fc!, imageCache: ic, wsWorker: wsWorker, queue: queue ?? .main) ic.workspace = workspace self.delegate = delegate webSocketWorker.status.signal.take(during: sessionLifetime).observe(on: UIScheduler()).observeValues { [weak self] value in self?.webSocketStatusChanged(status: value) } webSocketWorker.messageSignal.take(during: sessionLifetime).observeResult { [weak self] result in guard case .success(let data) = result else { fatalError("error is type Never,should never happen") } self?.handleWebSocket(data: data) } } ///opens the websocket with the specified request /// - returns: future for the open session (with file loading started) or an error public func open() -> SignalProducer<Double, Rc2Error> { return SignalProducer<Double, Rc2Error> { observer, _ in guard nil == self.openObserver else { observer.send(error: Rc2Error(type: .network, nested: SessionError.unknown)) return } self.openObserver = observer self.webSocketWorker.openConnection() }.take(during: sessionLifetime) } ///closes the websocket, which can not be reopened public func close() { webSocketWorker.close() fileCache.close() } // MARK: - execute ///Sends an execute request to the server /// - parameter srcScript: the script code to send to the server /// - parameter type: whether to run or source the script public func executeScript(_ srcScript: String, type: ExecuteType = .run) { //don't send empty scripts guard !srcScript.isEmpty else { return } var script = srcScript let helpCheck = helpRegex.firstMatch(in: script, options: [], range: NSRange(location: 0, length: script.utf16.count)) if helpCheck?.numberOfRanges == 3 { let topic = String(script[(helpCheck?.range(at: 2).toStringRange(script))!]) let adjScript = script.replacingCharacters(in: (helpCheck?.range.toStringRange(script))!, with: "") delegateQueue.async { self.delegate?.respondToHelp(topic) } guard !adjScript.isEmpty else { return } script = adjScript } eventObserver.send(value: SessionEvent(.execScript, props: ["userInitited": true.description])) // TODO: need to handle execute type, or remove as parameter let cmdData = SessionCommand.ExecuteParams(sourceCode: script, transactionId: UUID().uuidString, userInitiated: true, environmentId: nil) send(command: SessionCommand.execute(cmdData)) } /// sends a request to execute a script file /// - parameter fileId: the id of the file to execute /// - parameter type: whether to run or source the file public func execute(file: AppFile, type: ExecuteType = .run) { if file.model.name.hasSuffix(".Rmd") { eventObserver.send(value: SessionEvent(.execRmd)) } let cmdData = SessionCommand.ExecuteFileParams(file: file.model, transactionId: UUID().uuidString, range: nil, echo: type == .source) send(command: SessionCommand.executeFile(cmdData)) } // MARK: - environment variables /// clears all variables in the global environment public func clearVariables() { send(command: SessionCommand.clearEnvironment(0)) } /// asks the server to delete the named variable public func deleteVariable(name: String) { // TODO: escape name or create new command that escapes on server let cmdData = SessionCommand.ExecuteParams(sourceCode: "rm(\(name))", transactionId: UUID().uuidString, userInitiated: false, environmentId: nil) send(command: SessionCommand.execute(cmdData)) } /// asks the server for a refresh of all environment variables public func forceVariableRefresh() { // used to have a watch: true argument. send(command: SessionCommand.watchVariables(SessionCommand.WatchVariablesParams(watch: true, environmentId: nil))) } /// ask the server to send a message with current variable values and delta messages as they change public func startWatchingVariables() { if watchingVariables { return; } send(command: SessionCommand.watchVariables(SessionCommand.WatchVariablesParams(watch: true, environmentId: nil))) watchingVariables = true } /// ask the server to stop sending environment delta messages public func stopWatchingVariables() { if !watchingVariables { return } send(command: SessionCommand.watchVariables(SessionCommand.WatchVariablesParams(watch: false, environmentId: nil))) watchingVariables = false } // MARK: - file handling /// Creates a new file on the server /// /// - Parameters: /// - fileName: the name of the file. should be unique /// - contentUrl: the contents of the new file if not a copy of an existing file /// - timeout: how long to wait for a file inserted message /// - completionHandler: callback with the new file id (after it has been inserted in workspace.files) or an error public func create(fileName: String, contentUrl: URL? = nil, timeout: TimeInterval = 2.0, completionHandler: ((Result<Int, Rc2Error>) -> Void)?) { precondition(workspace.file(withName: fileName) == nil) imageCache.restClient.create(fileName: fileName, workspace: workspace, contentUrl: contentUrl) .observe(on: UIScheduler()).startWithResult { result in let file: File switch result { case .success(let rfile): file = rfile case .failure(let rerror): completionHandler?(Result<Int, Rc2Error>.failure(rerror)) return } //file is on the server, but not necessarily local yet. Pre-cache the data for it let sp: SignalProducer<Void, Rc2Error> if let srcUrl = contentUrl, srcUrl.fileExists() { sp = self.fileCache.cache(file: file, srcFile: srcUrl) } else { sp = self.fileCache.cache(file: file, withData: Data()) } sp.start { (event) in switch event { case .failed(let err): completionHandler?(Result<Int, Rc2Error>.failure(err)) case .completed: self.workspace.whenFileExists(fileId: file.id, within: 2.0).startWithCompleted { completionHandler?(Result<Int, Rc2Error>.success(file.id)) } default: Log.warn("invalid event from fileCache call", .session) } } } } /// asks the server to remove a file /// - parameter file: The file to remove /// - returns: a signal producer that will be complete once the server affirms the file was removed @discardableResult public func remove(file: AppFile) -> SignalProducer<Void, Rc2Error> { return SignalProducer<Void, Rc2Error> { observer, _ in let transId = UUID().uuidString let reqData = SessionCommand.FileOperationParams(file: file.model, operation: .remove, newName: nil, transactionId: transId) let command = SessionCommand.fileOperation(reqData) self.send(command: command) self.pendingTransactions[transId] = PendingTransaction(transId: transId, command: command) { (_, response, _) in guard case let SessionResponse.fileOperation(opData) = response else { return } if let err = opData.error { observer.send(error: Rc2Error(type: .session, nested: err)) return } observer.sendCompleted() } } } /// asks the server to rename a file /// - parameter file: The file to rename /// - parameter to: What to rename it to /// - returns: a signal producer that will be complete once the server affirms the file was renamed @discardableResult public func rename(file: AppFile, to newName: String) -> SignalProducer<Void, Rc2Error> { return SignalProducer<Void, Rc2Error> { observer, _ in let transId = UUID().uuidString let reqData = SessionCommand.FileOperationParams(file: file.model, operation: .rename, newName: newName, transactionId: transId) let command = SessionCommand.fileOperation(reqData) self.send(command: command) self.pendingTransactions[transId] = PendingTransaction(transId: transId, command: command) { (_, response, _) in guard case let SessionResponse.fileOperation(opData) = response else { return } if let err = opData.error { observer.send(error: Rc2Error(type: .session, nested: err)) return } observer.sendCompleted() } } } /// duplicates a file on the server /// /// - Parameters: /// - file: the file to duplicate /// - newName: the name for the duplicate /// - Returns: signal handler with the new file's id or an error public func duplicate(file: AppFile, to newName: String) -> SignalProducer<Int, Rc2Error> { return SignalProducer<Int, Rc2Error> { observer, _ in let transId = UUID().uuidString let reqData = SessionCommand.FileOperationParams(file: file.model, operation: .duplicate, newName: newName, transactionId: transId) let command = SessionCommand.fileOperation(reqData) self.send(command: command) self.pendingTransactions[transId] = PendingTransaction(transId: transId, command: command) { (_, response, _) in guard case let SessionResponse.fileOperation(opData) = response else { return } if let err = opData.error { observer.send(error: Rc2Error(type: .session, nested: err)) return } // if it was a rename or delete, we're done guard let newFile = opData.file else { observer.send(value: opData.fileId) observer.sendCompleted() return } // for a duplicate, we need to duplcate the file data in the cache for the new file so it doesn't have to be loaded over the network self.fileCache.cache(file: newFile, srcFile: self.fileCache.cachedUrl(file: file)).startWithCompleted { observer.send(value: opData.fileId) observer.sendCompleted() } } } } /// send the server a save file message /// /// - Parameters: /// - file: the file being saved /// - contents: the contents to save /// - executeType: should the saved code be executed /// - Returns: a signal producer for success or error. Success always sends a value of true. public func sendSaveFileMessage(file: AppFile, contents: String, executeType: ExecuteType = .none) -> SignalProducer<Bool, Rc2Error> { Log.info("sendSaveFileMessage called on file \(file.fileId)", .session) return SignalProducer<Bool, Rc2Error> { observer, _ in let transId = UUID().uuidString let commandData = SessionCommand.SaveParams(file: file.model, transactionId: transId, content: contents.data(using: .utf8)!) let command = SessionCommand.save(commandData) self.pendingTransactions[transId] = PendingTransaction(transId: transId, command: command) { (_, response, error) in guard case let SessionResponse.save(saveData) = response else { return } if let err = error { if let sessionError = err.nestedError as? SessionError { self.delegateQueue.async { self.delegate?.sessionErrorReceived(sessionError, details: nil) } } observer.send(error: err) return } // need to update AppFile to new model if let file = saveData.file, let afile = self.workspace.file(withId: file.id) { let fchange = SessionResponse.FileChangedData(type: .update, file: file, fileId: afile.fileId) // swiftlint:disable:next force_try try! self.workspace.update(change: fchange) //only throws if unsupported file type, which should not be possible } observer.send(value: true) observer.sendCompleted() } self.send(command: command) } } // MARK: - preview public func requestPreviewId(fileId: Int) -> SignalProducer<Int, Rc2Error> { return SignalProducer<Int, Rc2Error> { [weak self] observer, _ in guard let me = self else { fatalError() } let transId = UUID().uuidString let params = SessionCommand.InitPreviewParams(fileId: fileId, updateIdentifier: transId) let command = SessionCommand.initPreview(params) me.send(command: command) me.pendingTransactions[transId] = PendingTransaction(transId: transId, command: command){ (_, response, error) in if let err = error { observer.send(error: err) return } guard case let SessionResponse.previewInitialized(initData) = response else { fatalError("wrong response type") } observer.send(value: initData.previewId) observer.sendCompleted() } } } public func updatePreviewChunks(previewId: Int, chunkId: Int?, includePrevious: Bool, updateId: String) -> SignalProducer<Void, Rc2Error> { return SignalProducer<Void, Rc2Error> { [weak self] observer, _ in guard let me = self else { fatalError() } let params = SessionCommand.UpdatePreviewParams(previewId: previewId, chunkId: chunkId, includePrevious: includePrevious, identifier: updateId) let command = SessionCommand.updatePreview(params) me.send(command: command) observer.sendCompleted() } } } // MARK: FileSaver extension Session: FileSaver { public func save(file: AppFile, contents: String?) -> SignalProducer<Void, Rc2Error> { guard let contents = contents else { return SignalProducer<Void, Rc2Error>(error: Rc2Error(type: .invalidArgument, explanation: "passed no contents to save")) } return sendSaveFileMessage(file: file, contents: contents, executeType: .none) .map { _ in } } } // MARK: private methods private extension Session { //we've got a dictionary of the save response. keys should be transId, success, file, error func handleSave(response: SessionResponse, data: SessionResponse.SaveData) { Log.info("handleSaveResponse called", .session) // we want to circumvent the default pending handler, as we need to run it first Log.debug("calling pending transaction", .session) guard let pending = pendingTransactions[data.transactionId] else { fatalError("save message received without pending handler") } pendingTransactions.removeValue(forKey: data.transactionId) // handle error if let error = data.error { Log.error("got save response error: \(error)", .session) pending.handler(pending, response, Rc2Error(type: .session, nested: error)) return } // both these could be asserts because they should never happen guard let rawFile = data.file else { Log.error("got save response w/o file", .session) return } guard let existingFile = workspace.file(withId: rawFile.id) else { Log.error("got save response for non-existing file", .session) return } // update file to new version existingFile.update(to: rawFile) pending.handler(pending, response, nil) } func handleFileOperation(response: SessionResponse.FileOperationData) { guard response.error == nil else { //error should have been handled via pendingTransaction return } switch response.operation { case .duplicate: //no need to do anything, fileUpdated message should arrive break case .rename: //no need to do anything, fileUpdated message should arrive break case .remove: //no need to do anything, fileUpdated message should arrive break } } func handleFileChanged(response: SessionResponse.FileChangedData) { do { try fileCache.handle(change: response) try workspace.update(change: response) } catch { Log.warn("error handing file change: \(error)", .session) } } func handleShowOutput(response: SessionResponse, data: SessionResponse.ShowOutputData) { if let ofile = workspace.file(withId: data.file.id) { ofile.update(to: data.file) //update file metadata guard let fileData = data.fileData else { // the file was too large to send via websocket. need to recache and then call delegate fileCache.recache(file: ofile).startWithCompleted { self.delegateQueue.async { self.delegate?.sessionMessageReceived(response) } } return } fileCache.cache(file: ofile.model, withData: fileData).startWithCompleted { self.delegateQueue.async { self.delegate?.sessionMessageReceived(response) } } } else { Log.warn("got show output without file downloaded", .session) delegateQueue.async { self.delegate?.sessionMessageReceived(response) } } } func handleClosed(source: CloseSource, data: SessionResponse.CloseData? = nil, error: Error? = nil) { Log.info("got closed message from \(source)", .session) connectionOpen = false delegateQueue.async { self.delegate?.sessionClosed(reason: (source == .error ? error?.localizedDescription : data?.details) ?? "unknown reason") } } /// The following will not be passed to the delegate: .fileOperation, .fileChnaged, .save, .showOutput, .info, .error, .closed // swiftlint:disable:next cyclomatic_complexity func handleReceivedMessage(_ messageData: SessionWebSocketWorker.MessageData) { let response: SessionResponse do { // TODO: handle .binary message differently guard messageData.format == .binary else { fatalError("received unsupported binary data") } if Log.isLogging(.debug, category: .session) { var dmsg = "incoming: " + String(data: messageData.data, encoding: .utf8)! dmsg = debugJsonOutputRegex.stringByReplacingMatches(in: dmsg, options: [], range: NSRange(dmsg.startIndex..<dmsg.endIndex, in: dmsg), withTemplate: "<B>IMG HERE</B>") Log.debug(dmsg, .session) } response = try conInfo.decode(data: messageData.data) } catch { Log.info("failed to parse received json: \(String(data: messageData.data, encoding: .utf8) ?? "<invalid>"): \(error)", .session) return } Log.info("got message update: \(response)", .session) var informDelegate = false switch response { case .fileOperation(let opData): handleFileOperation(response: opData) case .fileChanged(let changeData): handleFileChanged(response: changeData) case .save(let saveData): handleSave(response: response, data: saveData) case .showOutput(let outputData): handleShowOutput(response: response, data: outputData) case .info(let infoData): conInfo.update(sessionInfo: infoData) case .closed(let closeData): handleClosed(source: .server, data: closeData) case .error(let errorData): eventObserver.send(value: SessionEvent(.sessionError, props: ["error": errorData.error.localizedDescription])) delegateQueue.async { self.delegate?.sessionErrorReceived(errorData.error, details: nil) } case .computeStatus(let status): let sendPreCommands = !computeIsRunning && status == .running computeStatus = status informDelegate = true if sendPreCommands { preRunningRequests?.forEach { send(command: $0) } preRunningRequests = nil } case .execComplete(let execData): if !execData.images.isEmpty { imageCache.cache(images: execData.images) } informDelegate = true case .previewInitialized: // no need to do anything, request callback deals with it break case .previewUpdated(let data): previewDelegate?.previewUpdateReceived(response: data) case .previewUpdateStarted(let data): previewDelegate?.previewUpdateStarted(response: data) default: informDelegate = true } if informDelegate { delegateQueue.async { self.delegate?.sessionMessageReceived(response) } } if let transId = transactionId(for: response), let trans = pendingTransactions[transId] { trans.handler(trans, response, nil) pendingTransactions.removeValue(forKey: transId) } } /// returns the transactionId for the response, if there is one // swiftlint:disable cyclomatic_complexity private func transactionId(for response: SessionResponse) -> String? { switch response { case .computeStatus: return nil case .connected: return nil case .closed: return nil case .echoExecute(let data): return data.transactionId case .echoExecuteFile(let data): return data.transactionId case .error(let err): return err.transactionId case .execComplete(let data): return data.transactionId case .fileChanged: return nil case .fileOperation(let data): return data.transactionId case .help: return nil case .results(let data): return data.transactionId case .save(let data): return data.transactionId case .showOutput(let data): return data.transactionId case .variableValue: return nil case .variables: return nil case .info: return nil case .environmentCreated: return nil case .previewInitialized(let data): return data.updateIdentifier case .previewUpdated(let data): return data.updateIdentifier case .previewUpdateStarted(let data): return data.updateIdentifier } } @discardableResult func send(command: SessionCommand) -> Bool { do { let data = try conInfo.encode(command) let cmdStr = String(data: data, encoding:.utf8)! appOutgoingQueue.sync { guard computeIsRunning else { Log.info("queueing command until compute is running") preRunningRequests?.append(command) return } Log.info("sending:\n \(cmdStr)") self.webSocketWorker.send(data: data) } return true } catch let err as NSError { Log.error("error sending message on websocket: \(err)", .session) return false } } private func webSocketStatusChanged(status: SessionWebSocketWorker.SocketStatus) { switch status { case .uninitialized: fatalError("status should never change to uninitialized") case .connecting: Log.debug("connecting", .session) case .connected: completePostOpenSetup() case .closed: handleClosed(source: .websocket) case .failed(let err): handleClosed(source: .websocketError, error: err) } } func handleWebSocket(data: SessionWebSocketWorker.MessageData) { handleReceivedMessage(data) } /// starts file caching and forwards responses to observer from open() call private func completePostOpenSetup() { fileCache.cacheAllFiles().on(failed: { (cacheError) in self.openObserver?.send(error: cacheError) }, completed: { self.connectionOpen = true self.openObserver?.sendCompleted() self.openObserver = nil }, value: { (progPercent) in self.openObserver?.send(value: progPercent) }).start() } }
isc
8470c7e7c157d98650de0ebbac7b43a7
37.388186
214
0.728768
3.78138
false
false
false
false
cliqz-oss/browser-ios
Storage/SQL/GenericTable.swift
2
7173
/* 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 XCGLogger import Shared private let log = Logger.syncLogger // A protocol for information about a particular table. This is used as a type to be stored by TableTable. protocol TableInfo { var name: String { get } var version: Int { get } } // A wrapper class for table info coming from the TableTable. This should ever only be used internally. class TableInfoWrapper: TableInfo { let name: String let version: Int init(name: String, version: Int) { self.name = name self.version = version } } /** * Something that knows how to construct part of a database. */ protocol SectionCreator: TableInfo { func create(_ db: SQLiteDBConnection) -> Bool } protocol SectionUpdater: TableInfo { func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool } /* * This should really be called "Section" or something like that. */ protocol Table: SectionCreator, SectionUpdater { func exists(_ db: SQLiteDBConnection) -> Bool func drop(_ db: SQLiteDBConnection) -> Bool } /** * A table in our database. Note this doesn't have to be a real table. It might be backed by a join * or something else interesting. */ protocol BaseTable: Table { associatedtype CurrentType func insert(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int? func update(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int func delete(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int func query(_ db: SQLiteDBConnection, options: QueryOptions?) -> Cursor<CurrentType> } public enum QuerySort { case none, lastVisit, frecency } open class QueryOptions { // A filter string to apploy to the query open var filter: Any? = nil // Allows for customizing how the filter is applied (i.e. only urls or urls and titles?) open var filterType: FilterType = .none // The way to sort the query open var sort: QuerySort = .none public init(filter: Any? = nil, filterType: FilterType = .none, sort: QuerySort = .none) { self.filter = filter self.filterType = filterType self.sort = sort } } public enum FilterType { case exactUrl case url case guid case id case none } let DBCouldNotOpenErrorCode = 200 enum TableResult { case exists // The table already existed. case created // The table was correctly created. case updated // The table was updated to a new version. case failed // Table creation failed. } open class GenericTable<T>: BaseTable { typealias CurrentType = T // Implementors need override these methods var name: String { return "" } var version: Int { return 0 } var rows: String { return "" } var factory: ((_ row: SDRow) -> CurrentType)? { return nil } // These methods take an inout object to avoid some runtime crashes that seem to be due // to using generics. Yay Swift! func getInsertAndArgs(_ item: inout CurrentType) -> (String, Args)? { return nil } func getUpdateAndArgs(_ item: inout CurrentType) -> (String, Args)? { return nil } func getDeleteAndArgs(_ item: inout CurrentType?) -> (String, Args)? { return nil } func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? { return nil } func create(_ db: SQLiteDBConnection) -> Bool { if let err = db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (\(rows))") { log.error("Error creating \(self.name) - \(err)") return false } return true } func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = self.version log.debug("Update table \(self.name) from \(from) to \(to)") return false } func exists(_ db: SQLiteDBConnection) -> Bool { let res = db.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name=?", factory: StringFactory, withArgs: [name]) return res.count > 0 } func drop(_ db: SQLiteDBConnection) -> Bool { let sqlStr = "DROP TABLE IF EXISTS \(name)" let args = [AnyObject?]() let err = db.executeChange(sqlStr, withArgs: args) if err != nil { log.error("Error dropping \(self.name): \(err)") } return err == nil } /** * Returns nil or the last inserted row ID. * err will be nil if there was no error (e.g., INSERT OR IGNORE). */ func insert(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int? { if var site = item { if let (query, args) = self.getInsertAndArgs(&site) { let previous = db.lastInsertedRowID if let error = db.executeChange(query, withArgs: args) { err = error return nil } let now = db.lastInsertedRowID if previous == now { log.debug("INSERT did not change last inserted row ID.") return nil } return now } } err = NSError(domain: "mozilla.org", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Tried to save something that isn't a site" ]) return -1 } func update(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int { if var item = item { if let (query, args) = getUpdateAndArgs(&item) { if let error = db.executeChange(query, withArgs: args) { log.error(error.description) err = error return 0 } return db.numberOfRowsModified } } err = NSError(domain: "mozilla.org", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Tried to save something that isn't a site" ]) return 0 } func delete(_ db: SQLiteDBConnection, item: CurrentType?, err: inout NSError?) -> Int { if var item: CurrentType? = item { if let (query, args) = getDeleteAndArgs(&item) { if let error = db.executeChange(query, withArgs: args) { print(error.description) err = error return 0 } return db.numberOfRowsModified } } return 0 } func query(_ db: SQLiteDBConnection, options: QueryOptions?) -> Cursor<CurrentType> { if let (query, args) = getQueryAndArgs(options) { if let factory = self.factory { let c = db.executeQuery(query, factory: factory, withArgs: args) return c } } return Cursor(status: CursorStatus.Failure, msg: "Invalid query: \(options?.filter)") } }
mpl-2.0
07a400fca9f542c4f2b84db1ffbfc79e
30.460526
141
0.595009
4.51416
false
false
false
false
rockbruno/swiftshield
Sources/SwiftShieldCore/BaseModels/AccessControl.swift
1
315
import Foundation enum AccessControl: String { case open = "source.decl.attribute.open" case `public` = "source.decl.attribute.public" case `private` = "source.decl.attribute.private" case `fileprivate` = "source.decl.attribute.fileprivate" case `internal` = "source.decl.attribute.internal" }
gpl-3.0
f7d979c50fc530aaae676ef748edb487
34
60
0.71746
3.705882
false
false
false
false
rasmusth/BluetoothKit
Example/Vendor/CryptoSwift/Sources/CryptoSwift/Rabbit.swift
3
6785
// // Rabbit.swift // CryptoSwift // // Created by Dima Kalachov on 12/11/15. // Copyright © 2015 Marcin Krzyzanowski. All rights reserved. // private typealias Key = SecureBytes final public class Rabbit: BlockCipher { public enum Error: Swift.Error { case invalidKeyOrInitializationVector } /// Size of IV in bytes public static let ivSize = 64 / 8 /// Size of key in bytes public static let keySize = 128 / 8 /// Size of block in bytes public static let blockSize = 128 / 8 /// Key private let key: Key /// IV (optional) private let iv: Array<UInt8>? /// State variables private var x = Array<UInt32>(repeating: 0, count: 8) /// Counter variables private var c = Array<UInt32>(repeating: 0, count: 8) /// Counter carry private var p7: UInt32 = 0 /// 'a' constants private var a: Array<UInt32> = [ 0x4D34D34D, 0xD34D34D3, 0x34D34D34, 0x4D34D34D, 0xD34D34D3, 0x34D34D34, 0x4D34D34D, 0xD34D34D3, ] // MARK: - Initializers convenience public init(key:Array<UInt8>) throws { try self.init(key: key, iv: nil) } public init(key:Array<UInt8>, iv:Array<UInt8>?) throws { self.key = Key(bytes: key) self.iv = iv guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { throw Error.invalidKeyOrInitializationVector } } // MARK: - fileprivate func setup() { p7 = 0 // Key divided into 8 subkeys var k = Array<UInt32>(repeating: 0, count: 8) for j in 0..<8 { k[j] = UInt32(key[Rabbit.blockSize - (2*j + 1)]) | (UInt32(key[Rabbit.blockSize - (2*j + 2)]) << 8) } // Initialize state and counter variables from subkeys for j in 0..<8 { if j % 2 == 0 { x[j] = (k[(j+1) % 8] << 16) | k[j] c[j] = (k[(j+4) % 8] << 16) | k[(j+5) % 8] } else { x[j] = (k[(j+5) % 8] << 16) | k[(j+4) % 8] c[j] = (k[j] << 16) | k[(j+1) % 8] } } // Iterate system four times nextState() nextState() nextState() nextState() // Reinitialize counter variables for j in 0..<8 { c[j] = c[j] ^ x[(j+4) % 8] } if let iv = iv { setupIV(iv) } } private func setupIV(_ iv: Array<UInt8>) { // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits // 0 1 2 3 4 5 6 7 IV bytes in array let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]]) let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]]) let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]]) let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]]) // Modify the counter state as function of the IV c[0] = c[0] ^ iv0 c[1] = c[1] ^ iv1 c[2] = c[2] ^ iv2 c[3] = c[3] ^ iv3 c[4] = c[4] ^ iv0 c[5] = c[5] ^ iv1 c[6] = c[6] ^ iv2 c[7] = c[7] ^ iv3 // Iterate system four times nextState() nextState() nextState() nextState() } private func nextState() { // Before an iteration the counters are incremented var carry = p7 for j in 0..<8 { let prev = c[j] c[j] = prev &+ a[j] &+ carry carry = prev > c[j] ? 1 : 0 // detect overflow } p7 = carry // save last carry bit // Iteration of the system var newX = Array<UInt32>(repeating: 0, count: 8) newX[0] = g(0) &+ rotateLeft(g(7), by: 16) &+ rotateLeft(g(6), by: 16) newX[1] = g(1) &+ rotateLeft(g(0), by: 8) &+ g(7) newX[2] = g(2) &+ rotateLeft(g(1), by: 16) &+ rotateLeft(g(0), by: 16) newX[3] = g(3) &+ rotateLeft(g(2), by: 8) &+ g(1) newX[4] = g(4) &+ rotateLeft(g(3), by: 16) &+ rotateLeft(g(2), by: 16) newX[5] = g(5) &+ rotateLeft(g(4), by: 8) &+ g(3) newX[6] = g(6) &+ rotateLeft(g(5), by: 16) &+ rotateLeft(g(4), by: 16) newX[7] = g(7) &+ rotateLeft(g(6), by: 8) &+ g(5) x = newX } private func g(_ j: Int) -> UInt32 { let sum = x[j] &+ c[j] let square = UInt64(sum) * UInt64(sum) return UInt32(truncatingBitPattern: square ^ (square >> 32)) } fileprivate func nextOutput() -> Array<UInt8> { nextState() var output16 = [UInt16](repeating: 0, count: Rabbit.blockSize / 2) output16[7] = UInt16(truncatingBitPattern: x[0]) ^ UInt16(truncatingBitPattern: x[5] >> 16) output16[6] = UInt16(truncatingBitPattern: x[0] >> 16) ^ UInt16(truncatingBitPattern: x[3]) output16[5] = UInt16(truncatingBitPattern: x[2]) ^ UInt16(truncatingBitPattern: x[7] >> 16) output16[4] = UInt16(truncatingBitPattern: x[2] >> 16) ^ UInt16(truncatingBitPattern: x[5]) output16[3] = UInt16(truncatingBitPattern: x[4]) ^ UInt16(truncatingBitPattern: x[1] >> 16) output16[2] = UInt16(truncatingBitPattern: x[4] >> 16) ^ UInt16(truncatingBitPattern: x[7]) output16[1] = UInt16(truncatingBitPattern: x[6]) ^ UInt16(truncatingBitPattern: x[3] >> 16) output16[0] = UInt16(truncatingBitPattern: x[6] >> 16) ^ UInt16(truncatingBitPattern: x[1]) var output8 = Array<UInt8>(repeating: 0, count: Rabbit.blockSize) for j in 0..<output16.count { output8[j * 2] = UInt8(truncatingBitPattern: output16[j] >> 8) output8[j * 2 + 1] = UInt8(truncatingBitPattern: output16[j]) } return output8 } } // MARK: Cipher extension Rabbit: Cipher { public func encrypt<C: Collection>(_ bytes: C) -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { setup() var result = Array<UInt8>(repeating: 0, count: bytes.count) var output = nextOutput() var byteIdx = 0 var outputIdx = 0 while byteIdx < bytes.count { if (outputIdx == Rabbit.blockSize) { output = nextOutput() outputIdx = 0 } result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] byteIdx += 1 outputIdx += 1 } return result } public func decrypt<C: Collection>(_ bytes: C) -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int { return encrypt(bytes) } }
mit
c74ad1e3583553e7bb41e6654fda64a4
31.932039
142
0.510171
3.398798
false
false
false
false
CodeEagle/RainbowTransition
Sources/ETNavBarTransparent.swift
1
20230
// // ETNavBarTransparent.swift // ETNavBarTransparentDemo // // Created by Bing on 2017/3/1. // Copyright © 2017年 tanyunbing. All rights reserved. // import UIKit import KVOBlock extension UIColor { // System default bar tint color open class var defaultNavBarTintColor: UIColor { return UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1.0) } } extension DispatchQueue { private static var onceTracker = [String]() public class func once(token: String, block: () -> Void) { objc_sync_enter(self) defer { objc_sync_exit(self) } if onceTracker.contains(token) { return } onceTracker.append(token) block() } } // MARK: - UINavigationController extension UINavigationController { public func enableRainbowTransition(with color: UIColor = .white, shadow enable: Bool = true) { UINavigationController._initialize() let bgg = NavigationBarrOverlay(frame: .zero) let parent = getBarView().0 let barBackgroundView = getBarView().1 parent.addSubview(bgg) parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[bgg]-0-|", options: NSLayoutFormatOptions.alignAllTop, metrics: nil, views: ["bgg": bgg])) parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[bgg]-0-|", options: NSLayoutFormatOptions.directionLeftToRight, metrics: nil, views: ["bgg": bgg])) bgg.tag = 9854 bgg.backgroundColor = color bgg.shadowParent = barBackgroundView.layer bgg.enableShadow(enable: enable) } fileprivate var lo_bg: NavigationBarrOverlay? { let parent = getBarView().0 return parent.viewWithTag(9854) as? NavigationBarrOverlay } private func getBarView() -> (UIView, UIView) { let barBackgroundView = navigationBar.subviews[0] let valueForKey = barBackgroundView.value(forKey:) var parenet = barBackgroundView if navigationBar.isTranslucent { if #available(iOS 10.0, *) { if let backgroundEffectView = valueForKey("_backgroundEffectView") as? UIVisualEffectView, navigationBar.backgroundImage(for: .default) == nil { parenet = backgroundEffectView.contentView } } else { if let adaptiveBackdrop = valueForKey("_adaptiveBackdrop") as? UIView, let backdropEffectView = adaptiveBackdrop.value(forKey: "_backdropEffectView") as? UIVisualEffectView { parenet = backdropEffectView.contentView } } } return (parenet, barBackgroundView) } public func enableShadow(enable: Bool = true) { lo_bg?.enableShadow(enable: enable) } public var globalNavBarTintColor: UIColor { get { guard let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.globalNavBarTintColor) as? UIColor else { return UIColor.defaultNavBarTintColor } return tintColor } set { navigationController?.navigationBar.tintColor = newValue objc_setAssociatedObject(self, &AssociatedKeys.globalNavBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } open override var preferredStatusBarStyle: UIStatusBarStyle { return topViewController?.preferredStatusBarStyle ?? .default } private static let onceToken = UUID().uuidString internal static func _initialize() { guard self == UINavigationController.self else { return } DispatchQueue.once(token: onceToken) { let needSwizzleSelectorArr = [ NSSelectorFromString("_updateInteractiveTransition:"), #selector(popToViewController), #selector(popToRootViewController), ] for selector in needSwizzleSelectorArr { let str = ("et_" + selector.description).replacingOccurrences(of: "__", with: "_") // popToRootViewControllerAnimated: et_popToRootViewControllerAnimated: let originalMethod = class_getInstanceMethod(self, selector) let swizzledMethod = class_getInstanceMethod(self, Selector(str)) method_exchangeImplementations(originalMethod, swizzledMethod) } } } // MARK: swizzMethod func et_updateInteractiveTransition(_ percentComplete: CGFloat) { guard let topViewController = topViewController, let coordinator = topViewController.transitionCoordinator else { et_updateInteractiveTransition(percentComplete) return } let fromViewController = coordinator.viewController(forKey: .from) let toViewController = coordinator.viewController(forKey: .to) // Bg Alpha let fromAlpha = fromViewController?.navBarBgAlpha ?? 0 let toAlpha = toViewController?.navBarBgAlpha ?? 0 let newAlpha = fromAlpha + (toAlpha - fromAlpha) * percentComplete setNeedsNavigationBackground(alpha: newAlpha) enableShadow(enable: toViewController?.navBarBgShadow ?? false) // Tint Color let fromColor = fromViewController?.navBarTintColor ?? globalNavBarTintColor let toColor = toViewController?.navBarTintColor ?? globalNavBarTintColor let newColor = averageColor(fromColor: fromColor, toColor: toColor, percent: percentComplete) navigationBar.tintColor = newColor let midColor = averageColor(fromColor: (fromViewController?.navBarBGColor ?? .white), toColor: (toViewController?.navBarBGColor ?? .white), percent: percentComplete) lo_bg?.update(color: midColor.withAlphaComponent(toAlpha), drag: false) et_updateInteractiveTransition(percentComplete) } // Calculate the middle Color with translation percent private func averageColor(fromColor: UIColor, toColor: UIColor, percent: CGFloat) -> UIColor { var fromRed: CGFloat = 0 var fromGreen: CGFloat = 0 var fromBlue: CGFloat = 0 var fromAlpha: CGFloat = 0 fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha) var toRed: CGFloat = 0 var toGreen: CGFloat = 0 var toBlue: CGFloat = 0 var toAlpha: CGFloat = 0 toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha) let nowRed = fromRed + (toRed - fromRed) * percent let nowGreen = fromGreen + (toGreen - fromGreen) * percent let nowBlue = fromBlue + (toBlue - fromBlue) * percent let nowAlpha = fromAlpha + (toAlpha - fromAlpha) * percent return UIColor(red: nowRed, green: nowGreen, blue: nowBlue, alpha: nowAlpha) } func et_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? { setNeedsNavigationBackground(alpha: viewController.navBarBgAlpha) let color = viewController.navBarBGColor lo_bg?.update(color: color.withAlphaComponent(viewController.navBarBgAlpha), drag: lo_poping) navigationBar.tintColor = viewController.navBarTintColor ?? globalNavBarTintColor return et_popToViewController(viewController, animated: animated) } func et_popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? { let alpha = viewControllers.first?.navBarBgAlpha ?? 0 setNeedsNavigationBackground(alpha: alpha) let color = viewControllers.first?.navBarBGColor ?? .white lo_bg?.update(color: color.withAlphaComponent(alpha), drag: lo_poping) navigationBar.tintColor = viewControllers.first?.navBarTintColor ?? globalNavBarTintColor return et_popToRootViewControllerAnimated(animated) } public func setNeedsNavigationBackground(alpha: CGFloat, animated: Bool = false) { let barBackgroundView = navigationBar.subviews[0] let valueForKey = barBackgroundView.value(forKey:) if let shadowView = valueForKey("_shadowView") as? UIView { shadowView.alpha = alpha } let color = topViewController?.navBarBGColor ?? .white lo_bg?.update(color: color.withAlphaComponent(alpha), drag: lo_poping) func aniamte(action: @escaping () -> Void) { UIView.animate(withDuration: 0.2) { action() } } if navigationBar.isTranslucent { if #available(iOS 10.0, *) { if let backgroundEffectView = valueForKey("_backgroundEffectView") as? UIView, navigationBar.backgroundImage(for: .default) == nil { if animated { aniamte { backgroundEffectView.alpha = alpha } } else { backgroundEffectView.alpha = alpha } return } } else { if let adaptiveBackdrop = valueForKey("_adaptiveBackdrop") as? UIView, let backdropEffectView = adaptiveBackdrop.value(forKey: "_backdropEffectView") as? UIView { if animated { aniamte { backdropEffectView.alpha = alpha } } else { backdropEffectView.alpha = alpha } return } } } if animated { aniamte { barBackgroundView.alpha = alpha } } else { barBackgroundView.alpha = alpha } } } // MARK: - UINavigationBarDelegate extension UINavigationController: UINavigationBarDelegate { public func navigationBar(_ navigationBar: UINavigationBar, shouldPop _: UINavigationItem) -> Bool { if let topVC = topViewController, let coor = topVC.transitionCoordinator, coor.initiallyInteractive { if #available(iOS 10.0, *) { coor.notifyWhenInteractionChanges { context in self.dealInteractionChanges(context) } } else { coor.notifyWhenInteractionEnds { context in self.dealInteractionChanges(context) } } return true } let itemCount = navigationBar.items?.count ?? 0 let n = viewControllers.count >= itemCount ? 2 : 1 let popToVC = viewControllers[viewControllers.count - n] enableShadow(enable: popToVC.navBarBgShadow) lo_bg?.update(color: popToVC.navBarBGColor, drag: false) popToViewController(popToVC, animated: true) return true } public func navigationBar(_ navigationBar: UINavigationBar, shouldPush _: UINavigationItem) -> Bool { setNeedsNavigationBackground(alpha: topViewController?.navBarBgAlpha ?? 0) enableShadow(enable: topViewController?.navBarBgShadow ?? false) lo_bg?.update(color: (topViewController?.navBarBGColor ?? .white).withAlphaComponent(topViewController?.navBarBgAlpha ?? 1), drag: false) navigationBar.tintColor = topViewController?.navBarTintColor ?? globalNavBarTintColor return true } private func dealInteractionChanges(_ context: UIViewControllerTransitionCoordinatorContext) { let animations: (UITransitionContextViewControllerKey) -> Void = { let nowAlpha = context.viewController(forKey: $0)?.navBarBgAlpha ?? 0 self.setNeedsNavigationBackground(alpha: nowAlpha) self.navigationBar.tintColor = (context.viewController(forKey: $0)?.navBarTintColor) ?? self.globalNavBarTintColor } if context.isCancelled { let cancelDuration: TimeInterval = context.transitionDuration * Double(context.percentComplete) let vc = context.viewController(forKey: .to) vc?.lo_poping = true let shadow = context.viewController(forKey: .from)?.navBarBgShadow ?? false enableShadow(enable: shadow) lo_bg?.update(color: (topViewController?.navBarBGColor ?? .white).withAlphaComponent(topViewController?.navBarBgAlpha ?? 1), drag: false) UIView.animate(withDuration: cancelDuration, animations: { animations(.from) }, completion: { _ in vc?.lo_poping = false }) } else { let finishDuration: TimeInterval = context.transitionDuration * Double(1 - context.percentComplete) UIView.animate(withDuration: finishDuration) { animations(.to) } } } } // MARK: - UIViewController extension extension UIViewController { fileprivate struct AssociatedKeys { static var navBarBgShadow: String = "navBarBgShadow" static var navBarBgAlpha: CGFloat = 1.0 static var globalNavBarTintColor: UIColor = UIColor.defaultNavBarTintColor static var navBarTintColor: UIColor = UIColor.defaultNavBarTintColor static var navBarBGColor: UIColor = UIColor.white static var bg = "bg" static var poping = "poping" static let keyPath = "contentOffset" static var distance = "distance" static var scrollView = "_RKeys_.scrollView" static var scrollViewWrapper = "_RKeys_.scrollViewWrapper" } public var navBarBgShadow: Bool { get { guard let value = objc_getAssociatedObject(self, &AssociatedKeys.navBarBgShadow) as? Bool else { return false } return value } set { objc_setAssociatedObject(self, &AssociatedKeys.navBarBgShadow, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) navigationController?.lo_bg?.enableShadow(enable: newValue) } } public var navBarBgAlpha: CGFloat { get { guard let alpha = objc_getAssociatedObject(self, &AssociatedKeys.navBarBgAlpha) as? CGFloat else { return 1.0 } return alpha } set { let alpha = max(min(newValue, 1), 0) // 必须在 0~1的范围 objc_setAssociatedObject(self, &AssociatedKeys.navBarBgAlpha, alpha, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) navigationController?.setNeedsNavigationBackground(alpha: alpha) } } public func setNavBarBgAlphaAnimated(value: CGFloat) { let alpha = max(min(value, 1), 0) // 必须在 0~1的范围 objc_setAssociatedObject(self, &AssociatedKeys.navBarBgAlpha, alpha, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) navigationController?.setNeedsNavigationBackground(alpha: value, animated: true) } public var navBarTintColor: UIColor? { get { let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.navBarTintColor) as? UIColor return tintColor } set { navigationController?.navigationBar.tintColor = newValue objc_setAssociatedObject(self, &AssociatedKeys.navBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var navBarBGColor: UIColor { get { guard let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.navBarBGColor) as? UIColor else { return UIColor.white } return tintColor } set { objc_setAssociatedObject(self, &AssociatedKeys.navBarBGColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var lo_poping: Bool { get { return (objc_getAssociatedObject(self, &AssociatedKeys.poping) as? Bool) ?? false } set { objc_setAssociatedObject(self, &AssociatedKeys.poping, newValue, .OBJC_ASSOCIATION_RETAIN) } } private var lo_ob: Bool { get { return (objc_getAssociatedObject(self, &AssociatedKeys.scrollView) as? Bool) ?? false } set { objc_setAssociatedObject(self, &AssociatedKeys.scrollView, newValue, .OBJC_ASSOCIATION_RETAIN) } } private var lo_distance: CGFloat { get { return (objc_getAssociatedObject(self, &AssociatedKeys.distance) as? CGFloat) ?? 0 } set { objc_setAssociatedObject(self, &AssociatedKeys.distance, newValue, .OBJC_ASSOCIATION_RETAIN) } } private var _wrapper: ScrollViewWrapper { get { if let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.scrollViewWrapper) as? ScrollViewWrapper { return wrapper } let wrapper = ScrollViewWrapper() objc_setAssociatedObject(self, &AssociatedKeys.scrollViewWrapper, wrapper, .OBJC_ASSOCIATION_RETAIN) return wrapper } set { objc_setAssociatedObject(self, &AssociatedKeys.scrollViewWrapper, newValue, .OBJC_ASSOCIATION_RETAIN) } } public func transparent(with scroll: UIScrollView?, total distance: CGFloat = 200, force: Bool = false, setAlphaForFirstTime: Bool = true) { guard let value = scroll else { return } if force == false, lo_ob == true { return } lo_ob = true if let sc = _wrapper.scrollView { sc.removeObserver(for: AssociatedKeys.keyPath) } _wrapper.scrollView = value lo_distance = distance var fisrtTime = false value.observeKeyPath(AssociatedKeys.keyPath, with: { [weak self] _, oldValue, newValue in guard let navi = self?.navigationController, navi.topViewController == self, self?.lo_poping == false else { return } guard let v = newValue as? CGPoint, let o = oldValue as? CGPoint else { return } if v == o, v == .zero { return } var a = v.y / distance if a < 0 { a = 0 } if a > 1 { a = 1 } if fisrtTime, setAlphaForFirstTime == false { fisrtTime = false return } self?.navBarBgAlpha = a self?.setNeedsStatusBarAppearanceUpdate() }) } public func rt_alpha(for scrollView: UIScrollView) -> CGFloat { if lo_distance == 0 { return 1 } var a = scrollView.contentOffset.y / lo_distance if a < 0 { a = 0 } if a > 1 { a = 1 } return a } public func unregister(scollView: UIScrollView?) { scollView?.removeObserver(for: AssociatedKeys.keyPath) } } private final class ScrollViewWrapper { weak var scrollView: UIScrollView? } // MARK: - NavigationBarrOverlay private final class NavigationBarrOverlay: UIView { weak var shadowParent: CALayer? lazy var shadowMask: CAGradientLayer = { let gMask = CAGradientLayer() gMask.colors = [UIColor(white: 0, alpha: 0.4).cgColor, UIColor.clear.cgColor] gMask.locations = [0, 1] gMask.anchorPoint = CGPoint.zero gMask.startPoint = CGPoint(x: 0.5, y: 0) gMask.endPoint = CGPoint(x: 0.5, y: 1) gMask.opacity = 0 return gMask }() fileprivate func enableShadow(enable: Bool = true) { if enable { if shadowMask.superlayer != layer { shadowParent?.addSublayer(shadowMask) } } else { shadowMask.removeFromSuperlayer() } } override init(frame _: CGRect) { super.init(frame: .zero) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false shadowParent?.addSublayer(shadowMask) } fileprivate override func layoutSubviews() { super.layoutSubviews() shadowMask.frame = bounds } fileprivate func update(color value: UIColor, drag: Bool) { let alpha = Float(value.cgColor.alpha) if drag { shadowMask.opacity = 1 - alpha } else { if alpha != 0 { shadowMask.opacity = 0 } else if shadowMask.opacity != 1 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in self?.shadowMask.opacity = 1 }) } } backgroundColor = value } }
mit
1a1ef805e2d1c3dd5d7f6c13ad1248cd
39.896761
190
0.633173
4.995796
false
false
false
false
17AustinZ/Poker-Chip
ConfigureCells/PlayerCell.swift
1
559
// // PlayerCell.swift // ChipManager // // Created by Austin Zhang on 8/9/15. // Copyright (c) 2015 Austin Zhang. All rights reserved. // import Foundation class PlayerCell : UITableViewCell{ @IBOutlet weak var chipNumber: UILabel! @IBOutlet weak var nameLabel: UILabel! var player : Player? { didSet{ if let player = player, chipNumber = chipNumber, nameLabel = nameLabel{ self.chipNumber.text = String(player.chips!) self.nameLabel.text = player.name! } } } }
mit
6d8b6fe5a3eff2954238fcb7bce4020f
21.4
83
0.610018
4.050725
false
false
false
false
CosmicMind/Material
Sources/iOS/Layout/Layout.swift
3
45710
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Motion /// A protocol that's conformed by UIView and UILayoutGuide. public protocol Constraintable: class { } @available(iOS 9.0, *) extension UILayoutGuide: Constraintable { } extension UIView: Constraintable { } /// Layout extension for UIView. public extension UIView { /** Used to chain layout constraints on a child context. - Parameter child: A child UIView to layout. - Returns: A Layout instance. */ func layout(_ child: UIView) -> Layout { if self != child.superview { addSubview(child) } child.translatesAutoresizingMaskIntoConstraints = false return child.layout } /// Layout instance for the view. var layout: Layout { return Layout(constraintable: self) } /// Anchor instance for the view. var anchor: LayoutAnchor { return LayoutAnchor(constraintable: self) } /** Anchor instance for safeAreaLayoutGuide. Below iOS 11, it will be same as view.anchor. */ var safeAnchor: LayoutAnchor { if #available(iOS 11.0, *) { return LayoutAnchor(constraintable: safeAreaLayoutGuide) } else { return anchor } } } private extension NSLayoutConstraint { /** Checks if the constraint is equal to given constraint. - Parameter _ other: An NSLayoutConstraint. - Returns: A Bool indicating whether constraints are equal. */ func equalTo(_ other: NSLayoutConstraint) -> Bool { return firstItem === other.firstItem && secondItem === other.secondItem && firstAttribute == other.firstAttribute && secondAttribute == other.secondAttribute && relation == other.relation } } /// A memory reference to the lastConstraint of UIView. private var LastConstraintKey: UInt8 = 0 private extension UIView { /** The last consntraint that's created by Layout system. Used to set multiplier/priority on the last constraint. */ var lastConstraint: NSLayoutConstraint? { get { return AssociatedObject.get(base: self, key: &LastConstraintKey) { nil } } set(value) { AssociatedObject.set(base: self, key: &LastConstraintKey, value: value) } } } public struct Layout { /// A weak reference to the constraintable. public weak var constraintable: Constraintable? /// Parent view of the view. var parent: UIView? { return (constraintable as? UIView)?.superview } /// Returns the view that is being laied out. public var view: UIView? { var v = constraintable as? UIView if #available(iOS 9.0, *), v == nil { v = (constraintable as? UILayoutGuide)?.owningView } return v } /** An initializer taking Constraintable. - Parameter view: A Constraintable. */ init(constraintable: Constraintable) { self.constraintable = constraintable } } public extension Layout { /** Sets multiplier of the last created constraint. Not meant for updating the multiplier as it will re-create the constraint. - Parameter _ multiplier: A CGFloat multiplier. - Returns: A Layout instance to allow chaining. */ @discardableResult func multiply(_ multiplier: CGFloat) -> Layout { return resetLastConstraint(multiplier: multiplier) } /** Sets priority of the last created constraint. Not meant for updating the multiplier as it will re-create the constraint. - Parameter _ value: A Float priority. - Returns: A Layout instance to allow chaining. */ @discardableResult func priority(_ value: Float) -> Layout { return priority(.init(rawValue: value)) } /** Sets priority of the last created constraint. Not meant for updating the priority as it will re-create the constraint. - Parameter _ priority: A UILayoutPriority. - Returns: A Layout instance to allow chaining. */ @discardableResult func priority(_ priority: UILayoutPriority) -> Layout { return resetLastConstraint(priority: priority) } /** Removes the last created constraint and creates new one with the new multiplier and/or priority (if provided). - Parameter multiplier: An optional CGFloat. - Parameter priority: An optional UILayoutPriority. - Returns: A Layout instance to allow chaining. */ private func resetLastConstraint(multiplier: CGFloat? = nil, priority: UILayoutPriority? = nil) -> Layout { guard let v = view?.lastConstraint, v.isActive else { return self } v.isActive = false let newV = NSLayoutConstraint(item: v.firstItem as Any, attribute: v.firstAttribute, relatedBy: v.relation, toItem: v.secondItem, attribute: v.secondAttribute, multiplier: multiplier ?? v.multiplier, constant: v.constant) newV.priority = priority ?? v.priority newV.isActive = true view?.lastConstraint = newV return self } } public extension Layout { /** Constraints top of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func top(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, relationer: relationer, constant: offset) } /** Constraints left of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func left(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, relationer: relationer, constant: offset) } /** Constraints right of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func right(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, relationer: relationer, constant: -offset) } /** Constraints leading of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leading(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, relationer: relationer, constant: offset) } /** Constraints trailing of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailing(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, relationer: relationer, constant: -offset) } /** Constraints bottom of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottom(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, relationer: relationer, constant: -offset) } /** Constraints top-left of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeft(top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, constants: top, left) } /** Constraints top-right of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRight(top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, constants: top, -right) } /** Constraints bottom-left of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeft(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, constants: -bottom, left) } /** Constraints bottom-right of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRight(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, constants: -bottom, -right) } /** Constraints left and right of the view to its parent's. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRight(left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, constants: left, -right) } /** Constraints top-leading of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeading(top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, constants: top, leading) } /** Constraints top-trailing of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailing(top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, constants: top, -trailing) } /** Constraints bottom-leading of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeading(bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, constants: -bottom, leading) } /** Constraints bottom-trailing of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailing(bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, constants: -bottom, -trailing) } /** Constraints leading and trailing of the view to its parent's. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailing(leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, constants: leading, -trailing) } /** Constraints top and bottom of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottom(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, constants: top, -bottom) } /** Constraints center of the view to its parent's. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func center(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, constants: offsetX, offsetY) } /** Constraints horizontal center of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerX(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, relationer: relationer, constant: offset) } /** Constraints vertical center of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerY(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, relationer: relationer, constant: offset) } /** Constraints width of the view to its parent's. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, relationer: relationer, constant: offset) } /** Constraints height of the view to its parent's. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, relationer: relationer, constant: offset) } /** Constraints edges of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edges(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, constants: top, left, -bottom, -right) } } public extension Layout { /** Constraints top of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func topSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints left of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints right of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func rightSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints leading of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints trailing of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailingSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints bottom of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints top-left of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeftSafe(top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, constants: top, left, useSafeArea: true) } /** Constraints top-right of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRightSafe(top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, constants: top, -right, useSafeArea: true) } /** Constraints bottom-left of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeftSafe(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, constants: -bottom, left, useSafeArea: true) } /** Constraints bottom-right of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRightSafe(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, constants: -bottom, -right, useSafeArea: true) } /** Constraints left and right of the view to its parent's safeArea. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRightSafe(left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, constants: left, -right, useSafeArea: true) } /** Constraints top-leading of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeadingSafe(top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, constants: top, leading, useSafeArea: true) } /** Constraints top-trailing of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailingSafe(top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, constants: top, -trailing, useSafeArea: true) } /** Constraints bottom-leading of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeadingSafe(bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, constants: -bottom, leading, useSafeArea: true) } /** Constraints bottom-trailing of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailingSafe(bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, constants: -bottom, -trailing, useSafeArea: true) } /** Constraints leading and trailing of the view to its parent's safeArea. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailingSafe(leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, constants: leading, -trailing, useSafeArea: true) } /** Constraints top and bottom of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottomSafe(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, constants: top, -bottom, useSafeArea: true) } /** Constraints center of the view to its parent's safeArea. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerSafe(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, constants: offsetX, offsetY, useSafeArea: true) } /** Constraints horizontal center of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerXSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints vertical center of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerYSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints width of the view to its parent's safeArea. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func widthSafe(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints height of the view to its parent's safeArea. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func heightSafe(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints edges of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edgesSafe(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, constants: top, left, -bottom, -right, useSafeArea: true) } } public extension Layout { /** Constraints width of the view to a constant value. - Parameter _ width: A CGFloat value. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(_ width: CGFloat, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.constantWidth, relationer: relationer, constants: width) } /** Constraints height of the view to a constant value. - Parameter _ height: A CGFloat value. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(_ height: CGFloat, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.constantHeight, relationer: relationer, constants: height) } /** The width and height of the view to its parent's. - Parameter _ size: A CGSize offset. - Returns: A Layout instance to allow chaining. */ @discardableResult func size(_ size: CGSize) -> Layout { return width(size.width).height(size.height) } } public extension Layout { /** Constraints top of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func top(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, to: anchor, relationer: relationer, constant: offset) } /** Constraints left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func left(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, to: anchor, relationer: relationer, constant: offset) } /** Constraints right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func right(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, to: anchor, relationer: relationer, constant: -offset) } /** Constraints leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leading(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, to: anchor, relationer: relationer, constant: offset) } /** Constraints trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailing(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, to: anchor, relationer: relationer, constant: -offset) } /** Constraints bottom of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottom(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, to: anchor, relationer: relationer, constant: -offset) } /** Constraints top-leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeading(_ anchor: LayoutAnchorable, top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, to: anchor, constants: top, leading) } /** Constraints top-trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailing(_ anchor: LayoutAnchorable, top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, to: anchor, constants: top, -trailing) } /** Constraints bottom-leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeading(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, to: anchor, constants: -bottom, leading) } /** Constraints bottom-trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailing(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, to: anchor, constants: -bottom, -trailing) } /** Constraints leading and trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailing(_ anchor: LayoutAnchorable, leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, to: anchor, constants: leading, -trailing) } /** Constraints top-left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeft(_ anchor: LayoutAnchorable, top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, to: anchor, constants: top, left) } /** Constraints top-right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRight(_ anchor: LayoutAnchorable, top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, to: anchor, constants: top, -right) } /** Constraints bottom-left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeft(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, to: anchor, constants: -bottom, left) } /** Constraints bottom-right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRight(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, to: anchor, constants: -bottom, -right) } /** Constraints left and right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRight(_ anchor: LayoutAnchorable, left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, to: anchor, constants: left, -right) } /** Constraints top and bottom of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottom(_ anchor: LayoutAnchorable, top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, to: anchor, constants: top, -bottom) } /** Constraints center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func center(_ anchor: LayoutAnchorable, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, to: anchor, constants: offsetX, offsetY) } /** Constraints horizontal center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerX(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, to: anchor, relationer: relationer, constant: offset) } /** Constraints vertical center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerY(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, to: anchor, relationer: relationer, constant: offset) } /** Constraints width of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, to: anchor, relationer: relationer, constant: offset) } /** Constraints height of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, to: anchor, relationer: relationer, constant: offset) } /** Constraints edges of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edges(_ anchor: LayoutAnchorable, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, to: anchor, constants: top, left, -bottom, -right) } } public extension Layout { /** Constraints the object and sets it's anchor to `bottom`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for top. - Returns: A Layout instance to allow chaining. */ @discardableResult func below(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return top(view.anchor.bottom, offset) } /** Constraints the object and sets it's anchor to `top`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func above(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return bottom(view.anchor.top, offset) } /** Constraints the object and sets it's anchor to `before/left`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func before(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return right(view.anchor.left, offset) } /** Constraints the object and sets it's anchor to `after/right`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func after(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return left(view.anchor.right, offset) } /** Constraints the object and sets it's aspect. - Parameter ratio: A CGFloat ratio multiplier. - Returns: A Layout instance to allow chaining. */ @discardableResult func aspect(_ ratio: CGFloat = 1) -> Layout { return height(view!.anchor.width).multiply(ratio) } } private extension Layout { /** Constraints the view to its parent according to the provided attribute. If the constraint already exists, will update its constant. - Parameter _ attribute: A LayoutAttribute. - Parameter _ relationer: A LayoutRelationer. - Parameter constant: A CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attribute: LayoutAttribute, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constant: CGFloat, useSafeArea: Bool = false) -> Layout { return constraint([attribute], relationer: relationer, constants: constant, useSafeArea: useSafeArea) } /** Constraints the view to its parent according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter _ relationer: A LayoutRelationer. - Parameter constants: A list of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], relationer: LayoutRelationer = LayoutRelationerStruct.equal, constants: CGFloat..., useSafeArea: Bool = false) -> Layout { var attributes = attributes var anchor: LayoutAnchor! if attributes == .constantHeight || attributes == .constantWidth { attributes.removeLast() anchor = LayoutAnchor(constraintable: nil, attributes: [.notAnAttribute]) } else { guard parent != nil else { fatalError("[Material Error: Constraint requires view to have parent.") } anchor = LayoutAnchor(constraintable: useSafeArea ? parent?.safeAnchor.constraintable : parent, attributes: attributes) } return constraint(attributes, to: anchor, relationer: relationer, constants: constants) } /** Constraints the view to the given anchor according to the provided attribute. If the constraint already exists, will update its constant. - Parameter _ attribute: A LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constant: A CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attribute: LayoutAttribute, to anchor: LayoutAnchorable, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constant: CGFloat) -> Layout { return constraint([attribute], to: anchor, relationer: relationer, constants: constant) } /** Constraints the view to the given anchor according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constants: A list of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], to anchor: LayoutAnchorable, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constants: CGFloat...) -> Layout { return constraint(attributes, to: anchor, relationer: relationer, constants: constants) } /** Constraints the view to the given anchor according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constants: An array of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], to anchor: LayoutAnchorable, relationer: LayoutRelationer, constants: [CGFloat]) -> Layout { let from = LayoutAnchor(constraintable: constraintable, attributes: attributes) var to = anchor as? LayoutAnchor if to?.attributes.isEmpty ?? true { let v = (anchor as? UIView) ?? (anchor as? LayoutAnchor)?.constraintable to = LayoutAnchor(constraintable: v, attributes: attributes) } let constraint = LayoutConstraint(fromAnchor: from, toAnchor: to!, relation: relationer(.nil, .nil), constants: constants) let constraints = (view?.constraints ?? []) + (view?.superview?.constraints ?? []) let newConstraints = constraint.constraints for newConstraint in newConstraints { guard let activeConstraint = constraints.first(where: { $0.equalTo(newConstraint) }) else { newConstraint.isActive = true view?.lastConstraint = newConstraint continue } activeConstraint.constant = newConstraint.constant } return self } } /// A closure typealias for relation operators. public typealias LayoutRelationer = (LayoutRelationerStruct, LayoutRelationerStruct) -> LayoutRelation /// A dummy struct used in creating relation operators (==, >=, <=). public struct LayoutRelationerStruct { /// Passed as an unused argument to the LayoutRelationer closures. static let `nil` = LayoutRelationerStruct() /** A method used as a default parameter for LayoutRelationer closures. Swift does not allow using == operator directly, so we had to create this. */ public static func equal(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .equal } } /// A method returning `LayoutRelation.equal` public func ==(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .equal } /// A method returning `LayoutRelation.greaterThanOrEqual` public func >=(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .greaterThanOrEqual } /// A method returning `LayoutRelation.lessThanOrEqual` public func <=(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .lessThanOrEqual }
mit
25a6299d31cba8634b06763a845f3de9
36.714521
175
0.70256
4.492825
false
false
false
false
evering7/iSpeak8
Pods/FeedKit/Sources/FeedKit/Models/RSS/RSSFeedCategory.swift
2
2748
// // RSSFeedCategory.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// The category of `<channel>`. Identifies a category or tag to which the feed /// belongs. public class RSSFeedCategory { /// The element's attributes. public class Attributes { /// A string that identifies a categorization taxonomy. It's an optional /// attribute of `<category>`. e.g. "http://www.fool.com/cusips" public var domain: String? } /// The element's attributes. public var attributes: Attributes? /// The element's value. public var value: String? } // MARK: - Initializers extension RSSFeedCategory { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = RSSFeedCategory.Attributes(attributes: attributeDict) } } extension RSSFeedCategory.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.domain = attributeDict["domain"] } } // MARK: - Equatable extension RSSFeedCategory: Equatable { public static func ==(lhs: RSSFeedCategory, rhs: RSSFeedCategory) -> Bool { return lhs.value == rhs.value && lhs.attributes == rhs.attributes } } extension RSSFeedCategory.Attributes: Equatable { public static func ==(lhs: RSSFeedCategory.Attributes, rhs: RSSFeedCategory.Attributes) -> Bool { return lhs.domain == rhs.domain } }
mit
b6603ebb68669479cb192ce0163e4cef
28.548387
101
0.667031
4.610738
false
false
false
false
swiftde/24-IBInspectable-IBDesignable
OwnView-Tutorial/OwnView-Tutorial/MyView.swift
2
758
// // MyView.swift // OwnView-Tutorial // // Created by Benjamin Herzog on 05.08.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit @IBDesignable class MyView: UIView { @IBInspectable var borderWidth: CGFloat = 10 { didSet{ layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor = UIColor.blackColor() { didSet{ layer.borderColor = borderColor.CGColor } } @IBInspectable var backColor: UIColor = UIColor.redColor() { didSet{ backgroundColor = backColor } } @IBInspectable var cornerRadius: CGFloat = 20 { didSet{ layer.cornerRadius = cornerRadius } } }
gpl-2.0
52849f87b44c73c4cfcb41b0e86c717a
21.969697
68
0.594987
4.708075
false
false
false
false
mmisesin/particle
Particle/Constants.swift
1
647
// // Constants.swift // Particle // // Created by Artem Misesin on 11/1/17. // Copyright © 2017 Artem Misesin. All rights reserved. // import Foundation public struct Constants { static let unknownErrorDescription = NSLocalizedString("Unknown error", comment: "") static let unknownTitle = NSLocalizedString("Unknown title", comment: "") static let unknownLink = NSLocalizedString("Unknown link", comment: "") static let emptyStateReader = NSLocalizedString("No pudo encontrar el contenido del artículo", comment: "") static let emptyStateReaderButton = NSLocalizedString("Remove the record", comment: "") }
mit
affa27c2fd786d4bf19d1343e00edf9e
32.947368
111
0.72093
4.51049
false
false
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/HttpProtocol.swift
1
1418
// // HttpProtocol.swift // Pods // // Created by Ye David on 3/2/17. // // import Foundation public typealias ResponseData = [String:AnyObject] public typealias RequestData = [String:AnyObject] public typealias PathParamsData = [(String,String)] open class HttpProtocol { public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PATCH = "PATCH" case DELETE = "DELETE" } public struct AuthorizationKeys { public static let appIdKey: String = "appId" public static let secretKey: String = "secret" public static let loginTokenKey: String = "loginToken" } public struct HTTPMethods { public static let Get: String = "GET" public static let Delete: String = "DELETE" } public struct HeaderFieldValues { public static let applicationJson: String = "application/json" } public struct HeaderFieldNames { public static let contentType: String = "Content-Type" public static let accept: String = "Accept" public static let authorization: String = "Authorization" } public static func authorizationKeys() -> [String] { return [AuthorizationKeys.appIdKey, AuthorizationKeys.secretKey] } public static func nonPayloadHttpMethods() -> [HTTPMethod] { return [HTTPMethod.DELETE, HTTPMethod.GET] } }
mit
f17404f5626c93f61a80fc09dc96ef8a
26.269231
72
0.646685
4.633987
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaLinkSocketCommandItem.swift
1
3267
import Foundation extension MVitaLinkSocketCommand { //MARK: internal func requestItemStatus( event:MVitaPtpMessageInEvent) { let message:MVitaPtpMessageOutEventCommand = MVitaPtpMessageOutEventCommand( event:event, dataPhase:MVitaPtpDataPhase.request, command:MVitaPtpCommand.requestItemStatus) writeMessageAndRead(message:message) } func requestItemsFilters( event:MVitaPtpMessageInEvent) { let message:MVitaPtpMessageOutEventCommand = MVitaPtpMessageOutEventCommand( event:event, dataPhase:MVitaPtpDataPhase.request, command:MVitaPtpCommand.requestItemsFilters) writeMessageAndRead(message:message) } func requestItemTreat( event:MVitaPtpMessageInEvent) { let message:MVitaPtpMessageOutEventCommand = MVitaPtpMessageOutEventCommand( event:event, dataPhase:MVitaPtpDataPhase.request, command:MVitaPtpCommand.requestItemTreat) writeMessageAndRead(message:message) } func requestItemFormat( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItemProperty = MVitaPtpMessageOutRequestItemProperty( treatId:treatId, property:MVitaPtpItemProperty.format) writeMessageAndRead(message:message) } func requestItemFileName( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItemProperty = MVitaPtpMessageOutRequestItemProperty( treatId:treatId, property:MVitaPtpItemProperty.fileName) writeMessageAndRead(message:message) } func requestItemDateCreated( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItemProperty = MVitaPtpMessageOutRequestItemProperty( treatId:treatId, property:MVitaPtpItemProperty.dateCreated) writeMessageAndRead(message:message) } func requestItemDateModified( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItemProperty = MVitaPtpMessageOutRequestItemProperty( treatId:treatId, property:MVitaPtpItemProperty.dateModified) writeMessageAndRead(message:message) } func requestItemElements( treatId:UInt32) { guard let storageId:UInt32 = model?.configuration.storage.storageId else { return } let message:MVitaPtpMessageOutRequestItemElements = MVitaPtpMessageOutRequestItemElements( treatId:treatId, storageId:storageId) writeMessageAndRead(message:message) } func requestItemFileSize( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItemProperty = MVitaPtpMessageOutRequestItemProperty( treatId:treatId, property:MVitaPtpItemProperty.fileSize) writeMessageAndRead(message:message) } func requestItemData( treatId:UInt32) { let message:MVitaPtpMessageOutRequestItem = MVitaPtpMessageOutRequestItem( treatId:treatId) writeMessageAndRead(message:message) } }
mit
110bf4c0b913c5a6c9bd4deb2caf2531
29.53271
98
0.668503
4.426829
false
false
false
false
benjaminsnorris/DateChooser
DateChooser/DateChooserCapabilities.swift
1
1035
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import Foundation public struct DateChooserCapabilities: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let setToCurrent = DateChooserCapabilities(rawValue: 1) public static let removeDate = DateChooserCapabilities(rawValue: 2) public static let dateAndTimeSeparate = DateChooserCapabilities(rawValue: 4) public static let dateAndTimeCombined = DateChooserCapabilities(rawValue: 8) public static let dateOnly = DateChooserCapabilities(rawValue: 16) public static let timeOnly = DateChooserCapabilities(rawValue: 32) public static let countdown = DateChooserCapabilities(rawValue: 64) public static let cancel = DateChooserCapabilities(rawValue: 128) public static let standard: DateChooserCapabilities = [.setToCurrent, .removeDate, .dateAndTimeSeparate] }
mit
5b19ce2d5a45c32a59b143b3e43022cb
33.655172
108
0.676617
4.427313
false
false
false
false
sadawi/PrimarySource
Pod/OSX/Cocoa+CollectionPresenter.swift
1
3184
// // Cocoa+CollectionPresenter.swift // Pods // // Created by Sam Williams on 5/27/16. // // import Foundation import Cocoa extension NSTableView: CollectionPresenter { } extension NSOutlineView: ColumnReloadableCollectionPresenter { public func reloadItem(_ item: Any?, columnIdentifiers: [String], reloadChildren: Bool = false) { if let item = item { let row = self.row(forItem: item) let rowIndexes = IndexSet(integer: row) for identifier in columnIdentifiers { let column = self.column(withIdentifier: identifier) let columnIndexes = IndexSet(integer: column) self.reloadData(forRowIndexes: rowIndexes, columnIndexes: columnIndexes) } if reloadChildren { // self.reloadData() // TODO: which? self.reloadItem(item, reloadChildren: true) } } } } extension NSOutlineView: ExpandableCollectionPresenter { // Already implements the methods } protocol ColumnSpannable { } protocol OutlineViewDataSource: NSOutlineViewDataSource { func outlineView(_ outlineView: NSOutlineView, columnSpanForItem item: AnyObject, column: NSTableColumn) -> Int } @IBDesignable open class OutlineView: NSOutlineView, ColumnSpannable { var outlineViewDataSource: OutlineViewDataSource? { return self.dataSource as? OutlineViewDataSource } @IBInspectable var hidesOutlineTriangles: Bool = false let kOutlineColumnWidth:CGFloat = 11 // TODO: don't hardcode override open func frameOfOutlineCell(atRow row: Int) -> NSRect { if self.hidesOutlineTriangles { return NSRect.zero } else { return super.frameOfOutlineCell(atRow: row) } } override open func frameOfCell(atColumn column: Int, row: Int) -> NSRect { var superFrame = super.frameOfCell(atColumn: column, row: row) let tableColumn = self.tableColumns[column] // let indent = self.indentationPerLevel if self.hidesOutlineTriangles { if tableColumn === self.outlineTableColumn { superFrame = NSRect(x: superFrame.origin.x - kOutlineColumnWidth, y: superFrame.origin.y, width: superFrame.size.width + kOutlineColumnWidth, height: superFrame.size.height) } } guard let dataSource = self.outlineViewDataSource else { return superFrame } guard let item = self.item(atRow: row) else { return superFrame } let colspan = dataSource.outlineView(self, columnSpanForItem: item as AnyObject, column: tableColumn) if colspan == 1 { return superFrame } else if colspan > 1 && colspan <= self.numberOfColumns { var mergedFrames = superFrame for i in 0..<colspan { let nextFrame = super.frameOfCell(atColumn: column + i, row: row) mergedFrames = NSUnionRect(mergedFrames, nextFrame) } return mergedFrames } return superFrame } }
mit
2d6b232dd83638d1de0511a2b6431f82
32.166667
189
0.626884
4.967239
false
false
false
false
mortenjust/androidtool-mac
AndroidTool/MasterViewController.swift
1
4750
// // MasterViewController.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Cocoa // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class MasterViewController: NSViewController, DeviceDiscovererDelegate, NSTableViewDelegate, NSTableViewDataSource { var discoverer = DeviceDiscoverer() var devices : [Device]! var deviceVCs = [DeviceViewController]() var window : NSWindow! var previousSig:Double = 0 @IBOutlet var emptyStateView: NSImageView! @IBOutlet weak var devicesTable: NSTableView! override func awakeFromNib() { discoverer.delegate = self devices = [Device]() discoverer.start() } func installApk(_ apkPath:String){ showDevicePicker(apkPath) } func showDevicePicker(_ apkPath:String){ let devicePickerVC = DevicePickerViewController(nibName: "DevicePickerViewController", bundle: nil) devicePickerVC?.devices = devices devicePickerVC?.apkPath = apkPath if #available(OSX 10.10, *) { self.presentViewControllerAsSheet(devicePickerVC!) } else { // Fallback on earlier versions } } func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return false } func numberOfRows(in tableView: NSTableView) -> Int { // println("asked number of rows") if devices == nil { return 0 } return devices.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let deviceVC = DeviceViewController(device: devices[row]) deviceVCs.append(deviceVC!) // save it from deallocation return deviceVC?.view } func removeDevice(_ device:Device){ } func fingerPrintForDeviceList(_ deviceList:[Device]) -> Double { var total:Double = 0 for d in deviceList { total += d.firstBoot! } total = total/Double(deviceList.count) return total } func deviceListSignature(_ deviceList:[Device]) -> Double { var total:Double = 0 for device in deviceList { if let firstboot = device.firstBoot { total += firstboot } } let signa = total/Double(deviceList.count) return signa } func showEmptyState(){ // resize window if !emptyStateView.isDescendant(of: view) { emptyStateView.frame.origin.y = -15 emptyStateView.frame.origin.x = 45 view.addSubview(emptyStateView) } } func removeEmptyState(){ emptyStateView.removeFromSuperview() } func devicesUpdated(_ deviceList: [Device]) { let newSig = deviceListSignature(deviceList) if deviceList.count == 0 { previousSig=0 devicesTable.reloadData() showEmptyState() } else { removeEmptyState() } devices = deviceList devices.sort(by: {$0.model < $1.model}) // refresh each device with updated data like current activity // for deviceVC in deviceVCs { // for device in devices { // if deviceVC.device.adbIdentifier == device.adbIdentifier { // deviceVC.device = device // deviceVC.setStatusToCurrentActivity() // } // } // } // make sure we don't refresh the tableview when it's not necessary if newSig != previousSig { devicesTable.reloadData() var newHeight=Util().deviceHeight // adjust window height accordingly if devices.count != 0 { newHeight = CGFloat(devices.count) * (Util().deviceHeight) + 20 } else { newHeight = 171 // emptystate height } Util().changeWindowHeight(window, view: self.view, newHeight: newHeight) previousSig = newSig } } override func viewDidLoad() { if #available(OSX 10.10, *) { super.viewDidLoad() } else { // Fallback on earlier versions } } }
apache-2.0
6c5fe9adf87985cffaf253e0f29df774
27.106509
117
0.575789
5.015839
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_enum.swift
1
11859
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z0-9_]+]]CyAA6EitherACLLOySiGGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-apple-SAME: %objc_class*, // CHECK-unknown-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: i8*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: }> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA6EitherACLLOySiGGMM // CHECK-unknown-SAME: [[INT]] 0, // CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject // CHECK-unknown-SAME: %swift.type* null, // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_2:[a-zA-Z0-9_]+]]5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(25|13)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(120|72)}}, // CHECK-unknown-SAME: i32 96, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : i32, // : %swift.method_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" to %swift.type_descriptor* // : ), // CHECK-SAME: i8* null, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main6Either[[UNIQUE_ID_1]]OySiGMf" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] // CHECK: @"$s4main6Either[[UNIQUE_ID_1]]OySiGMf" = fileprivate class Value<First> { let first_Value: First init(first: First) { self.first_Value = first } } fileprivate enum Either<Value> { case left(Value) case right(Int) } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]CyAA6EitherACLLOySiGGMb"([[INT]] 0) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Value(first: Either.left(13)) ) } doit() // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast ( // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main6Either[[UNIQUE_ID_1]]OySiGMf" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) to i8* // CHECK-SAME: ), // CHECK-SAME: [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_3:[0-9A-Z_]+]]CyAA6EitherACLLOySiGGMb"([[INT]] [[METADATA_REQUEST]]) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0 // CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1 // CHECK: ret %swift.metadata_response [[RESULT_METADATA]] // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK: [[INT]] [[METADATA_REQUEST]], // CHECK: i8* [[ERASED_TYPE]], // CHECK: i8* undef, // CHECK: i8* undef, // CHECK: %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* // CHECK: $s4main5Value[[UNIQUE_ID_1]]CMn // CHECK: to %swift.type_descriptor* // CHECK: ) // CHECK: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA6EitherACLLOySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK: entry: // CHECK-unknown: ret // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value[ // : [ // : UNIQUE_ID_1 // : ] // : ]C* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : [[INT]], // : %T4main5Value[ // : [ // : UNIQUE_ID_1 // : ] // : ]C* ( // : %swift.opaque*, // : %swift.type* // : )* // : }>* // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CyAA6EitherACLLOySiGGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type* // CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0 // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: }
apache-2.0
0942476a7fd173acc79235c3982482a1
42.599265
214
0.448604
3.249931
false
false
false
false
stephentyrone/swift
validation-test/Reflection/reflect_existential.swift
3
8056
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_existential // RUN: %target-codesign %t/reflect_existential // RUN: %target-run %target-swift-reflection-test %t/reflect_existential | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest class TestGeneric<T> { var t: T init(_ t: T) { self.t = t } } protocol P {} protocol CP : class {} class C : CP {} class D : C, P {} reflect(object: TestGeneric(D() as Any)) // CHECK-64: Type reference: // CHECK-64: (bound_generic_class reflect_existential.TestGeneric // CHECK-64: (protocol_composition)) // CHECK-64: Type info: // CHECK-64: (class_instance size=48 alignment=8 stride=48 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 bitwise_takable=1))))) // CHECK-32: Type reference: // CHECK-32: (bound_generic_class reflect_existential.TestGeneric // CHECK-32: (protocol_composition)) // CHECK-32: Type info: // CHECK-32: (class_instance size=24 alignment=4 stride=24 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))) reflect(object: TestGeneric(D() as P)) // CHECK-64: Type reference: // CHECK-64: (bound_generic_class reflect_existential.TestGeneric // CHECK-64: (protocol_composition // CHECK-64: (protocol reflect_existential.P))) // CHECK-64: Type info: // CHECK-64: (class_instance size=56 alignment=8 stride=56 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 bitwise_takable=1)) // CHECK-64: (field name=wtable offset=32 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: Type reference: // CHECK-32: (bound_generic_class reflect_existential.TestGeneric // CHECK-32: (protocol_composition // CHECK-32: (protocol reflect_existential.P))) // CHECK-32: Type info: // CHECK-32: (class_instance size=28 alignment=4 stride=28 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32: (field name=wtable offset=16 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) reflect(object: TestGeneric(D() as (P & AnyObject))) // CHECK-64: Type reference: // CHECK-64: (bound_generic_class reflect_existential.TestGeneric // CHECK-64: (protocol_composition any_object // CHECK-64: (protocol reflect_existential.P))) // CHECK-64: Type info: // CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=object offset=0 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=wtable offset=8 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: Type reference: // CHECK-32: (bound_generic_class reflect_existential.TestGeneric // CHECK-32: (protocol_composition any_object // CHECK-32: (protocol reflect_existential.P))) // CHECK-32: Type info: // CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=object offset=0 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=wtable offset=4 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) reflect(object: TestGeneric(D() as CP)) // CHECK-64: Type reference: // CHECK-64: (bound_generic_class reflect_existential.TestGeneric // CHECK-64: (protocol_composition any_object // CHECK-64: (protocol reflect_existential.CP))) // CHECK-64: Type info: // CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=object offset=0 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=wtable offset=8 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: Type reference: // CHECK-32: (bound_generic_class reflect_existential.TestGeneric // CHECK-32: (protocol_composition any_object // CHECK-32: (protocol reflect_existential.CP))) // CHECK-32: Type info: // CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=object offset=0 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=wtable offset=4 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) reflect(object: TestGeneric(D() as (C & P))) // CHECK-64: Type reference: // CHECK-64: (bound_generic_class reflect_existential.TestGeneric // CHECK-64: (protocol_composition any_object // CHECK-64: (class reflect_existential.C) // CHECK-64: (protocol reflect_existential.P))) // CHECK-64: Type info: // CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1 // CHECK-64: (field name=object offset=0 // CHECK-64: (reference kind=strong refcounting=native)) // CHECK-64: (field name=wtable offset=8 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: Type reference: // CHECK-32: (bound_generic_class reflect_existential.TestGeneric // CHECK-32: (protocol_composition any_object // CHECK-32: (class reflect_existential.C) // CHECK-32: (protocol reflect_existential.P))) // CHECK-32: Type info: // CHECK-32: (class_instance size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=object offset=0 // CHECK-32: (reference kind=strong refcounting=native)) // CHECK-32: (field name=wtable offset=4 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
62d4ddc19717c7133e92fd942231b361
44.772727
125
0.705313
3.29354
false
true
false
false
netcosports/Gnomon
Sources/JSON/JSONModel.swift
1
1501
// // Created by Vladimir Burdukov on 08/23/17. // Copyright © 2017 NetcoSports. All rights reserved. // import Foundation import SwiftyJSON #if SWIFT_PACKAGE import Gnomon #endif extension JSON { func xpath(_ path: String) throws -> JSON { guard path.count > 0 else { throw "empty xpath" } let components = path.components(separatedBy: "/") guard components.count > 0 else { return self } return try xpath(components) } private func xpath(_ components: [String]) throws -> JSON { guard let key = components.first else { return self } let value = self[key] guard value.exists() else { throw "can't find key \(key) in json \(self)" } return try value.xpath(Array(components.dropFirst())) } } public protocol JSONModel: BaseModel where DataContainer == JSON { } extension JSON: DataContainerProtocol { public typealias Iterator = GenericDataContainerIterator<JSON> public static func container(with data: Data, at path: String?) throws -> JSON { let json = try JSON(data: data) if let path = path { let xpathed = try json.xpath(path) if let error = xpathed.error { throw Gnomon.Error.unableToParseModel(error) } return xpathed } else { return json } } public func multiple() -> GenericDataContainerIterator<JSON>? { if let array = array { return .init(array) } else { return nil } } public static func empty() -> JSON { return JSON() } }
mit
c1403359620660df519d187619ccd32a
21.727273
82
0.652
3.989362
false
false
false
false
tomaz/MassiveViewController
MVVM/MVVMAfter/MVVMAfter/FolderViewModel.swift
1
2476
import UIKit private var FolderNameDidChangeContext = 0 private var FolderSizeDidChangeContext = 0 /** Wrapper view model for FolderData. This view model implements the following convenience functions/properties: Events: - nameDidChange: block that gets called whenever underlying folder name changes - sizeDidChange: block that gets called whenever underlying folder size changes - nameOrSizeDidChange: block that gets called when either name or size changes Convenience properties: - sizeInKB: calculates folder size in KB - nameAndSizeDescription: this is commonly used in our controllers, so now they can conveniently just use this property We could get more creative. For example, we're blindly setting up KVO, but we could do it dynamically, depending on observation blocks client actually subscribe to. */ class FolderViewModel: NSObject { init(folder: FolderData) { // Assign folder we're handling. self.folder = folder // Let super class initiale super.init() // Setup KVO. self.folder.addObserver(self, forKeyPath: "name", options: nil, context: &FolderNameDidChangeContext) self.folder.addObserver(self, forKeyPath: "size", options: nil, context: &FolderSizeDidChangeContext) } deinit { // Remove observer when deallocating. self.folder.removeObserver(self, forKeyPath: "name") self.folder.removeObserver(self, forKeyPath: "size") } // MARK: - Overriden methods override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if context == &FolderNameDidChangeContext { println("FolderViewModel: folder name changed, notifying observer") self.nameDidChange?(name: self.folder.name) self.nameOrSizeDidChange?() } else if context == &FolderSizeDidChangeContext { println("FolderViewModel: folder size changed, notifying observer") self.sizeDidChange?(size: self.folder.size) self.nameOrSizeDidChange?() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } // MARK: - Derived properties var sizeInKB: Int { return self.folder.size / 1024 } var nameAndSizeDescription: String { return "\(self.folder.name) (\(self.sizeInKB) KB)" } // MARK: - Properties private (set) internal var folder: FolderData var nameDidChange: ((name: String) -> ())? var sizeDidChange: ((size: Int) -> ())? var nameOrSizeDidChange: dispatch_block_t? }
mit
1aef7cf86343f872f5fb2d238a9e3820
31.578947
164
0.752423
4.006472
false
false
false
false
kwkhaw/Layer-Parse-iOS-Swift-Example
Code/AppDelegate.swift
1
8827
import UIKit import Parse import Atlas import SVProgressHUD @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var layerClient: LYRClient! var controller: ViewController! // MARK TODO: Before first launch, update LayerAppIDString, ParseAppIDString or ParseClientKeyString values // TODO:If LayerAppIDString, ParseAppIDString or ParseClientKeyString are not set, this app will crash" let LayerAppIDString: NSURL! = NSURL(string: "layer:///apps/staging/5e594efe-ded1-11e4-8ee4-e3d900000e81") let ParseAppIDString: String = "9us9WVAOeboE3QSgRuXPwe0enLGgnaBGxoqNsL6R" let ParseClientKeyString: String = "pc0AD9flDK8XTlFuktkBmNQuCE0L3xr90i48vCtv" //Please note, You must set `LYRConversation *conversation` as a property of the ViewController. var conversation: LYRConversation! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { setupParse() setupLayer() // Show View Controller controller = ViewController() controller.layerClient = layerClient // Register for push self.registerApplicationForPushNotifications(application) self.window!.rootViewController = UINavigationController(rootViewController: controller) self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK:- Push Notification Registration func registerApplicationForPushNotifications(application: UIApplication) { // Set up push notifications // For more information about Push, check out: // https://developer.layer.com/docs/guides/ios#push-notification // Register device for iOS8 let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil) application.registerUserNotificationSettings(notificationSettings) application.registerForRemoteNotifications() } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // Store the deviceToken in the current installation and save it to Parse. let currentInstallation: PFInstallation = PFInstallation.currentInstallation() currentInstallation.setDeviceTokenFromData(deviceToken) currentInstallation.saveInBackground() // Send device token to Layer so Layer can send pushes to this device. // For more information about Push, check out: // https://developer.layer.com/docs/ios/guides#push-notification assert(self.layerClient != nil, "The Layer client has not been initialized!") do { try self.layerClient.updateRemoteNotificationDeviceToken(deviceToken) print("Application did register for remote notifications: \(deviceToken)") } catch let error as NSError { print("Failed updating device token with error: \(error)") } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { if userInfo["layer"] == nil { PFPush.handlePush(userInfo) completionHandler(UIBackgroundFetchResult.NewData) return } let userTappedRemoteNotification: Bool = application.applicationState == UIApplicationState.Inactive var conversation: LYRConversation? = nil if userTappedRemoteNotification { SVProgressHUD.show() conversation = self.conversationFromRemoteNotification(userInfo) if conversation != nil { self.navigateToViewForConversation(conversation!) } } let success: Bool = self.layerClient.synchronizeWithRemoteNotification(userInfo, completion: { (changes, error) in completionHandler(self.getBackgroundFetchResult(changes, error: error)) if userTappedRemoteNotification && conversation == nil { // Try navigating once the synchronization completed self.navigateToViewForConversation(self.conversationFromRemoteNotification(userInfo)) } }) if !success { // This should not happen? completionHandler(UIBackgroundFetchResult.NoData) } } func getBackgroundFetchResult(changes: [AnyObject]!, error: NSError!) -> UIBackgroundFetchResult { if changes?.count > 0 { return UIBackgroundFetchResult.NewData } return error != nil ? UIBackgroundFetchResult.Failed : UIBackgroundFetchResult.NoData } func conversationFromRemoteNotification(remoteNotification: [NSObject : AnyObject]) -> LYRConversation { let layerMap = remoteNotification["layer"] as! [String: String] let conversationIdentifier = NSURL(string: layerMap["conversation_identifier"]!) return self.existingConversationForIdentifier(conversationIdentifier!)! } func navigateToViewForConversation(conversation: LYRConversation) { if self.controller.conversationListViewController != nil { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { SVProgressHUD.dismiss() if (self.controller.navigationController!.topViewController as? ConversationViewController)?.conversation != conversation { self.controller.conversationListViewController.presentConversation(conversation) } }); } else { SVProgressHUD.dismiss() } } func existingConversationForIdentifier(identifier: NSURL) -> LYRConversation? { let query: LYRQuery = LYRQuery(queryableClass: LYRConversation.self) query.predicate = LYRPredicate(property: "identifier", predicateOperator: LYRPredicateOperator.IsEqualTo, value: identifier) query.limit = 1 do { return try self.layerClient.executeQuery(query).firstObject as? LYRConversation } catch { // This should never happen? return nil } } func setupParse() { // Enable Parse local data store for user persistence Parse.enableLocalDatastore() Parse.setApplicationId(ParseAppIDString, clientKey: ParseClientKeyString) // Set default ACLs let defaultACL: PFACL = PFACL() defaultACL.setPublicReadAccess(true) PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true) } func setupLayer() { layerClient = LYRClient(appID: LayerAppIDString) layerClient.autodownloadMIMETypes = NSSet(objects: ATLMIMETypeImagePNG, ATLMIMETypeImageJPEG, ATLMIMETypeImageJPEGPreview, ATLMIMETypeImageGIF, ATLMIMETypeImageGIFPreview, ATLMIMETypeLocation) as? Set<String> } }
apache-2.0
8e5ade89122066d525aff4aa4602188e
48.589888
285
0.711
5.672879
false
false
false
false
Blackjacx/SwiftTrace
Sources/Color.swift
1
3180
// // Color.swift // SwiftTrace // // Created by Stefan Herold on 13/08/16. // // public struct Color: Equatable, JSONSerializable, CustomStringConvertible { public var red: Double = 0.0 public var green: Double = 0.0 public var blue: Double = 0.0 public var description: String { return "\(red) \(green) \(blue)" } /** * Returns a gray scale color */ public init(red: Double, green: Double, blue: Double) { set(red: red, green: green, blue: blue) } /** * Returns a gray scale color */ public init(gray: Double) { set(gray: gray) } /** * Returns a color from an json object */ public init(json: [String: AnyObject]) throws { guard let red = json["r"] as? Double, let green = json["g"] as? Double, let blue = json["b"] as? Double else { throw JSONError.decodingError(type(of: self), json) } self.red = red self.green = green self.blue = blue } /** * Clamps the color components between 0 and maxValue */ public mutating func clamp(maxValue: Double = 1.0) { red = min(max(0, red), maxValue) green = min(max(0, green), maxValue) blue = min(max(0, blue), maxValue) } /** * Sets all components to the same value */ public mutating func set(gray: Double) { red = gray green = gray blue = gray } /** * Sets all components to the same value */ public mutating func set(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } } /** * Returns true if two colors have the same element values. */ public func == (c1: Color, c2: Color) -> Bool { return c1.red == c2.red && c1.green == c2.green && c1.blue == c2.blue } /** * Adds c1 and c2 */ public func + (c1: Color, c2: Color) -> Color { return Color(red: c1.red + c2.red, green: c1.green + c2.green, blue: c1.blue + c2.blue) } /** * Adds c1 and c2 (self modifying) */ public func += (c1: inout Color, c2: Color) { c1 = c1 + c2 } /** * Multiply c1 and c2 component wise */ public func * (c1: Color, c2: Color) -> Color { return Color(red: c1.red * c2.red, green: c1.green * c2.green, blue: c1.blue * c2.blue) } /** * Multiply c1 and c2 component wise (self modifying) */ public func *= (c1: inout Color, c2: Color) { c1 = c1 * c2 } /** * Multiply each color component with a scalar */ public func * (c: Color, s: Double) -> Color { return Color(red: c.red * s, green: c.green * s, blue: c.blue * s) } public func * (s: Double, c: Color) -> Color { return c * s } /** * Multiply each color component with a scalar (self modifying) */ public func *= (c: inout Color, s: Double) { c = c * s } /** * Divide each color component by a scalar */ public func / (c: Color, s: Double) -> Color { return Color(red: c.red / s, green: c.green / s, blue: c.blue / s) } /** * Divide each color component by a scalar (self modifying) */ public func /= (c: inout Color, s: Double) { c = c / s }
mit
457694cb735d2cf6b371f4f2e3b61bdc
21.553191
91
0.56478
3.278351
false
false
false
false
wangyuxianglove/TestKitchen1607
Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/main(主要模块)/view/IngreLikeHeaderView.swift
1
1019
// // IngreLikeHeaderView.swift // Testkitchen1607 // // Created by qianfeng on 16/10/26. // Copyright © 2016年 zhb. All rights reserved. // import UIKit class IngreLikeHeaderView: UIView { override init(frame: CGRect) { super.init(frame: frame) //设置背景颜色 backgroundColor=UIColor(white: 0.9, alpha: 1.0) //文本输入框 let textField=UITextField(frame: CGRect(x: 40, y: 4, width: bounds.size.width-40*2, height: 36)) textField.placeholder="输入菜名或食材" textField.borderStyle = .RoundedRect addSubview(textField) //设置搜索图片 let image=UIImage(named: "search1") let imageView=UIImageView(image: image) imageView.frame=CGRectMake(0, 0, 25, 25) textField.leftView=imageView textField.leftViewMode = .Always } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ad9ffe20555b81931571716959261458
23.820513
104
0.615702
3.967213
false
false
false
false
iadmir/Signal-iOS
Signal/src/ViewControllers/InviteFlow.swift
2
10499
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import Social import ContactsUI import MessageUI @objc(OWSInviteFlow) class InviteFlow: NSObject, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate, ContactsPickerDelegate { enum Channel { case message, mail, twitter } let TAG = "[ShareActions]" let installUrl = "https://signal.org/install/" let homepageUrl = "https://signal.org" let actionSheetController: UIAlertController let presentingViewController: UIViewController let contactsManager: OWSContactsManager var channel: Channel? required init(presentingViewController: UIViewController, contactsManager: OWSContactsManager) { self.presentingViewController = presentingViewController self.contactsManager = contactsManager actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) super.init() actionSheetController.addAction(dismissAction()) if #available(iOS 9.0, *) { if let messageAction = messageAction() { actionSheetController.addAction(messageAction) } if let mailAction = mailAction() { actionSheetController.addAction(mailAction) } } if let tweetAction = tweetAction() { actionSheetController.addAction(tweetAction) } } // MARK: Twitter func canTweet() -> Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) } func tweetAction() -> UIAlertAction? { guard canTweet() else { Logger.info("\(TAG) Twitter not supported.") return nil } guard let twitterViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) else { Logger.error("\(TAG) unable to build twitter controller.") return nil } let tweetString = NSLocalizedString("SETTINGS_INVITE_TWITTER_TEXT", comment:"content of tweet when inviting via twitter") twitterViewController.setInitialText(tweetString) let tweetUrl = URL(string: installUrl) twitterViewController.add(tweetUrl) twitterViewController.add(#imageLiteral(resourceName: "twitter_sharing_image")) let tweetTitle = NSLocalizedString("SHARE_ACTION_TWEET", comment:"action sheet item") return UIAlertAction(title: tweetTitle, style: .default) { _ in Logger.debug("\(self.TAG) Chose tweet") self.presentingViewController.present(twitterViewController, animated: true, completion: nil) } } func dismissAction() -> UIAlertAction { return UIAlertAction(title: CommonStrings.dismissButton, style: .cancel) } // MARK: ContactsPickerDelegate @available(iOS 9.0, *) func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) { Logger.debug("\(TAG) didSelectContacts:\(contacts)") guard let inviteChannel = channel else { Logger.error("\(TAG) unexpected nil channel after returning from contact picker.") return } switch inviteChannel { case .message: let phoneNumbers: [String] = contacts.map { $0.userTextPhoneNumbers.first }.filter { $0 != nil }.map { $0! } dismissAndSendSMSTo(phoneNumbers: phoneNumbers) case .mail: let recipients: [String] = contacts.map { $0.emails.first }.filter { $0 != nil }.map { $0! } sendMailTo(emails: recipients) default: Logger.error("\(TAG) unexpected channel after returning from contact picker: \(inviteChannel)") } } @available(iOS 9.0, *) func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool { guard let inviteChannel = channel else { Logger.error("\(TAG) unexpected nil channel in contact picker.") return true } switch inviteChannel { case .message: return contact.userTextPhoneNumbers.count > 0 case .mail: return contact.emails.count > 0 default: Logger.error("\(TAG) unexpected channel after returning from contact picker: \(inviteChannel)") } return true } // MARK: SMS @available(iOS 9.0, *) func messageAction() -> UIAlertAction? { guard MFMessageComposeViewController.canSendText() else { Logger.info("\(TAG) Device cannot send text") return nil } let messageTitle = NSLocalizedString("SHARE_ACTION_MESSAGE", comment: "action sheet item to open native messages app") return UIAlertAction(title: messageTitle, style: .default) { _ in Logger.debug("\(self.TAG) Chose message.") self.channel = .message let picker = ContactsPicker(delegate: self, multiSelection: true, subtitleCellType: .phoneNumber) let navigationController = UINavigationController(rootViewController: picker) self.presentingViewController.present(navigationController, animated: true) } } public func dismissAndSendSMSTo(phoneNumbers: [String]) { self.presentingViewController.dismiss(animated: true) { self.sendSMSTo(phoneNumbers: phoneNumbers) } } public func sendSMSTo(phoneNumbers: [String]) { if #available(iOS 10.0, *) { // iOS10 message compose view doesn't respect some system appearence attributes. // Specifically, the title is white, but the navbar is gray. // So, we have to set system appearence before init'ing the message compose view controller in order // to make its colors legible. // Then we have to be sure to set it back in the ComposeViewControllerDelegate callback. UIUtil.applyDefaultSystemAppearence() } let messageComposeViewController = MFMessageComposeViewController() messageComposeViewController.messageComposeDelegate = self messageComposeViewController.recipients = phoneNumbers let inviteText = NSLocalizedString("SMS_INVITE_BODY", comment:"body sent to contacts when inviting to Install Signal") messageComposeViewController.body = inviteText.appending(" \(self.installUrl)") self.presentingViewController.navigationController?.present(messageComposeViewController, animated:true) } // MARK: MessageComposeViewControllerDelegate func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { // Revert system styling applied to make messaging app legible on iOS10. UIUtil.applySignalAppearence() self.presentingViewController.dismiss(animated: true, completion: nil) switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment:"Alert body after invite failed"), preferredStyle: .alert) warning.addAction(UIAlertAction(title: CommonStrings.dismissButton, style: .default, handler: nil)) self.presentingViewController.present(warning, animated: true, completion: nil) case .sent: Logger.debug("\(self.TAG) user successfully invited their friends via SMS.") case .cancelled: Logger.debug("\(self.TAG) user cancelled message invite") } } // MARK: Mail @available(iOS 9.0, *) func mailAction() -> UIAlertAction? { guard MFMailComposeViewController.canSendMail() else { Logger.info("\(TAG) Device cannot send mail") return nil } let mailActionTitle = NSLocalizedString("SHARE_ACTION_MAIL", comment: "action sheet item to open native mail app") return UIAlertAction(title: mailActionTitle, style: .default) { _ in Logger.debug("\(self.TAG) Chose mail.") self.channel = .mail let picker = ContactsPicker(delegate: self, multiSelection: true, subtitleCellType: .email) let navigationController = UINavigationController(rootViewController: picker) self.presentingViewController.present(navigationController, animated: true) } } @available(iOS 9.0, *) func sendMailTo(emails recipientEmails: [String]) { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setBccRecipients(recipientEmails) let subject = NSLocalizedString("EMAIL_INVITE_SUBJECT", comment:"subject of email sent to contacts when inviting to install Signal") let bodyFormat = NSLocalizedString("EMAIL_INVITE_BODY", comment:"body of email sent to contacts when inviting to install Signal. Embeds {{link to install Signal}} and {{link to WhisperSystems home page}}") let body = String.init(format: bodyFormat, installUrl, homepageUrl) mailComposeViewController.setSubject(subject) mailComposeViewController.setMessageBody(body, isHTML: false) self.presentingViewController.dismiss(animated: true) { self.presentingViewController.navigationController?.present(mailComposeViewController, animated:true) { UIUtil.applySignalAppearence() } } } // MARK: MailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { self.presentingViewController.dismiss(animated: true, completion: nil) switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment:"Alert body after invite failed"), preferredStyle: .alert) warning.addAction(UIAlertAction(title: CommonStrings.dismissButton, style: .default, handler: nil)) self.presentingViewController.present(warning, animated: true, completion: nil) case .sent: Logger.debug("\(self.TAG) user successfully invited their friends via mail.") case .saved: Logger.debug("\(self.TAG) user saved mail invite.") case .cancelled: Logger.debug("\(self.TAG) user cancelled mail invite.") } } }
gpl-3.0
3d5917a050a596f97bd780f130a3e777
41.164659
213
0.674159
5.356633
false
false
false
false
4faramita/TweeBox
TweeBox/MentionTimelineTableViewController.swift
1
2070
// // MentionTimelineTableViewController.swift // TweeBox // // Created by 4faramita on 2017/8/23. // Copyright © 2017年 4faramita. All rights reserved. // import UIKit class MentionTimelineTableViewController: TimelineTableViewController { override func refreshTimeline(handler: (() -> Void)?) { let mentionTimelineParams = MentionTimelineParams() let timeline = Timeline( maxID: maxID, sinceID: sinceID, fetchNewer: fetchNewer, resourceURL: mentionTimelineParams.resourceURL, params: mentionTimelineParams ) timeline.fetchData { [weak self] (maxID, sinceID, tweets) in if (self?.maxID == nil) && (self?.sinceID == nil) { if let sinceID = sinceID { self?.sinceID = sinceID } if let maxID = maxID { self?.maxID = maxID } } else { if (self?.fetchNewer)! { if let sinceID = sinceID { self?.sinceID = sinceID } } else { if let maxID = maxID { self?.maxID = maxID } } } if tweets.count > 0 { self?.insertNewTweets(with: tweets) let cells = self?.tableView.visibleCells if cells != nil { for cell in cells! { let indexPath = self?.tableView.indexPath(for: cell) if let tweetCell = cell as? GeneralTweetTableViewCell { tweetCell.section = indexPath?.section } } } } if let handler = handler { handler() } } } }
mit
23e62071953f04859cd9f8f22aef41ed
28.528571
79
0.425254
5.922636
false
false
false
false
nakau1/Formations
Formations/Sources/Modules/Team/Views/Menu/TeamMenuViewController.swift
1
4246
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit import Rswift // MARK: - Controller Definition - class TeamMenuViewController: UIViewController { // MARK: ファクトリメソッド class func create(for team: Team) -> UIViewController { return R.storyboard.teamMenuViewController.instantiate(self) { vc in vc.team = team } } enum Row { case formation case formationTemplate case players case team static var rows: [Row] { return [.formation, .formationTemplate, .players, .team] } var name: String { switch self { case .formation: return "フォーメーション作成" case .formationTemplate: return "フォーメーション雛形作成" case .players: return "選手一覧" case .team: return "チーム設定" } } var summery: String { switch self { case .formation: return "" case .formationTemplate: return "フォーメーションの" case .players: return "選手の一覧、追加や編集、削除を行うことができます" case .team: return "チームの情報を編集することができます" } } var image: UIImage? { return nil } func process(_ viewController: UIViewController, team: Team) { switch self { case .formation: viewController.present(FormationViewController.create(for: team)) case .formationTemplate: viewController.push(FormationTemplateListViewController.create(for: team)) case .players: viewController.push(PlayerListViewController.create(for: team)) case .team: viewController.push(TeamEditViewController.create(for: team)) } } } @IBOutlet fileprivate weak var tableView: UITableView! private var team: Team! override func viewDidLoad() { super.viewDidLoad() prepare() } func prepare() { prepareNavigationBar() prepareBackgroundView() prepareObservingNotifications() title = team.name } func prepareBackgroundView() { let image = team.loadTeamImage().teamImage?.retina BackgroundView.notifyChangeImage(image) } private func prepareObservingNotifications() { Realm.Team.observe(self, change: #selector(didReceiveTeamChange(notification:))) } @objc private func didReceiveTeamChange(notification: Notification) { title = team.name } } // MARK: - UITableViewDataSource & UITableViewDelegate extension TeamMenuViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Row.rows.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.teamMenu, for: indexPath)! cell.menu = Row.rows[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) Row.rows[indexPath.row].process(self, team: team) } } // MARK: - Cell - class TeamMenuTableViewCell: UnhighlightableTableViewCell { @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var summeryLabel: UILabel! @IBOutlet private weak var menuImageView: UIImageView! var menu: TeamMenuViewController.Row! { didSet { guard let menu = self.menu else { return } nameLabel.text = menu.name summeryLabel.text = menu.summery menuImageView.image = menu.image } } }
apache-2.0
c032ba005c20ee13b7ee66326bf25bc7
30.75
109
0.589321
5.048447
false
false
false
false
ahumeijun/GeekWeather
GeekWeather/Commands/ls.swift
1
2249
// // ls.swift // GeekWeather // // Created by 梅俊 on 15/12/17. // Copyright © 2015年 RangerStudio. All rights reserved. // import UIKit import CocoaLumberjack class ls: Command { override init() { super.init() self.validOptions.appendContentsOf(["1", "a"]) } override func execute() throws -> String! { var results : [String] = [String]() for option in self.options { if let argument = option.argument { self.arguments.append(argument) } } if self.arguments.isEmpty { self.arguments.append("."); } for path in self.arguments { self.delegate.pathTree.push() defer { self.delegate.pathTree.pop() } do { try self.delegate.pathTree.moveToPath(path) } catch { throw error } DDLogDebug("ls path is \(self.delegate.pathTree.workPtr.treepath())") var paths = self.delegate.pathTree.workPtr.contents() var count = 3 for option in self.options { guard self.validOptions.contains(option.option) else { throw CmdExecError.InvalidOption(opt: option.option) } switch option.option { case "1": count = 1 case "a": paths.append(".") paths.append("..") default: break } } let max = count var result = "" for name in paths { result += name count-- if count == 0 { result += "\n" count = max } else { result += " " } } if result.characters.last != "\n" { result += "\n" } results.append(result) } return results.joinWithSeparator("\n\n") } }
apache-2.0
5bc491da3228bbc944c84293891f11fa
25.376471
81
0.41347
5.226107
false
false
false
false
rodrigoDyT/todo-mobile-ios
PowerTodo/PowerTodo/SignInViewController.swift
1
4845
// // ViewController.swift // PowerTodo // // Created by Rodrigo on 9/20/16. // Copyright © 2016 SG Solutions. All rights reserved. // import UIKit import NVActivityIndicatorView class SignInViewController: UIViewController { @IBOutlet weak var emailTxtField: UITextField! @IBOutlet weak var passwordTextField: UITextField! var actInd: NVActivityIndicatorView! = nil enum AlertControllerTitles: String{ case incorretCredentials = "Oops" } enum AlertControllerMessages: String { case incorrectCredentials = "Senha ou Email incorretos majestade" case incompleteCredentials = "Tem coisa faltando no email ou senha" } enum AlertTitleForButtons: String { case incorrectCredentials = "Ok, vou tentar de novo" case incompleteCredentials = "Ok, vou arrumar" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationController?.navigationBar.barTintColor = UIColor.white self.navigationController?.navigationBar.tintColor = UIColor.purple } @IBAction func signInButton(_ sender: AnyObject) { self.showActivityIndicatory(uiView: self.view) self.handleLogin() //let disableMyButton = sender as? UIButton //disableMyButton?.isEnabled = false } @IBAction func ForgotPasswordButton(_ sender: AnyObject) { self.performSegue(withIdentifier: "recoverPasswordSegue", sender: self) } @IBAction func signUpButton(_ sender: AnyObject) { self.performSegue(withIdentifier: "signUpSegue", sender: self) } func handleLogin(){ if((self.emailTxtField.text?.characters.count)! < 6 || (self.passwordTextField.text?.characters.count)! < 3 ){ self.buildAlert(titleController: AlertControllerTitles.incorretCredentials.rawValue, messageController: AlertControllerMessages.incompleteCredentials.rawValue, titleButton: AlertTitleForButtons.incompleteCredentials.rawValue) self.resetFields() }else{ let user: User = User( name: "", email: self.emailTxtField.text!, password: self.passwordTextField.text! ) user.signIn() let loginResultNotification = Notification.Name(rawValue:"loginResultNotification") let nc = NotificationCenter.default nc.addObserver(forName:loginResultNotification, object:nil, queue:nil, using:handleNotificationResponse) } } func handleNotificationResponse(notification:Notification) -> Void{ guard let userInfo = notification.userInfo, let success = userInfo["success"] as? Bool else { print("No userInfo found in notification") return } if(success){ self.performSegue(withIdentifier: "fromSignToHomeSegue", sender: self) }else{ self.buildAlert(titleController: AlertControllerTitles.incorretCredentials.rawValue, messageController: AlertControllerMessages.incorrectCredentials.rawValue, titleButton: AlertTitleForButtons.incorrectCredentials.rawValue) } self.resetFields() } func buildAlert(titleController: String, messageController: String, titleButton: String){ let alert = UIAlertController(title: titleController, message: messageController, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: titleButton, style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } func showActivityIndicatory(uiView: UIView) { self.actInd = NVActivityIndicatorView( frame: CGRect(x: 0, y: 0, width: 70, height: 70), type: .ballTrianglePath, color: UIColor.purple, padding: CGFloat(0)) actInd.center = uiView.center uiView.addSubview(actInd) actInd.startAnimating() } @IBAction func unwindHome(_ segue: UIStoryboardSegue) { self.resetFields() if !segue.source.isBeingDismissed { segue.source.dismiss(animated: true, completion: nil) ; } } func resetFields(){ if(self.actInd != nil){ self.actInd.stopAnimating() } let nc = NotificationCenter.default nc.removeObserver(self) self.emailTxtField.text = "" self.passwordTextField.text = "" } }
mit
3d0ed53754dbc916f67701066d5b4e7c
31.72973
237
0.627374
5.311404
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Common/CloudKitSync/FavoriteSongUploader.swift
1
2601
// // FavoriteSongUploader.swift // DereGuide // // Created by zzk on 29/09/2017. // Copyright © 2017 zzk. All rights reserved. // import CoreData /// use local favorite Song to create remote favorite Song final class FavoriteSongUploader: ElementChangeProcessor { typealias Element = FavoriteSong var remote: FavoriteSongsRemote init(remote: FavoriteSongsRemote) { self.remote = remote } var elementsInProgress = InProgressTracker<FavoriteSong>() func setup(for context: ChangeProcessorContext) { // no-op } func processChangedLocalElements(_ objects: [FavoriteSong], in context: ChangeProcessorContext) { processInsertedFavoriteSongs(objects, in: context) } func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], in context: ChangeProcessorContext, completion: () -> ()) { completion() } func fetchLatestRemoteRecords(in context: ChangeProcessorContext) { // no-op } var predicateForLocallyTrackedElements: NSPredicate { return FavoriteSong.waitingForUploadPredicate } } extension FavoriteSongUploader { fileprivate func processInsertedFavoriteSongs(_ insertions: [FavoriteSong], in context: ChangeProcessorContext) { remote.upload(insertions) { (remoteFavoriteSongs, error) in context.perform { guard !(error?.isPermanent ?? false) else { // Since the error was permanent, delete these objects: insertions.forEach { $0.markForLocalDeletion() } self.elementsInProgress.markObjectsAsComplete(insertions) return } // currently not retry for temporarily error // set unit remote id for favoriteSong in insertions { guard let remoteFavoriteSong = remoteFavoriteSongs.first(where: { favoriteSong.createdAt == $0.localCreatedAt }) else { continue } favoriteSong.creatorID = remoteFavoriteSong.creatorID favoriteSong.remoteIdentifier = remoteFavoriteSong.id } context.delayedSaveOrRollback() if Config.cloudKitDebug && insertions.count > 0 { print("favorite song uploader: upload \(insertions.count) success \(insertions.filter { $0.remoteIdentifier != nil }.count)") } self.elementsInProgress.markObjectsAsComplete(insertions) } } } }
mit
af06b390006455e076375d991e1e6a03
32.766234
150
0.624615
5.252525
false
false
false
false
DasHutch/minecraft-castle-challenge
app/_src/RuleTableViewCell.swift
1
1997
// // RuleTableViewCell.swift // MC Castle Challenge // // Created by Gregory Hutchinson on 9/20/15. // Copyright © 2015 Gregory Hutchinson. All rights reserved. // import UIKit class RuleTableViewCell: UITableViewCell { @IBOutlet weak var ruleLabel: UILabel! @IBOutlet weak var indexLabel: UILabel! struct ViewData { let rule: Rule let index: Int } var viewData: ViewData? { didSet { updateRuleLabel(viewData?.rule.description) updateRuleIndexLabel(viewData?.index) updateLabelFontForDynamicTextStyles() } } //MARK: - Lifecycle override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func prepareForReuse() { //NOTE: Clear Label, Etc updateRuleLabel(nil) updateRuleIndexLabel(nil) updateLabelFontForDynamicTextStyles() } //MARK: - Public //MARK: - Private private func updateRuleLabel(rule: String?) { updateLabel(ruleLabel, withText: rule) } private func updateRuleIndexLabel(ruleIndex: Int?) { if ruleIndex >= 0 && ruleIndex != nil { let nonZeroBasedIndex = ruleIndex! + 1 let ruleIndexString = "\(nonZeroBasedIndex)." updateLabel(indexLabel, withText: ruleIndexString) }else { updateLabel(indexLabel, withText: "") } } private func updateLabel(label: UILabel?, withText text: String?) { label?.text = text } private func updateLabelFontForDynamicTextStyles() { ruleLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleHeadline) indexLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleBody) } } extension RuleTableViewCell.ViewData { init(rule: Rule, withIndex index: Int) { self.rule = rule self.index = index } }
gpl-2.0
5205b80b86ea42cb45eabb2c6035c972
25.613333
89
0.630261
4.674473
false
false
false
false
jadekler/git-swift-todo-tutorial
Todo/Todo/TodoListTableTableViewController.swift
1
2307
import UIKit class TodoListTableViewController: UITableViewController { var todoItems: [TodoItem] = [] @IBAction func unwindAndAddToList(segue: UIStoryboardSegue) { let source = segue.sourceViewController as! AddTodoItemViewController let todoItem:TodoItem = source.todoItem if todoItem.itemName != "" { self.todoItems.append(todoItem) self.tableView.reloadData() } } @IBAction func unwindToList(segue: UIStoryboardSegue) { } func loadInitialData() { todoItems = [ TodoItem(itemName: "Go to the dentist"), TodoItem(itemName: "Fetch groceries"), TodoItem(itemName: "Sleep") ] } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let tappedItem = todoItems[indexPath.row] as TodoItem tappedItem.completed = !tappedItem.completed tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) } override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let foo = tableView!.dequeueReusableCellWithIdentifier("ListPrototypeCell") as UITableViewCell? let tempCell = foo! let todoItem = todoItems[indexPath.row] // Downcast from UILabel? to UILabel let cell = tempCell.textLabel as UILabel! cell.text = todoItem.itemName if (todoItem.completed) { tempCell.accessoryType = UITableViewCellAccessoryType.Checkmark; } else { tempCell.accessoryType = UITableViewCellAccessoryType.None; } return tempCell } override func viewDidLoad() { super.viewDidLoad() loadInitialData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoItems.count } }
mit
887af7cc1505ca24c81a445822f46a9c
30.60274
119
0.647594
5.696296
false
false
false
false
iosyoujian/Swift-DeviceType
DeviceType/UIDevice+DeviceType.swift
2
979
// // UIDevice+DeviceType.swift // Swift-DeviceType // // Created by Ian Hirschfeld on 3/6/15. // Copyright (c) 2015 Ian Hirschfeld. All rights reserved. // import UIKit extension UIDevice { var deviceType: DeviceType { return DeviceType() } var isPortrait: Bool { return UIDevice.currentDevice().orientation == .Portrait || UIDevice.currentDevice().orientation == .PortraitUpsideDown } var isLandscape: Bool { return UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight } var isIPodTouch: Bool { return UIDevice.currentDevice().model == "iPod touch" } var isIPhone: Bool { return UIDevice.currentDevice().model == "iPhone" } var isIPad: Bool { return UIDevice.currentDevice().model == "iPad" } var isSimulator: Bool { return UIDevice.currentDevice().model == "iPhone Simulator" || UIDevice.currentDevice().model == "iPad Simulator" } }
mit
310b8d0fb361cdfe7b47feee45f14c66
22.309524
124
0.684372
4.370536
false
false
false
false
barisarsan/ScreenSceneController
ScreenSceneController/ScreenSceneControllerTests/ScreenSceneSpec.swift
1
14352
// // ScreenSceneSpec.swift // ScreenSceneController // // Copyright (c) 2014 Ruslan Shevchuk // // 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 Quick import Nimble class ScreenSceneSpec: QuickSpec { override func spec() { describe("ScreenScene", { var mainController: UIViewController! var mainAttachment: ScreenSceneAttachment! var accessoryController: UIViewController! var accessoryAttachment: ScreenSceneAttachment! var screenScene: MockScreenScene! beforeEach({ mainController = UIViewController() mainAttachment = ScreenSceneAttachment(viewController: mainController) accessoryController = UIViewController() accessoryAttachment = ScreenSceneAttachment(viewController: accessoryController) }) it("should add attachments when it loaded", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) screenScene.viewDidLoad() expect(mainAttachment.viewController.parentViewController) === screenScene expect(accessoryAttachment.viewController.parentViewController) === screenScene }) it("should have setup like this when it loaded", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) screenScene.viewDidLoad() expect(screenScene.edgesForExtendedLayout) == UIRectEdge.None expect(screenScene.extendedLayoutIncludesOpaqueBars).to(beTruthy()) expect(screenScene.automaticallyAdjustsScrollViewInsets).to(beFalsy()) expect(screenScene.sceneTapGestureRecognizer.delegate) === screenScene expect(screenScene.view.gestureRecognizers).to(contain(screenScene.sceneTapGestureRecognizer)) }) describe("reactions on view events", { beforeEach({ screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) }) it("viewDidLayoutSubviews", { screenScene.updateShadowsWasCalled = false screenScene.viewDidLayoutSubviews() expect(screenScene.updateShadowsWasCalled).to(beTruthy()) }) it("willAppear check") { screenScene.updateLayoutWasCalled = false screenScene.viewWillAppear(false) expect(screenScene.updateLayoutWasCalled).to(beTruthy()) } it("willRotateToInterfaceOrientation check") { screenScene.updateLayoutWasCalled = false screenScene.updateShadowsWasCalled = false screenScene.willRotateToInterfaceOrientation(screenScene.interfaceOrientation, duration: 0) expect(screenScene.updateLayoutWasCalled).to(beTruthy()) expect(screenScene.updateShadowsWasCalled).to(beTruthy()) } }) it("should remove attachment before add new one", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) expect(screenScene.accessoryScreenSceneAttachment) === accessoryAttachment let allNewAccessoryAttachment = ScreenSceneAttachment(viewController: UIViewController()) screenScene.attachAccessory(allNewAccessoryAttachment, animated: false) expect(screenScene.accessoryScreenSceneAttachment) === allNewAccessoryAttachment }) it("should setup views hierarchy when add screen scene attachment", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: nil) expect(accessoryAttachment.containerView.superview).to(beNil()) expect(accessoryAttachment.viewController.view.superview).to(beNil()) expect(accessoryAttachment.containerOverlay.superview).to(beNil()) screenScene.attachAccessory(accessoryAttachment, animated: false) expect(accessoryAttachment.containerView.superview) === screenScene.view expect(accessoryAttachment.viewController.view.superview) === accessoryAttachment.containerView expect(accessoryAttachment.navigationBar.superview) === accessoryAttachment.containerView expect(accessoryAttachment.containerOverlay.superview) === accessoryAttachment.containerView }) it("should remove views owned by attachment when they are disappear", { screenScene.addScreenSceneAttachment(accessoryAttachment) screenScene.removeAllAttachments() for attachment in screenScene.screenSceneAttachments { for viewOwnedByAttachemnt in [attachment.viewController.view, attachment.containerView, attachment.containerOverlay, attachment.navigationBar] { expect(viewOwnedByAttachemnt.superview).to(beNil()) } } }) it("should bring focus on right view", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) screenScene.bringFocus(mainAttachment, animated: false) screenScene.updateFocus() expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beFalsy()) screenScene.bringFocus(accessoryAttachment, animated: false) screenScene.updateFocus() expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beTruthy()) screenScene.bringFocus(mainAttachment, animated: false) screenScene.updateFocus() expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beFalsy()) }) it("should detach exlusive focus accessory if it lost focus", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) accessoryAttachment.screenSceneAttachmentLayout.exclusiveFocus = true expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beTruthy()) screenScene.bringFocus(mainAttachment, animated: false) expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beFalsy()) }) it("currently dragging containerView only can bring focus on itself", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) screenScene.scrollViewDidScroll(mainAttachment.containerView) expect(screenScene.attachmentInFocus(screenScene.accessoryScreenSceneAttachment)).to(beTruthy()) screenScene.scrollViewDidScroll(mainAttachment.containerView) expect(screenScene.attachmentInFocus(mainAttachment)).to(beFalsy()) screenScene.draggingContainerView = mainAttachment.containerView screenScene.scrollViewDidScroll(screenScene.draggingContainerView!) expect(screenScene.attachmentInFocus(mainAttachment)).to(beTruthy()) screenScene.scrollViewDidScroll(accessoryAttachment.containerView) expect(screenScene.attachmentInFocus(accessoryAttachment)).to(beFalsy()) screenScene.draggingContainerView = accessoryAttachment.containerView screenScene.scrollViewDidScroll(screenScene.draggingContainerView!) expect(screenScene.attachmentInFocus(accessoryAttachment)).to(beTruthy()) }) it("containersViews should be right ones", { screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: nil) expect(screenScene.containersViews.count).to(equal(1)) screenScene.attachAccessory(accessoryAttachment, animated: false) expect(screenScene.containersViews.count).to(equal(2)) expect(screenScene.screenSceneAttachmentByContainerView(screenScene.accessoryScreenSceneAttachment!.containerView)) === screenScene.accessoryScreenSceneAttachment screenScene.detachAccessory(animated: false) expect(screenScene.containersViews.count).to(equal(1)) expect(screenScene.containersViews).to(contain(mainAttachment.containerView)) screenScene.removeAllAttachments() expect(screenScene.containersViews.count).to(equal(0)) }) it("should have constraints count equal to X when have one attachment", { let numberOfConstraintsWhenScreenSceneHaveOneAttachment = 20 screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: nil) let containtsBeforeAttachement = screenScene.view.constraints() screenScene.attachAccessory(accessoryAttachment, animated: false) screenScene.detachAccessory(animated: false) expect(screenScene.view.constraints().count).to(beLessThanOrEqualTo(numberOfConstraintsWhenScreenSceneHaveOneAttachment)) }) it("should have constraints count equal to X when have two attachments", { let numberOfConstraintsWhenScreenSceneHaveTwoAttachment = 36 screenScene = MockScreenScene(mainScreenSceneAttachment: mainAttachment, accessoryScreenSceneAttachment: accessoryAttachment) expect(screenScene.view.constraints().count).to(beLessThanOrEqualTo(numberOfConstraintsWhenScreenSceneHaveTwoAttachment)) screenScene.detachAccessory(animated: false) screenScene.attachAccessory(accessoryAttachment, animated: false) expect(screenScene.view.constraints().count).to(beLessThanOrEqualTo(numberOfConstraintsWhenScreenSceneHaveTwoAttachment)) }) it("should update scene when attachmentLayoutDidChange") { screenScene.updateMotionEffectsWasCalled = false screenScene.updateLayoutWasCalled = false screenScene.updateFocusWasCalled = false screenScene.attachmentLayoutDidChange() expect(screenScene.updateMotionEffectsWasCalled).to(beTruthy()) expect(screenScene.updateLayoutWasCalled).to(beTruthy()) expect(screenScene.updateFocusWasCalled).to(beTruthy()) } }) } } class MockScreenScene: ScreenScene { var viewDidLayoutSubviewsWasCalled = false var updateShadowsWasCalled = false var updateFocusWasCalled = false var updateLayoutWasCalled = false var updateMotionEffectsWasCalled = false override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() viewDidLayoutSubviewsWasCalled = true } override func updateShadows(#duration: NSTimeInterval) { super.updateShadows(duration: duration) updateShadowsWasCalled = true } override func updateFocus() { super.updateFocus() updateFocusWasCalled = true } override func updateLayout(interfaceOrientation: UIInterfaceOrientation) { super.updateLayout(interfaceOrientation) updateLayoutWasCalled = true } override func updateMotionEffects(screenSceneAttachment: ScreenSceneAttachment) { super.updateMotionEffects(screenSceneAttachment) updateMotionEffectsWasCalled = true } }
mit
12eba2e783a7d0da5a0718dc4b99f5d1
48.6609
178
0.634894
6.269987
false
false
false
false
MoWangChen/Learning
App/colorQrCode/colorQrCode/ColorfulQRCodeView.swift
1
3256
// // ColorfulQRCodeView.swift // colorQrCode // // Created by 谢鹏翔 on 2018/1/29. // Copyright © 2018年 365ime. All rights reserved. // import UIKit class ColorfulQRCodeView: UIView { lazy var maskLayer: CALayer = { let _maskLayer = CALayer.init(); self.layer.addSublayer(_maskLayer); return _maskLayer; }() lazy var gradientLayer: CAGradientLayer = { let layer = CAGradientLayer.init(); layer.colors = [ UIColor.init(red: 0x2a / 255.0, green: 0x9c / 255.0, blue: 0x1f / 255.0, alpha: 1.0).cgColor, UIColor.init(red: 0xe6 / 255.0, green: 0xcd / 255.0, blue: 0x27 / 255.0, alpha: 1.0).cgColor, UIColor.init(red: 0xe6 / 255.0, green: 0x27 / 255.0, blue: 0x57 / 255.0, alpha: 1.0).cgColor ]; self.layer.addSublayer(layer); layer.frame = self.bounds; return layer; }() override func awakeFromNib() { super.awakeFromNib(); self.backgroundColor = UIColor.white; } func syncFrame() { self.maskLayer.frame = self.bounds; self.gradientLayer.frame = self.bounds; } // 设置黑白二维码图片 func setQRcodeImage(qrcodeImage: UIImage) { let imageMask = genQRCodeImageMask(grayScaleQRCodeImage: qrcodeImage); maskLayer.contents = imageMask; maskLayer.frame = self.bounds; self.gradientLayer.mask = maskLayer; } func genQRCodeImageMask(grayScaleQRCodeImage: UIImage?) -> CGImage? { if let image = grayScaleQRCodeImage { let bitsPerComponent = 8; let bytesPerPixel = 4; let width: Int = Int(image.size.width); let height: Int = Int(image.size.height); let imageData = UnsafeMutableRawPointer.allocate(bytes: Int(width * height * bytesPerPixel), alignedTo: 8); // 将原始黑白二维码图片绘制到像素格式为RGBA的图片上,绘制后的像素数据在imageData中 let colorSpace = CGColorSpaceCreateDeviceRGB(); let imageContext = CGContext.init(data: imageData, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: bitsPerComponent, bytesPerRow: width * bytesPerPixel, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue); UIGraphicsPushContext(imageContext!); imageContext?.translateBy(x: 0, y: CGFloat(height)); imageContext?.scaleBy(x: 1, y: -1); image.draw(in: CGRect.init(x: 0, y: 0, width: width, height: height)); // 根据每个像素R通道的值修改Alpha通道的值, 当Red大于100, 则Alpha置为0, 反之置为255 for row in 0..<height { for col in 0..<width { let offset = row * width * bytesPerPixel + col * bytesPerPixel let r = imageData.load(fromByteOffset: offset + 1, as: UInt8.self) let alpha:UInt8 = r > 100 ? 0 : 255 imageData.storeBytes(of: alpha, toByteOffset: offset, as: UInt8.self) } } return imageContext?.makeImage(); } return nil; } }
mit
033f86734190ee90415261d2f1e3c450
37.9125
274
0.596209
4.101449
false
false
false
false
danielbyon/Convert
Sources/Convert/Convert.swift
1
3462
// // Convert.swift // Convert // // Copyright © 2017 Daniel Byon // // 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 public protocol Convertible: Comparable, Hashable { associatedtype Unit: RawRepresentable var value: Double { get } var unit: Unit { get } init(value: Double, unit: Unit) func to(_ unit: Unit) -> Self static func + (lhs: Self, rhs: Self) -> Self static func - (lhs: Self, rhs: Self) -> Self static func * (lhs: Self, rhs: Self) -> Self static func / (lhs: Self, rhs: Self) -> Self } public extension Convertible where Unit.RawValue: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(value) hasher.combine(unit.rawValue) } } public extension Convertible where Unit.RawValue == Double { func to(_ unit: Unit) -> Self { let value = self.value * self.unit.rawValue / unit.rawValue return Self(value: value, unit: unit) } static func + (lhs: Self, rhs: Self) -> Self { return perform(lhs: lhs, rhs: rhs, operation: +) } static func - (lhs: Self, rhs: Self) -> Self { return perform(lhs: lhs, rhs: rhs, operation: -) } static func * (lhs: Self, rhs: Self) -> Self { return perform(lhs: lhs, rhs: rhs, operation: *) } static func / (lhs: Self, rhs: Self) -> Self { guard rhs.value != 0.0 else { fatalError("Attempting to divide by zero.") } return perform(lhs: lhs, rhs: rhs, operation: /) } static func < (lhs: Self, rhs: Self) -> Bool { let (lhs, rhs, _) = computeCommonUnitValues(lhs, rhs) return lhs < rhs } static func == (lhs: Self, rhs: Self) -> Bool { let (lhs, rhs, _) = computeCommonUnitValues(lhs, rhs) return lhs == rhs } // MARK: Private private static func perform(lhs: Self, rhs: Self, operation: (Double, Double) -> Double) -> Self { let (lhs, rhs, unit) = computeCommonUnitValues(lhs, rhs) let value = operation(lhs, rhs) return Self(value: value, unit: unit) } private static func computeCommonUnitValues(_ lhs: Self, _ rhs: Self) -> (lhs: Double, rhs: Double, unit: Unit) { return lhs.unit.rawValue < rhs.unit.rawValue ? (lhs: lhs.value, rhs: rhs.to(lhs.unit).value, unit: lhs.unit) : (lhs: lhs.to(rhs.unit).value, rhs: rhs.value, unit: rhs.unit) } }
mit
3c05bd131682739815b7b415e0ce4506
32.601942
117
0.646634
3.841287
false
false
false
false