repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
azu/command-line-tool-by-swift
refs/heads/master
git-current-branch.swift
mit
1
#!/usr/bin/env xcrun swift -i -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk // -sdk $(xcrun --show-sdk-path --sdk macosx) import Cocoa var task = NSTask(); task.launchPath = "/bin/sh" task.arguments = ["-c", "git symbolic-ref --short HEAD"] let stdout = NSPipe() task.standardOutput = stdout; task.launch() task.waitUntilExit() var fileHandle = stdout.fileHandleForReading var result = NSString( data: fileHandle.readDataToEndOfFile(), encoding:NSUTF8StringEncoding ) print(result)
f26f951e2ecc75150da65f8f238ea3ff
26.95
140
0.744186
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
AOPDemo/AOPDemo/Pods/Result/Result/Result.swift
apache-2.0
21
// Copyright (c) 2015 Rob Rix. All rights reserved. /// An enum representing either a failure with an explanatory error, or a success with a result value. public enum Result<T, Error: ErrorType>: ResultType, CustomStringConvertible, CustomDebugStringConvertible { case Success(T) case Failure(Error) // MARK: Constructors /// Constructs a success wrapping a `value`. public init(value: T) { self = .Success(value) } /// Constructs a failure wrapping an `error`. public init(error: Error) { self = .Failure(error) } /// Constructs a result from an Optional, failing with `Error` if `nil`. public init(_ value: T?, @autoclosure failWith: () -> Error) { self = value.map(Result.Success) ?? .Failure(failWith()) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(@autoclosure _ f: () throws -> T) { self.init(attempt: f) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(@noescape attempt f: () throws -> T) { do { self = .Success(try f()) } catch { self = .Failure(error as! Error) } } // MARK: Deconstruction /// Returns the value from `Success` Results or `throw`s the error. public func dematerialize() throws -> T { switch self { case let .Success(value): return value case let .Failure(error): throw error } } /// Case analysis for Result. /// /// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results. public func analysis<Result>(@noescape ifSuccess ifSuccess: T -> Result, @noescape ifFailure: Error -> Result) -> Result { switch self { case let .Success(value): return ifSuccess(value) case let .Failure(value): return ifFailure(value) } } // MARK: Higher-order functions /// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??` public func recover(@autoclosure value: () -> T) -> T { return self.value ?? value() } /// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??` public func recoverWith(@autoclosure result: () -> Result<T,Error>) -> Result<T,Error> { return analysis( ifSuccess: { _ in self }, ifFailure: { _ in result() }) } // MARK: Errors /// The domain for errors constructed by Result. public static var errorDomain: String { return "com.antitypical.Result" } /// The userInfo key for source functions in errors constructed by Result. public static var functionKey: String { return "\(errorDomain).function" } /// The userInfo key for source file paths in errors constructed by Result. public static var fileKey: String { return "\(errorDomain).file" } /// The userInfo key for source file line numbers in errors constructed by Result. public static var lineKey: String { return "\(errorDomain).line" } /// Constructs an error. public static func error(message: String? = nil, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> NSError { var userInfo: [String: AnyObject] = [ functionKey: function, fileKey: file, lineKey: line, ] if let message = message { userInfo[NSLocalizedDescriptionKey] = message } return NSError(domain: errorDomain, code: 0, userInfo: userInfo) } // MARK: CustomStringConvertible public var description: String { return analysis( ifSuccess: { ".Success(\($0))" }, ifFailure: { ".Failure(\($0))" }) } // MARK: CustomDebugStringConvertible public var debugDescription: String { return description } } /// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal. public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { if let left = left.value, right = right.value { return left == right } else if let left = left.error, right = right.error { return left == right } return false } /// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values. public func != <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { return !(left == right) } /// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> T) -> T { return left.recover(right()) } /// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> Result<T, Error>) -> Result<T, Error> { return left.recoverWith(right()) } // MARK: - Derive result from failable closure public func materialize<T>(@noescape f: () throws -> T) -> Result<T, NSError> { return materialize(try f()) } public func materialize<T>(@autoclosure f: () throws -> T) -> Result<T, NSError> { do { return .Success(try f()) } catch { return .Failure(error as NSError) } } // MARK: - Cocoa API conveniences /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.: /// /// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) } public func `try`<T>(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> T?) -> Result<T, NSError> { var error: NSError? return `try`(&error).map(Result.Success) ?? .Failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line)) } /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.: /// /// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) } public func `try`(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> Bool) -> Result<(), NSError> { var error: NSError? return `try`(&error) ? .Success(()) : .Failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line)) } // MARK: - Operators infix operator >>- { // Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc. associativity left // Higher precedence than function application, but lower than function composition. precedence 100 } /// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors. /// /// This is a synonym for `flatMap`. public func >>- <T, U, Error> (result: Result<T, Error>, @noescape transform: T -> Result<U, Error>) -> Result<U, Error> { return result.flatMap(transform) } // MARK: - ErrorTypeConvertible conformance /// Make NSError conform to ErrorTypeConvertible extension NSError: ErrorTypeConvertible { public static func errorFromErrorType(error: ErrorType) -> NSError { return error as NSError } } // MARK: - /// An “error” that is impossible to construct. /// /// This can be used to describe `Result`s where failures will never /// be generated. For example, `Result<Int, NoError>` describes a result that /// contains an `Int`eger and is guaranteed never to be a `Failure`. public enum NoError: ErrorType { } import Foundation
35f9ec625f96cefc2e464d52e39ed993
32.075221
162
0.683478
false
false
false
false
andrebocchini/SwiftChatty
refs/heads/master
Example/Pods/Alamofire/Source/ParameterEncoding.swift
mit
2
// // ParameterEncoding.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. /// /// There is no published specification for how to encode collection types. By default the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } /// Configures how `Array` parameters are encoded. /// /// - brackets: An empty set of square brackets is appended to the key for every value. /// This is the default behavior. /// - noBrackets: No brackets are appended. The key is encoded as is. public enum ArrayEncoding { case brackets, noBrackets func encode(key: String) -> String { switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Configures how `Bool` parameters are encoded. /// /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. /// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding { case numeric, literal func encode(value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination /// The encoding to use for `Array` parameters. public let arrayEncoding: ArrayEncoding /// The encoding to use for `Bool` parameters. public let boolEncoding: BoolEncoding // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// - parameter arrayEncoding: The encoding to use for `Array` parameters. /// - parameter boolEncoding: The encoding to use for `Bool` parameters. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { self.destination = destination self.arrayEncoding = arrayEncoding self.boolEncoding = boolEncoding } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape(boolEncoding.encode(value: bool)))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string[range] escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring) index = endIndex } } return escaped } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. /// /// - parameter urlRequest: The request to apply the JSON object to. /// - parameter jsonObject: The JSON object to apply to the request. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header /// field of an encoded request is set to `application/x-plist`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } }
dc6ab3267026cd181bab5da8008a6c13
39.753623
143
0.642146
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
refs/heads/main
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/TrafficMapViewController.swift
apache-2.0
1
// Copyright 2020 Google LLC. 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 GoogleMaps import UIKit class TrafficMapViewController: UIViewController { private var mapView: GMSMapView = { let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12) let mapView = GMSMapView(frame: .zero, camera: camera) mapView.isTrafficEnabled = true return mapView }() override func loadView() { view = mapView } }
6bf76887e24814587d27c17945c9e53d
32
91
0.734343
false
false
false
false
exponent/exponent
refs/heads/master
packages/expo-dev-menu/ios/DevMenuUtils.swift
bsd-3-clause
2
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation class DevMenuUtils { /** Swizzles implementations of given selectors. */ static func swizzle(selector selectorA: Selector, withSelector selectorB: Selector, forClass: AnyClass) { if let methodA = class_getInstanceMethod(forClass, selectorA), let methodB = class_getInstanceMethod(forClass, selectorB) { let impA = method_getImplementation(methodA) let argsTypeA = method_getTypeEncoding(methodA) let impB = method_getImplementation(methodB) let argsTypeB = method_getTypeEncoding(methodB) if class_addMethod(forClass, selectorA, impB, argsTypeB) { class_replaceMethod(forClass, selectorB, impA, argsTypeA) } else { method_exchangeImplementations(methodA, methodB) } } } /** Strips `RCT` prefix from given string. */ static func stripRCT(_ str: String) -> String { return str.starts(with: "RCT") ? String(str.dropFirst(3)) : str } static func resourcesBundle() -> Bundle? { let frameworkBundle = Bundle(for: DevMenuUtils.self) guard let resourcesBundleUrl = frameworkBundle.url(forResource: "EXDevMenu", withExtension: "bundle") else { return nil } return Bundle(url: resourcesBundleUrl) } }
2b4b63087f08ddc8fdab8260f65deea2
30.829268
112
0.700383
false
false
false
false
kbot/imoji-ios-sdk-ui
refs/heads/master
Examples/Artmoji/artmoji/IMCreateArtmojiViewController.swift
mit
1
// // ImojiSDKUI // // Created by Alex Hoang // Copyright (C) 2015 Imoji // // 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 ImojiSDKUI public class IMCreateArtmojiViewController: UIViewController { // Required init variables private var session: IMImojiSession! public var imageBundle: NSBundle public var sourceImage: UIImage? public var capturedImageOrientation: UIImageOrientation // Artmoji view private(set) public var createArtmojiView: IMCreateArtmojiView! // MARK: - Object lifecycle public init(sourceImage: UIImage?, capturedImageOrientation: UIImageOrientation?, session: IMImojiSession, imageBundle: NSBundle) { self.sourceImage = sourceImage self.capturedImageOrientation = capturedImageOrientation ?? UIImageOrientation.Up self.session = session self.imageBundle = imageBundle super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View lifecycle override public func loadView() { if let _ = self.sourceImage { super.loadView() createArtmojiView = IMCreateArtmojiView(session: self.session, sourceImage: self.sourceImage!, imageBundle: self.imageBundle) createArtmojiView.capturedImageOrientation = self.capturedImageOrientation createArtmojiView.delegate = self view.addSubview(createArtmojiView) createArtmojiView.mas_makeConstraints { make in make.top.equalTo()(self.mas_topLayoutGuideBottom) make.left.equalTo()(self.view) make.right.equalTo()(self.view) make.bottom.equalTo()(self.mas_bottomLayoutGuideTop) } } } override public func prefersStatusBarHidden() -> Bool { return true } // Mark: - Buton action methods #if NOT_PHOTO_EXTENSION func collectionViewControllerCreateImojiButtonTapped() { let cameraViewController = IMCameraViewController(session: self.session, imageBundle: self.imageBundle, controllerType: IMArtmojiConstants.PresentingViewControllerType.CreateImoji) cameraViewController.modalPresentationStyle = UIModalPresentationStyle.FullScreen cameraViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve cameraViewController.delegate = self presentedViewController!.presentViewController(cameraViewController, animated: true, completion: nil) } #endif // Mark: - Draw create imoji button func drawCreateImojiButtonImage() -> UIImage { let size = CGSizeMake(60.0, 41.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let context = UIGraphicsGetCurrentContext() CGContextSetBlendMode(context, CGBlendMode.Normal) let shadowSize: CGFloat = 1.5 let cornerRadius: CGFloat = 2.5 let shapeLayer = CAShapeLayer() let path = UIBezierPath(roundedRect: CGRectMake(shadowSize, shadowSize, size.width - (shadowSize * 2), size.height - (shadowSize * 2)), cornerRadius: cornerRadius) shapeLayer.path = path.CGPath shapeLayer.fillColor = UIColor.whiteColor().CGColor shapeLayer.strokeColor = UIColor(red: 35.0 / 255.0, green: 31.0 / 255.0, blue: 32.0 / 255.0, alpha: 0.12).CGColor shapeLayer.shadowColor = UIColor.blackColor().CGColor shapeLayer.shadowOpacity = 0.18 shapeLayer.shadowOffset = CGSizeZero shapeLayer.shadowRadius = shadowSize shapeLayer.cornerRadius = cornerRadius shapeLayer.renderInContext(context!) let createImojiImage = UIImage(named: "Artmoji-Create-Imoji")! UIGraphicsBeginImageContextWithOptions(createImojiImage.size, false, 0.0) IMArtmojiConstants.DefaultBarTintColor.setFill() let bounds = CGRectMake(0, 0, createImojiImage.size.width, createImojiImage.size.height) UIRectFill(bounds) createImojiImage.drawInRect(bounds, blendMode: CGBlendMode.DestinationIn, alpha: 1.0) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() tintedImage!.drawInRect(CGRectMake((size.width - tintedImage!.size.width) / 2.0, (size.height - createImojiImage.size.height) / 2.0, tintedImage!.size.width, tintedImage!.size.height)) let layer = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return layer } // Mark: - UIKit.UIImagePickerController's completion selector func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<Void>) { if error == nil { let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil) activityController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo ] activityController.popoverPresentationController?.sourceView = self.createArtmojiView.shareButton presentViewController(activityController, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Yikes!", message: "There was a problem saving your Artmoji to your photos.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } // Allow images to be saved again self.createArtmojiView.shareButton.userInteractionEnabled = true; } } // MARK: - IMCreateArtmojiViewDelegate extension IMCreateArtmojiViewController: IMCreateArtmojiViewDelegate { public func artmojiView(view: IMCreateArtmojiView, didFinishLoadingImoji imoji: IMImojiObject) { dismissViewControllerAnimated(false, completion: nil) } public func userDidCancelCreateArtmojiView(view: IMCreateArtmojiView, dirty: Bool) { if dirty { let alert = UIAlertController(title: "Start new artmoji?", message: "This will clear your current work.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Keep Editing", style: UIAlertActionStyle.Default, handler: nil)) alert.addAction(UIAlertAction(title: "New", style: UIAlertActionStyle.Default) { alert in self.dismissViewControllerAnimated(false, completion: nil) }) presentViewController(alert, animated: true, completion: nil) } else { dismissViewControllerAnimated(false, completion: nil) } } public func userDidFinishCreatingArtmoji(artmoji: UIImage, view: IMCreateArtmojiView) { // Prevent multiple saves of the same image self.createArtmojiView.shareButton.userInteractionEnabled = false; UIImageWriteToSavedPhotosAlbum(artmoji, self, "image:didFinishSavingWithError:contextInfo:", nil) } public func userDidSelectImojiCollectionButtonFromArtmojiView(view: IMCreateArtmojiView) { let collectionViewController = IMCollectionViewController(session: self.session) collectionViewController.topToolbar.barTintColor = IMArtmojiConstants.DefaultBarTintColor collectionViewController.topToolbar.translucent = false collectionViewController.backButton.setImage(UIImage(named: "Artmoji-Borderless-Cancel"), forState: UIControlState.Normal) collectionViewController.backButton.hidden = false collectionViewController.bottomToolbar.addFlexibleSpace() collectionViewController.bottomToolbar.addToolbarButtonWithType(IMToolbarButtonType.Trending) collectionViewController.bottomToolbar.addFlexibleSpace() #if NOT_PHOTO_EXTENSION let createImojiImage = drawCreateImojiButtonImage().imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) collectionViewController.bottomToolbar.addBarButton(UIBarButtonItem(image: createImojiImage, style: UIBarButtonItemStyle.Plain, target: self, action: "collectionViewControllerCreateImojiButtonTapped")) #endif collectionViewController.bottomToolbar.addToolbarButtonWithType(IMToolbarButtonType.Reactions) collectionViewController.bottomToolbar.addFlexibleSpace() collectionViewController.bottomToolbar.barTintColor = IMArtmojiConstants.DefaultBarTintColor collectionViewController.bottomToolbar.translucent = false collectionViewController.bottomToolbar.delegate = self collectionViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve collectionViewController.collectionView.infiniteScroll = true collectionViewController.collectionView.collectionViewDelegate = self collectionViewController.collectionViewControllerDelegate = self presentViewController(collectionViewController, animated: true) { finished in #if !NOT_PHOTO_EXTENSION collectionViewController.topToolbar.mas_makeConstraints { make in make.top.equalTo()(collectionViewController.view).offset()(50) } collectionViewController.collectionView.mas_makeConstraints { make in make.top.equalTo()(collectionViewController.view).offset()(50) } #endif collectionViewController.bottomToolbar.selectButtonOfType(IMToolbarButtonType.Trending) } } } // MARK: - IMToolbarDelegate extension IMCreateArtmojiViewController: IMToolbarDelegate { public func userDidSelectCategory(category: IMImojiCategoryObject, fromCollectionView collectionView: IMCollectionView) { collectionView.loadImojisFromCategory(category) } public func userDidSelectToolbarButton(buttonType: IMToolbarButtonType) { switch buttonType { case IMToolbarButtonType.Trending: let collectionViewController = presentedViewController as! IMCollectionViewController collectionViewController.collectionView.loadImojiCategoriesWithOptions(IMCategoryFetchOptions.init(classification: IMImojiSessionCategoryClassification.Trending)) break case IMToolbarButtonType.Reactions: let collectionViewController = presentedViewController as! IMCollectionViewController collectionViewController.collectionView.loadImojiCategoriesWithOptions(IMCategoryFetchOptions.init(classification: IMImojiSessionCategoryClassification.Generic)) break case IMToolbarButtonType.Back: dismissViewControllerAnimated(true, completion: nil) break default: break } } } #if NOT_PHOTO_EXTENSION // MARK: - IMCameraViewControllerDelegate extension IMCreateArtmojiViewController: IMCameraViewControllerDelegate { public func userDidCancelCameraViewController(viewController: IMCameraViewController) { viewController.dismissViewControllerAnimated(true, completion: nil) } public func userDidFinishCreatingImoji(imoji: IMImojiObject, fromCameraViewController viewController: IMCameraViewController) { createArtmojiView.addImoji(imoji) } } #endif // MARK: - IMCollectionViewControllerDelegate extension IMCreateArtmojiViewController: IMCollectionViewControllerDelegate { public func backgroundColorForCollectionViewController(collectionViewController: UIViewController) -> UIColor? { return IMArtmojiConstants.DefaultBarTintColor } public func userDidSelectSplash(splashType: IMCollectionViewSplashCellType, fromCollectionView collectionView: IMCollectionView) { switch splashType { case IMCollectionViewSplashCellType.NoResults: let collectionViewController = presentedViewController as! IMCollectionViewController collectionViewController.searchField.becomeFirstResponder(); break; default: break; } } } // MARK: - IMCollectionViewDelegate extension IMCreateArtmojiViewController: IMCollectionViewDelegate { public func userDidSelectImoji(imoji: IMImojiObject, fromCollectionView collectionView: IMCollectionView) { createArtmojiView.addImoji(imoji) } }
9a474f5d711174a7289a02de5aa386cd
46.395833
209
0.722637
false
false
false
false
apple/swift-numerics
refs/heads/main
Sources/RealModule/ElementaryFunctions.swift
apache-2.0
1
//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // // Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// /// A type that has elementary functions available. /// /// An ["elementary function"][elfn] is a function built up from powers, roots, /// exponentials, logarithms, trigonometric functions (sin, cos, tan) and /// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their /// inverses. /// /// Conformance to this protocol means that all of these building blocks are /// available as static functions on the type. /// /// ```swift /// let x: Float = 1 /// let y = Float.sin(x) // 0.84147096 /// ``` /// /// There are three broad families of functions defined by /// `ElementaryFunctions`: /// - Exponential, trigonometric, and hyperbolic functions: /// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`. /// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions: /// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and /// `atanh`. /// - Power and root functions: /// `pow`, `sqrt`, and `root`. /// /// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition /// and subtraction and the `.zero` property are also available. /// /// There are two other protocols that you are more likely to want to use /// directly: /// /// `RealFunctions` refines `ElementaryFunctions` and includes /// additional functions specific to real number types. /// /// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the /// protocol that you will want to use most often for generic code. /// /// See Also: /// /// - `RealFunctions` /// - `Real` /// /// [elfn]: http://en.wikipedia.org/wiki/Elementary_function public protocol ElementaryFunctions: AdditiveArithmetic { /// The [exponential function][wiki] e^x whose base `e` is the base of the /// natural logarithm. /// /// See also `expMinusOne()`, as well as `exp2()` and `exp10()` /// defined for types conforming to `RealFunctions`. /// /// [wiki]: https://en.wikipedia.org/wiki/Exponential_function static func exp(_ x: Self) -> Self /// exp(x) - 1, computed in such a way as to maintain accuracy for small x. /// /// When `x` is close to zero, the expression `.exp(x) - 1` suffers from /// catastrophic cancellation and the result will not have full accuracy. /// The `.expMinusOne(x)` function gives you a means to address this problem. /// /// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x` /// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it /// should actually round to `2*x`. We can get a full-accuracy result by /// using the following instead: /// ``` /// let t = .expMinusOne(x) /// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1 /// ``` /// This re-written expression delivers an accurate result for all values /// of `x`, not just for small values. /// /// See also `exp()`, as well as `exp2()` and `exp10()` defined for types /// conforming to `RealFunctions`. static func expMinusOne(_ x: Self) -> Self /// The [hyperbolic cosine][wiki] of `x`. /// ``` /// e^x + e^-x /// cosh(x) = ------------ /// 2 /// ``` /// /// See also `sinh()`, `tanh()` and `acosh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function static func cosh(_ x: Self) -> Self /// The [hyperbolic sine][wiki] of `x`. /// ``` /// e^x - e^-x /// sinh(x) = ------------ /// 2 /// ``` /// /// See also `cosh()`, `tanh()` and `asinh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function static func sinh(_ x: Self) -> Self /// The [hyperbolic tangent][wiki] of `x`. /// ``` /// sinh(x) /// tanh(x) = --------- /// cosh(x) /// ``` /// /// See also `cosh()`, `sinh()` and `atanh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function static func tanh(_ x: Self) -> Self /// The [cosine][wiki] of `x`. /// /// For real types, `x` may be interpreted as an angle measured in radians. /// /// See also `sin()`, `tan()` and `acos()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Cosine static func cos(_ x: Self) -> Self /// The [sine][wiki] of `x`. /// /// For real types, `x` may be interpreted as an angle measured in radians. /// /// See also `cos()`, `tan()` and `asin()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Sine static func sin(_ x: Self) -> Self /// The [tangent][wiki] of `x`. /// /// For real types, `x` may be interpreted as an angle measured in radians. /// /// See also `cos()`, `sin()` and `atan()`, as well as `atan2(y:x:)` for /// types that conform to `RealFunctions`. /// /// [wiki]: https://en.wikipedia.org/wiki/Tangent static func tan(_ x: Self) -> Self /// The [natural logarithm][wiki] of `x`. /// /// See also `log(onePlus:)`, as well as `log2()` and `log10()` for types /// that conform to `RealFunctions`. /// /// [wiki]: https://en.wikipedia.org/wiki/Logarithm static func log(_ x: Self) -> Self /// log(1 + x), computed in such a way as to maintain accuracy for small x. /// /// See also `log()`, as well as `log2()` and `log10()` for types /// that conform to `RealFunctions`. static func log(onePlus x: Self) -> Self /// The [inverse hyperbolic cosine][wiki] of `x`. /// ``` /// cosh(acosh(x)) ≅ x /// ``` /// See also `asinh()`, `atanh()` and `cosh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function static func acosh(_ x: Self) -> Self /// The [inverse hyperbolic sine][wiki] of `x`. /// ``` /// sinh(asinh(x)) ≅ x /// ``` /// See also `acosh()`, `atanh()` and `sinh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function static func asinh(_ x: Self) -> Self /// The [inverse hyperbolic tangent][wiki] of `x`. /// ``` /// tanh(atanh(x)) ≅ x /// ``` /// See also `acosh()`, `asinh()` and `tanh()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function static func atanh(_ x: Self) -> Self /// The [arccosine][wiki] (inverse cosine) of `x`. /// /// For real types, the result may be interpreted as an angle measured in /// radians. /// ``` /// cos(acos(x)) ≅ x /// ``` /// See also `asin()`, `atan()` and `cos()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions static func acos(_ x: Self) -> Self /// The [arcsine][wiki] (inverse sine) of `x`. /// /// For real types, the result may be interpreted as an angle measured in /// radians. /// ``` /// sin(asin(x)) ≅ x /// ``` /// See also `acos()`, `atan()` and `sin()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions static func asin(_ x: Self) -> Self /// The [arctangent][wiki] (inverse tangent) of `x`. /// /// For real types, the result may be interpreted as an angle measured in /// radians. /// ``` /// tan(atan(x)) ≅ x /// ``` /// See also `acos()`, `asin()` and `tan()`, as well as `atan2(y:x:)` for /// types that conform to `RealArithmetic`. /// /// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions static func atan(_ x: Self) -> Self /// exp(y * log(x)) computed with additional internal precision. /// /// The edge-cases of this function are defined based on the behavior of the /// expression `exp(y log x)`, matching IEEE 754's `powr` operation. /// In particular, this means that if `x` and `y` are both zero, `pow(x,y)` /// is `nan` for real types and `infinity` for complex types, rather than 1. /// /// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined /// in terms of repeated multiplication, and hence returns 1 for this case. /// /// See also `sqrt()` and `root()`. static func pow(_ x: Self, _ y: Self) -> Self /// `x` raised to the nth power. /// /// The edge-cases of this function are defined in terms of repeated /// multiplication or division, rather than exp(n log x). In particular, /// `Float.pow(0, 0)` is 1. /// /// See also `sqrt()` and `root()`. static func pow(_ x: Self, _ n: Int) -> Self /// The [square root][wiki] of `x`. /// /// See also `pow()` and `root()`. /// /// [wiki]: https://en.wikipedia.org/wiki/Square_root static func sqrt(_ x: Self) -> Self /// The nth root of `x`. /// /// See also `pow()` and `sqrt()`. static func root(_ x: Self, _ n: Int) -> Self }
58ded39cfc10410b4db049916579575f
33.198473
80
0.581585
false
false
false
false
boqian2000/swift-algorithm-club
refs/heads/master
DiningPhilosophers/Sources/main.swift
mit
1
// // Swift Dining philosophers problem Algorithm // https://en.wikipedia.org/wiki/Dining_philosophers_problem // // Created by Jacopo Mangiavacchi on 11/02/16. // // import Foundation import Dispatch let numberOfPhilosophers = 4 struct ForkPair { static let forksSemaphore:[DispatchSemaphore] = Array(repeating: DispatchSemaphore(value: 1), count: numberOfPhilosophers) let leftFork: DispatchSemaphore let rightFork: DispatchSemaphore init(leftIndex: Int, rightIndex: Int) { //Order forks by index to prevent deadlock if leftIndex > rightIndex { leftFork = ForkPair.forksSemaphore[leftIndex] rightFork = ForkPair.forksSemaphore[rightIndex] } else { leftFork = ForkPair.forksSemaphore[rightIndex] rightFork = ForkPair.forksSemaphore[leftIndex] } } func pickUp() { //Acquire by starting with the lower index leftFork.wait() rightFork.wait() } func putDown() { //The order does not matter here leftFork.signal() rightFork.signal() } } struct Philosophers { let forkPair: ForkPair let philosopherIndex: Int var leftIndex = -1 var rightIndex = -1 init(philosopherIndex: Int) { leftIndex = philosopherIndex rightIndex = philosopherIndex - 1 if rightIndex < 0 { rightIndex += numberOfPhilosophers } self.forkPair = ForkPair(leftIndex: leftIndex, rightIndex: rightIndex) self.philosopherIndex = philosopherIndex print("Philosopher: \(philosopherIndex) left: \(leftIndex) right: \(rightIndex)") } func run() { while true { print("Acquiring lock for Philosofer: \(philosopherIndex) Left:\(leftIndex) Right:\(rightIndex)") forkPair.pickUp() print("Start Eating Philosopher: \(philosopherIndex)") //sleep(1000) print("Releasing lock for Philosofer: \(philosopherIndex) Left:\(leftIndex) Right:\(rightIndex)") forkPair.putDown() } } } // Layout of the table (P = philosopher, f = fork) for 4 Philosopher // P0 // f3 f0 // P3 P1 // f2 f1 // P2 let globalSem = DispatchSemaphore(value: 0) for i in 0..<numberOfPhilosophers { DispatchQueue.global(qos: .background).async { let p = Philosophers(philosopherIndex: i) p.run() } } //start the thread signaling the semaphore for i in 0..<numberOfPhilosophers { ForkPair.forksSemaphore[i].signal() } //wait forever globalSem.wait()
6e0425f94faf383652e1aa3f3d25f5ec
24
126
0.617196
false
false
false
false
ledwards/ios-yelp
refs/heads/master
Yelp/BusinessCell.swift
mit
1
// // BusinessCell.swift // Yelp // // Created by Lee Edwards on 2/6/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var ratingLabel: UIImageView! @IBOutlet weak var reviewsCountLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! var business: Business! { didSet { nameLabel.text = business.name thumbImageView.setImageWithURL(business.imageURL!) ratingLabel.setImageWithURL(business.ratingImageURL!) reviewsCountLabel.text = "\(business.reviewCount!) Reviews" addressLabel.text = business.address categoriesLabel.text = business.categories distanceLabel.text = business.distance } } override func awakeFromNib() { super.awakeFromNib() thumbImageView.layer.cornerRadius = 5 thumbImageView.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } }
a6c73aaffdcc68296ac7a8e420d0e2dc
28.93617
71
0.662402
false
false
false
false
teaxus/TSAppEninge
refs/heads/master
Source/Basic/Controller/TSImagePicker/TSGeneralHook.swift
mit
1
// // TSGeneralHook.swift // StandardProject // // Created by teaxus on 15/12/31. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit public class TSGeneralHook: UIView { public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func draw(_ rect: CGRect) { self.backgroundColor = UIColor.clear self.layer.cornerRadius = self.frame.size.width / 2.0 self.layer.masksToBounds = true let width = self.frame.size.width let height = self.frame.size.height //// Color Declarations let color2 = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) let color4 = UIColor(red: 0.000, green: 0.478, blue: 1.000, alpha: 1.000) //// C_2 Drawing let c_2Path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: width, height: height)) color2.setFill() c_2Path.fill() //// C_1 Drawing let c_1Path = UIBezierPath(ovalIn: CGRect(x: 3.0/31.0*width, y: 3.0/31.0*height, width: 25.0/31.0*width, height: 25.0/31.0*height)) color4.setFill() c_1Path.fill() //// Bezier Drawing let bezierPath = UIBezierPath() UIColor.blue.setFill() bezierPath.fill() //// Hold Drawing let holdPath = UIBezierPath() holdPath.move(to: CGPoint(x:8.5/31.0*width,y:15.77/31.0*height)) holdPath.addLine(to: CGPoint(x:13.79/31.0*width,y:21.5/31.0*height)) holdPath.addLine(to: CGPoint(x:23.5/31.0*width,y:12.5/31.0*height)) holdPath.lineCapStyle = .round UIColor.white.setStroke() holdPath.lineWidth = 3 holdPath.stroke() } }
325b78a36e148d213b05ce777cc42bb8
30.084746
139
0.589422
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
06-Daily/code/Daily/IBAnimatable/ActivityIndicatorAnimationBallScaleMultiple.swift
gpl-3.0
5
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallScaleMultiple: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let beginTime = CACurrentMediaTime() let beginTimes = [0, 0.2, 0.4] let animation = self.animation for i in 0 ..< 3 { let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.opacity = 0 circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } // MARK: - Setup private extension ActivityIndicatorAnimationBallScaleMultiple { var animation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var scaleAnimation: CABasicAnimation { let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.fromValue = 0 scaleAnimation.toValue = 1 return scaleAnimation } var opacityAnimation: CAKeyframeAnimation { let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = duration opacityAnimation.keyTimes = [0, 0.05, 1] opacityAnimation.values = [0, 1, 0] return opacityAnimation } }
f42c515cba4947470e971d1892798824
30.454545
90
0.681599
false
false
false
false
BenEmdon/swift-algorithm-club
refs/heads/master
Longest Common Subsequence/LongestCommonSubsequence.swift
mit
12
extension String { public func longestCommonSubsequence(_ other: String) -> String { // Computes the length of the lcs using dynamic programming. // Output is a matrix of size (n+1)x(m+1), where matrix[x][y] is the length // of lcs between substring (0, x-1) of self and substring (0, y-1) of other. func lcsLength(_ other: String) -> [[Int]] { // Create matrix of size (n+1)x(m+1). The algorithm needs first row and // first column to be filled with 0. var matrix = [[Int]](repeating: [Int](repeating: 0, count: other.characters.count+1), count: self.characters.count+1) for (i, selfChar) in self.characters.enumerated() { for (j, otherChar) in other.characters.enumerated() { if otherChar == selfChar { // Common char found, add 1 to highest lcs found so far. matrix[i+1][j+1] = matrix[i][j] + 1 } else { // Not a match, propagates highest lcs length found so far. matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j]) } } } // Due to propagation, lcs length is at matrix[n][m]. return matrix } // Backtracks from matrix[n][m] to matrix[1][1] looking for chars that are // common to both strings. func backtrack(_ matrix: [[Int]]) -> String { var i = self.characters.count var j = other.characters.count // charInSequence is in sync with i so we can get self[i] var charInSequence = self.endIndex var lcs = String() while i >= 1 && j >= 1 { // Indicates propagation without change: no new char was added to lcs. if matrix[i][j] == matrix[i][j - 1] { j -= 1 } // Indicates propagation without change: no new char was added to lcs. else if matrix[i][j] == matrix[i - 1][j] { i -= 1 // As i was decremented, move back charInSequence. charInSequence = self.index(before: charInSequence) } // Value on the left and above are different than current cell. // This means 1 was added to lcs length (line 17). else { i -= 1 j -= 1 charInSequence = self.index(before: charInSequence) lcs.append(self[charInSequence]) } } // Due to backtrack, chars were added in reverse order: reverse it back. // Append and reverse is faster than inserting at index 0. return String(lcs.characters.reversed()) } // Combine dynamic programming approach with backtrack to find the lcs. return backtrack(lcsLength(other)) } }
44b53dbf15c0da63463a55764994fdf1
36.371429
123
0.59289
false
false
false
false
danielallsopp/Charts
refs/heads/master
Source/ChartsRealm/Data/RealmBarLineScatterCandleBubbleDataSet.swift
apache-2.0
1
// // RealmBarLineScatterCandleBubbleDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation #if NEEDS_CHARTS import Charts #endif import Realm import Realm.Dynamic public class RealmBarLineScatterCandleBubbleDataSet: RealmBaseDataSet, IBarLineScatterCandleBubbleChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors public var highlightColor = NSUIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0) public var highlightLineWidth = CGFloat(0.5) public var highlightLineDashPhase = CGFloat(0.0) public var highlightLineDashLengths: [CGFloat]? // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBarLineScatterCandleBubbleDataSet copy.highlightColor = highlightColor copy.highlightLineWidth = highlightLineWidth copy.highlightLineDashPhase = highlightLineDashPhase copy.highlightLineDashLengths = highlightLineDashLengths return copy } }
a185625981ef7155d4fd9fdf808eb2c1
28.772727
110
0.726718
false
false
false
false
lyimin/EyepetizerApp
refs/heads/master
EyepetizerApp/EyepetizerApp/Controllers/DiscoverController/EYEDiscoverDetailShareController.swift
mit
1
// // EYEDiscoverDetailShareController.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/30. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit import Alamofire class EYEDiscoverDetailShareController: UIViewController, LoadingPresenter { var loaderView : EYELoaderView! override func viewDidLoad() { super.viewDidLoad() // 添加collectionview self.view.addSubview(collectionView) // 初始化url setupLoaderView() // 获取数据 getData(params: ["categoryId": categoryId]) setLoaderViewHidden(false) // 上拉加载更多 collectionView.footerViewPullToRefresh { [unowned self] in if let url = self.nextURL { self.getData(url, params: nil) } } } convenience init(categoryId : Int) { self.init() self.categoryId = categoryId } //MARK: --------------------------- Private Methods -------------------------- private func getData(api : String = EYEAPIHeaper.API_Discover_Share, params:[String: AnyObject]? = nil) { Alamofire.request(.GET, api, parameters: params).responseSwiftyJSON ({ [unowned self](request, response, json, error) -> Void in // 字典转模型 刷新数据 if json != .null && error == nil { let dataDict = json.rawValue as! NSDictionary // 下一个url self.nextURL = dataDict["nextPageUrl"] as? String let itemArray = dataDict["videoList"] as! NSArray // 字典转模型 let list = itemArray.map({ (dict) -> ItemModel in ItemModel(dict: dict as? NSDictionary) }) if let _ = params { self.modelArray = list } else { self.modelArray.appendContentsOf(list) self.collectionView.footerViewEndRefresh() } // 刷新数据 self.collectionView.reloadData() } self.setLoaderViewHidden(true) }) } //MARK: --------------------------- Getter and Setter -------------------------- // 分类id private var categoryId : Int! = 0 // 按时间排序collection private lazy var collectionView : EYECollectionView = { let rect = CGRect(x: 0, y: 0, width: self.view.width, height: UIConstant.SCREEN_HEIGHT-UIConstant.UI_TAB_HEIGHT-UIConstant.UI_NAV_HEIGHT) var collectionView = EYECollectionView(frame: rect, collectionViewLayout:EYECollectionLayout()) collectionView.delegate = self collectionView.dataSource = self return collectionView }() // 时间排序模型数据 private var modelArray : [ItemModel] = [ItemModel]() private var nextURL : String? } extension EYEDiscoverDetailShareController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return modelArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EYEChoiceCell.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceCell cell.model = modelArray[indexPath.row] return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if self.parentViewController is EYEDiscoverDetailController { (parentViewController as! EYEDiscoverDetailController).selectCell = collectionView.cellForItemAtIndexPath(indexPath) as! EYEChoiceCell } let model = modelArray[indexPath.row] self.navigationController?.pushViewController(EYEVideoDetailController(model: model), animated: true) } }
e23c68809e9c5a10144a102c6c2c8cc7
37.028846
146
0.611884
false
false
false
false
khizkhiz/swift
refs/heads/master
test/SILGen/protocols.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s //===----------------------------------------------------------------------===// // Calling Existential Subscripts //===----------------------------------------------------------------------===// protocol SubscriptableGet { subscript(a : Int) -> Int { get } } protocol SubscriptableGetSet { subscript(a : Int) -> Int { get set } } var subscriptableGet : SubscriptableGet var subscriptableGetSet : SubscriptableGetSet func use_subscript_rvalue_get(i : Int) -> Int { return subscriptableGet[i] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_rvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols16subscriptableGetPS_16SubscriptableGet_ : $*SubscriptableGet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter.1 // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_get(i : Int) -> Int { return subscriptableGetSet[i] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols19subscriptableGetSetPS_19SubscriptableGetSet_ : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter.1 // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_set(i : Int) { subscriptableGetSet[i] = i } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols19subscriptableGetSetPS_19SubscriptableGetSet_ : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Subscripts //===----------------------------------------------------------------------===// func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(generic : T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_rvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK-NEXT: destroy_addr %0 func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(generic: inout T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T, var, name "generic" // CHECK: [[PB:%.*]] = project_box [[INOUTBOX]] // CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr [[PB]] to [initialization] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter.1 // CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]]) // CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T // CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T // CHECK-NEXT: copy_addr [[PB]] to %0 : $*T // CHECK-NEXT: strong_release [[INOUTBOX]] : $@box T // CHECK: return [[APPLYRESULT]] func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(generic: inout T, idx : Int) { generic[idx] = idx } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T // CHECK: [[PB:%.*]] = project_box [[INOUTBOX]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[PB]]) // CHECK: strong_release [[INOUTBOX]] //===----------------------------------------------------------------------===// // Calling Existential Properties //===----------------------------------------------------------------------===// protocol PropertyWithGetter { var a : Int { get } } protocol PropertyWithGetterSetter { var b : Int { get set } } var propertyGet : PropertyWithGetter var propertyGetSet : PropertyWithGetterSetter func use_property_rvalue_get() -> Int { return propertyGet.a } // CHECK-LABEL: sil hidden @{{.*}}use_property_rvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols11propertyGetPS_18PropertyWithGetter_ : $*PropertyWithGetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]] // CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[COPY]]) func use_property_lvalue_get() -> Int { return propertyGetSet.b } // CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols14propertyGetSetPS_24PropertyWithGetterSetter_ : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]]) func use_property_lvalue_set(x : Int) { propertyGetSet.b = x } // CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols14propertyGetSetPS_24PropertyWithGetterSetter_ : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Properties //===----------------------------------------------------------------------===// func use_property_archetype_rvalue_get<T : PropertyWithGetter>(generic : T) -> Int { return generic.a } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_rvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter.1 // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] // CHECK-NEXT: dealloc_stack [[STACK]] // CHECK-NEXT: destroy_addr %0 func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(generic : T) -> Int { return generic.b } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK-NEXT: destroy_addr %0 func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(generic: inout T, v : Int) { generic.b = v } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T // CHECK: [[PB:%.*]] = project_box [[INOUTBOX]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, [[PB]]) // CHECK: strong_release [[INOUTBOX]] //===----------------------------------------------------------------------===// // Calling Initializers //===----------------------------------------------------------------------===// protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_TF9protocols27use_initializable_archetype func use_initializable_archetype<T: Initializable>(t: T, i: Int) { // CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[T_RESULT]] : $*T // CHECK: dealloc_stack [[T_RESULT]] : $*T // CHECK: destroy_addr [[VAR_0:%[0-9]+]] : $*T // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() T(int: i) } // CHECK: sil hidden @_TF9protocols29use_initializable_existential func use_initializable_existential(im: Initializable.Type, i: Int) { // CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable // CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator.1, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable // CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable im.init(int: i) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } //===----------------------------------------------------------------------===// // Protocol conformance and witness table generation //===----------------------------------------------------------------------===// class ClassWithGetter : PropertyWithGetter { var a: Int { get { return 42 } } } // Make sure we are generating a protocol witness that calls the class method on // ClassWithGetter. // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9protocols15ClassWithGetterS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed ClassWithGetter) -> Int { // CHECK: bb0([[C:%.*]] : $*ClassWithGetter): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetter // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]] // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter.1 : (ClassWithGetter) -> () -> Int , $@convention(method) (@guaranteed ClassWithGetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: strong_release [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter { var a: Int { get { return 1 } set {} } var b: Int { get { return 2 } set {} } } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_g1bSi : $@convention(witness_method) (@in_guaranteed ClassWithGetterSetter) -> Int { // CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetterSetter // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]] // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter.1 : (ClassWithGetterSetter) -> () -> Int , $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: strong_release [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return // Stored variables fulfilling property requirements // class ClassWithStoredProperty : PropertyWithGetter { var a : Int = 0 // Make sure that accesses go through the generated accessors for classes. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @{{.*}}ClassWithStoredProperty{{.*}}methodUsingProperty // CHECK: bb0([[ARG:%.*]] : $ClassWithStoredProperty): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NOT: strong_retain // CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter.1 : (ClassWithStoredProperty) -> () -> Int , $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]]) // CHECK-NOT: strong_release // CHECK-NEXT: return [[RESULT]] : $Int } struct StructWithStoredProperty : PropertyWithGetter { var a : Int // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @{{.*}}StructWithStoredProperty{{.*}}methodUsingProperty // CHECK: bb0(%0 : $StructWithStoredProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a // CHECK-NEXT: return %2 : $Int } // Make sure that we generate direct function calls for out struct protocol // witness since structs don't do virtual calls for methods. // // *NOTE* Even though at first glance the copy_addr looks like a leak // here, StructWithStoredProperty is a trivial struct implying that no // leak is occurring. See the test with StructWithStoredClassProperty // that makes sure in such a case we don't leak. This is due to the // thunking code being too dumb but it is harmless to program // correctness. // // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9protocols24StructWithStoredPropertyS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed StructWithStoredProperty) -> Int { // CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredProperty // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFV9protocols24StructWithStoredPropertyg1aSi : $@convention(method) (StructWithStoredProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return class C {} // Make sure that if the getter has a class property, we pass it in // in_guaranteed and don't leak. struct StructWithStoredClassProperty : PropertyWithGetter { var a : Int var c: C = C() // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @{{.*}}StructWithStoredClassProperty{{.*}}methodUsingProperty // CHECK: bb0(%0 : $StructWithStoredClassProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a // CHECK-NEXT: return %2 : $Int } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9protocols29StructWithStoredClassPropertyS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed StructWithStoredClassProperty) -> Int { // CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredClassProperty // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFV9protocols29StructWithStoredClassPropertyg1aSi : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: release_value [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return // rdar://22676810 protocol ExistentialProperty { var p: PropertyWithGetterSetter { get set } } func testExistentialPropertyRead<T: ExistentialProperty>(t: inout T) { let b = t.p.b } // CHECK-LABEL: sil hidden @_TF9protocols27testExistentialPropertyRead // CHECK: [[T:%.*]] = alloc_box $T // CHECK: [[PB:%.*]] = project_box [[T]] // CHECK: copy_addr %0 to [initialization] [[PB]] : $*T // CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter // CHECK: [[T_TEMP:%.*]] = alloc_stack $T // CHECK: copy_addr [[PB]] to [initialization] [[T_TEMP]] : $*T // CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter.1 : // CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]]) // CHECK-NEXT: destroy_addr [[T_TEMP]] // CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]] // CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]] // CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]]) // CHECK-NEXT: destroy_addr [[T0]] // CHECK-NOT: witness_method // CHECK: return // CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWC9protocols15ClassWithGetterS_18PropertyWithGetterS_FS1_g1aSi // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols { // CHECK-NEXT: method #PropertyWithGetterSetter.b!getter.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_g1bSi // CHECK-NEXT: method #PropertyWithGetterSetter.b!setter.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_s1bSi // CHECK-NEXT: method #PropertyWithGetterSetter.b!materializeForSet.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_m1bSi // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWC9protocols21ClassWithGetterSetterS_18PropertyWithGetterS_FS1_g1aSi // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWV9protocols24StructWithStoredPropertyS_18PropertyWithGetterS_FS1_g1aSi // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWV9protocols29StructWithStoredClassPropertyS_18PropertyWithGetterS_FS1_g1aSi // CHECK-NEXT: }
5437af9c6ed00555d1a40d54e725bbb0
47.278302
248
0.639814
false
false
false
false
RemyDCF/tpg-offline
refs/heads/master
tpg offline/Departures/Callout.swift
mit
1
import Mapbox class CustomCalloutView: UIView, MGLCalloutView { var representedObject: MGLAnnotation // Allow the callout to remain open during panning. let dismissesAutomatically: Bool = false let isAnchoredToAnnotation: Bool = true // https://github.com/mapbox/mapbox-gl-native/issues/9228 override var center: CGPoint { set { var newCenter = newValue newCenter.y -= bounds.midY super.center = newCenter } get { return super.center } } lazy var leftAccessoryView = UIView() /* unused */ lazy var rightAccessoryView = UIView() /* unused */ weak var delegate: MGLCalloutViewDelegate? let tipHeight: CGFloat = 10.0 let tipWidth: CGFloat = 20.0 let mainBody: UIStackView let titleLabel: UILabel let subTitleLabel: UILabel private lazy var backgroundView: UIView = { let view = UIView() view.backgroundColor = App.cellBackgroundColor view.layer.cornerRadius = 4.0 return view }() required init(representedObject: MGLAnnotation) { self.representedObject = representedObject self.titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 8)) self.titleLabel.text = representedObject.title ?? "" self.titleLabel.numberOfLines = 0 self.titleLabel.textColor = App.textColor self.subTitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 8)) self.subTitleLabel.text = representedObject.subtitle ?? "" self.subTitleLabel.font = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize) self.subTitleLabel.numberOfLines = 0 self.subTitleLabel.textColor = App.textColor self.mainBody = UIStackView() self.mainBody.alignment = .fill self.mainBody.distribution = .fill self.mainBody.axis = .vertical self.mainBody.translatesAutoresizingMaskIntoConstraints = false self.mainBody.widthAnchor.constraint(equalToConstant: 150).isActive = true self.mainBody.addArrangedSubview(self.titleLabel) self.mainBody.addArrangedSubview(self.subTitleLabel) self.mainBody.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) self.mainBody.isLayoutMarginsRelativeArrangement = true super.init(frame: .zero) backgroundColor = .clear mainBody.backgroundColor = .darkGray mainBody.tintColor = .white mainBody.layer.cornerRadius = 4.0 pinBackground(backgroundView, to: mainBody) addSubview(mainBody) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func pinBackground(_ view: UIView, to stackView: UIStackView) { view.translatesAutoresizingMaskIntoConstraints = false stackView.insertSubview(view, at: 0) view.pin(to: stackView) } // MARK: - MGLCalloutView API func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) { view.addSubview(self) // Prepare title label. //mainBody.setTitle(representedObject.title!, for: .normal) // Prepare our frame, adding extra space at the bottom for the tip. let size = mainBody.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) let frameWidth: CGFloat = size.width let frameHeight: CGFloat = size.height + tipHeight let frameOriginX = rect.origin.x + (rect.size.width/2.0) - (frameWidth/2.0) let frameOriginY = rect.origin.y - frameHeight frame = CGRect(x: frameOriginX, y: frameOriginY, width: frameWidth, height: frameHeight) mainBody.backgroundColor = .white if animated { alpha = 0 UIView.animate(withDuration: 0.2) { [weak self] in self?.alpha = 1 } } } func dismissCallout(animated: Bool) { if superview != nil { if animated { UIView.animate(withDuration: 0.2, animations: { [weak self] in self?.alpha = 0 }, completion: { [weak self] _ in self?.removeFromSuperview() }) } else { removeFromSuperview() } } } // MARK: - Callout interaction handlers func isCalloutTappable() -> Bool { if let delegate = delegate { if delegate.responds(to: #selector(MGLCalloutViewDelegate.calloutViewShouldHighlight)) { return delegate.calloutViewShouldHighlight!(self) } } return false } @objc func calloutTapped() { if isCalloutTappable(), delegate!.responds(to: #selector(MGLCalloutViewDelegate.calloutViewTapped)) { delegate!.calloutViewTapped!(self) } } // MARK: - Custom view styling override func draw(_ rect: CGRect) { // Draw the pointed tip at the bottom. let fillColor: UIColor = App.cellBackgroundColor let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0) let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0), y: rect.origin.y + rect.size.height) let heightWithoutTip = rect.size.height - tipHeight - 1 let currentContext = UIGraphicsGetCurrentContext()! let tipPath = CGMutablePath() tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip)) tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y)) tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip)) tipPath.closeSubpath() fillColor.setFill() currentContext.addPath(tipPath) currentContext.fillPath() } } public extension UIView { func pin(to view: UIView) { NSLayoutConstraint.activate([ leadingAnchor.constraint(equalTo: view.leadingAnchor), trailingAnchor.constraint(equalTo: view.trailingAnchor), topAnchor.constraint(equalTo: view.topAnchor), bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } }
494e95c1ac575ccf5c257e583e6ee65c
30.61413
84
0.678013
false
false
false
false
aredotna/case
refs/heads/master
ios/Add to Are.na/ShareViewController.swift
mit
1
// // ShareViewController.swift // Add to Are.na // // Created by Charles Broskoski on 1/30/18. // Copyright © 2018 When It Changed, Inc. All rights reserved. // import UIKit import Social import MobileCoreServices import Apollo import AWSCore import AWSS3 extension NSItemProvider { var isURL: Bool { return hasItemConformingToTypeIdentifier(kUTTypeURL as String) } var isText: Bool { return hasItemConformingToTypeIdentifier(kUTTypeText as String) } var isImage: Bool { return hasItemConformingToTypeIdentifier(kUTTypeImage as String) } } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } class ShareViewController: SLComposeServiceViewController { // For fetching data via Apollo private var apollo: ApolloClient? private var authToken = String() private var appToken = String() // Label for placeholder when text field is empty var placeholderLabel : UILabel! // Arrays that hold fetched channels private var recentConnections = [Channel]() private var userChannels = [Channel]() // Values to hold the block that will be created private var selectedChannel: Channel! private var urlString: String? private var textString: String? private var sourceURL: String? private var imageString: String? private var customTitle = String() // Values for uploading images to S3 private var groupID = String() private var AWSBucket = String() private var AWSPoolId = String() private var AWSTransferKey = String() override func viewDidLoad() { super.viewDidLoad() setConfig() setupUI() getShareContext() if #available(iOS 13.0, *) { // Always adopt a light interface style. overrideUserInterfaceStyle = .light } } override func presentationAnimationDidFinish() { getDefaults() setupApollo() fetchRecentConnections() } override func isContentValid() -> Bool { if ((selectedChannel != nil) && (selectedChannel.id != nil)) { return true } return false } override func didSelectPost() { var mutation = CreateBlockMutationMutation(channel_ids: [GraphQLID(describing: selectedChannel.id!)], title: self.customTitle, description: self.contentText, source_url: urlString) // Content is text if ((urlString) == nil && (self.contentText) != nil && (self.imageString) == nil) { mutation = CreateBlockMutationMutation(channel_ids: [GraphQLID(describing: selectedChannel.id!)], title: self.customTitle, content: self.contentText, description: "") } // If content is not an image if ((self.imageString) == nil) { apollo?.perform(mutation: mutation) { (result, error) in self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } // If content is an image, then upload the image and create a block } else { let bucket = self.AWSBucket let url = URL(string: self.imageString!)! let data = try? Data(contentsOf: url) let uuid = NSUUID().uuidString.lowercased() let key = "\(uuid)/\(url.lastPathComponent)" let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: self.AWSPoolId) let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider) configuration?.sharedContainerIdentifier = self.groupID AWSServiceManager.default().defaultServiceConfiguration = configuration AWSS3TransferUtility.register(with: configuration!, forKey: self.AWSTransferKey) let transferUtility = AWSS3TransferUtility.s3TransferUtility(forKey: self.AWSTransferKey) let expression = AWSS3TransferUtilityUploadExpression() expression.setValue("public-read", forRequestHeader: "x-amz-acl") var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock? completionHandler = { (task, error) -> Void in DispatchQueue.main.async(execute: { let url = URL(string: "https://s3.amazonaws.com/")?.appendingPathComponent(bucket) let publicURL = url?.appendingPathComponent(key).absoluteString // Create image in Are.na mutation.source_url = publicURL self.apollo?.perform(mutation: mutation) { (result, error) in } // Remove reference to transferUtility AWSS3TransferUtility.remove(forKey: self.AWSTransferKey) self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) }) } transferUtility.uploadData( data!, bucket: bucket, key: key, contentType: "image/png", expression: expression, completionHandler: completionHandler).continueWith { (task) -> AnyObject! in if let error = task.error { print("Error: \(error.localizedDescription)") self.showAlert(message: "Error uploading file \(error.localizedDescription)", title: "Error") self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } return nil; } } } override func configurationItems() -> [Any]! { if let channel = SLComposeSheetConfigurationItem() { channel.title = "Channel" channel.value = selectedChannel?.title channel.valuePending = selectedChannel?.title == nil channel.tapHandler = { let vc = ShareSelectViewController() vc.recentConnections = self.recentConnections vc.userChannels = self.userChannels vc.delegate = self self.pushConfigurationViewController(vc) } let customTitle = SLComposeSheetConfigurationItem() customTitle?.title = "Title" customTitle?.value = self.customTitle customTitle?.tapHandler = { let vc = ShareTitleViewController() vc.currentValue = self.customTitle vc.delegate = self self.pushConfigurationViewController(vc) } return [customTitle, channel] } return nil } // Handle empty textView by showing the placeholder override func textViewDidChange(_ textView: UITextView) { super.textViewDidChange(textView) placeholderLabel.isHidden = !textView.text.isEmpty } // Set values needed for S3 transfer private func setConfig() -> Any { guard let path = Bundle.main.path(forResource: "Info", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) else { return false } self.groupID = dict.value(forKey: "Group ID") as! String self.AWSBucket = dict.value(forKey: "AWS Bucket") as! String self.AWSPoolId = dict.value(forKey: "AWS Cognito Pool ID") as! String self.AWSTransferKey = dict.value(forKey: "AWS Transfer Key") as! String return true } // "CSS" private func setupUI() { let imageView = UIImageView(image: UIImage(named: "logo.png")) imageView.contentMode = .scaleAspectFit navigationItem.titleView = imageView navigationController?.navigationBar.topItem?.titleView = imageView navigationController?.navigationBar.tintColor = UIColor.black navigationController?.navigationBar.backgroundColor = UIColor.white navigationController?.view.backgroundColor = UIColor.white navigationController?.navigationBar.topItem?.rightBarButtonItem?.title = "Connect" placeholderLabel = UILabel() placeholderLabel.text = "Description" placeholderLabel.font = UIFont.italicSystemFont(ofSize: (textView.font?.pointSize)!) placeholderLabel.sizeToFit() textView.addSubview(placeholderLabel) placeholderLabel.frame.origin = CGPoint(x: 5, y: (textView.font?.pointSize)! / 2) placeholderLabel.textColor = UIColor.lightGray placeholderLabel.isHidden = !textView.text.isEmpty } // Get tokens used for Apollo private func getDefaults() { let userDefaults = UserDefaults(suiteName: self.groupID) if let authToken = userDefaults?.string(forKey: "authToken") { self.authToken = authToken } if let appToken = userDefaults?.string(forKey: "appToken") { self.appToken = appToken } } // Set headers on Apollo client private func setupApollo() { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = [ "X-APP-TOKEN": self.appToken, "X-AUTH-TOKEN": self.authToken ] let url = URL(string: "https://api.are.na/graphql")! let transport = HTTPNetworkTransport(url: url, configuration: configuration) self.apollo = ApolloClient(networkTransport: transport) } // Fetch both recent connections and all channels for the user private func fetchRecentConnections() { self.apollo?.fetch(query: RecentConnectionsQuery()) { (result, error) in if let error = error { self.showAlert(message: "Please log in through the Are.na app and try again.", title: "Access Denied") NSLog("Error fetching connections: \(error.localizedDescription)") } let recentConnections = result?.data?.me?.recentConnections recentConnections?.forEach { let channel = Channel() channel.id = $0?.id channel.title = $0?.title channel.visibility = $0?.visibility self.recentConnections.append(channel) } let allChannels = result?.data?.me?.contents allChannels?.forEach { let channel = Channel() channel.id = $0?.id channel.title = $0?.title channel.visibility = $0?.visibility self.userChannels.append(channel) } self.selectedChannel = self.recentConnections.first self.reloadConfigurationItems() self.validateContent() } } // Figure out what kind of content we are dealing with private func getShareContext() { let extensionItem = extensionContext?.inputItems[0] as! NSExtensionItem let contentTypeURL = kUTTypeURL as String let contentTypeText = kUTTypeText as String let contentTypeImage = kUTTypeImage as String for attachment in extensionItem.attachments as! [NSItemProvider] { if attachment.isImage { attachment.loadItem(forTypeIdentifier: contentTypeImage, options: nil, completionHandler: { (results, error) in if let image = results as? URL { self.imageString = image.absoluteString self.customTitle = image.lastPathComponent } else if let image = results as? UIImage { if let data = UIImagePNGRepresentation(image) { let filename = getDocumentsDirectory().appendingPathComponent("screenshot.png") try? data.write(to: filename) self.imageString = filename.absoluteString self.customTitle = filename.lastPathComponent } } }) } if attachment.isURL { // if the attachment is a url, clear the default text field. self.customTitle = self.contentText self.textView.text = "" placeholderLabel.isHidden = false attachment.loadItem(forTypeIdentifier: contentTypeURL, options: nil, completionHandler: { (results, error) in let url = results as! URL? self.urlString = url!.absoluteString }) } if attachment.isText { attachment.loadItem(forTypeIdentifier: contentTypeText, options: nil, completionHandler: { (results, error) in let text = results as! String self.textString = text _ = self.isContentValid() }) } } } // Show an alert on the event of an error private func showAlert(message: String, title: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: .default)) self.present(alert, animated: true, completion: nil) } } extension ShareViewController: ShareSelectViewControllerDelegate { func selected(channel: Channel) { selectedChannel = channel reloadConfigurationItems() popConfigurationViewController() } } extension ShareViewController: ShareTitleViewControllerDelegate { func titleFinshedEditing(newValue: String) { self.customTitle = newValue reloadConfigurationItems() popConfigurationViewController() } }
d61d43f2bcf87b1da39722e16c8faa11
39.944606
188
0.604671
false
true
false
false
grandiere/box
refs/heads/master
box/View/Handler/VHandler.swift
mit
1
import UIKit class VHandler:VView { private weak var controller:CHandler! private(set) weak var viewField:VHandlerField! private(set) weak var labelWarning:UILabel! private weak var layoutFieldLeft:NSLayoutConstraint! private weak var layoutButtonLeft:NSLayoutConstraint! private let kTitleHeight:CGFloat = 120 private let kTitleMarginHorizontal:CGFloat = 10 private let kFieldHeight:CGFloat = 50 private let kFieldWidth:CGFloat = 160 private let kWarningHeight:CGFloat = 90 private let kButtonWidth:CGFloat = 100 private let kButtonHeight:CGFloat = 34 override init(controller:CController) { let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:19), NSForegroundColorAttributeName:UIColor.white] let attributesSubtitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:16), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.7)] let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("VHandler_labelTitle", comment:""), attributes:attributesTitle) let stringSubtitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("VHandler_labelSubtitle", comment:""), attributes:attributesSubtitle) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringSubtitle) super.init(controller:controller) self.controller = controller as? CHandler let viewField:VHandlerField = VHandlerField( controller:self.controller) self.viewField = viewField let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.textAlignment = NSTextAlignment.center labelTitle.backgroundColor = UIColor.clear labelTitle.numberOfLines = 0 labelTitle.attributedText = mutableString let labelWarning:UILabel = UILabel() labelWarning.isHidden = true labelWarning.isUserInteractionEnabled = false labelWarning.translatesAutoresizingMaskIntoConstraints = false labelWarning.backgroundColor = UIColor.clear labelWarning.textAlignment = NSTextAlignment.center labelWarning.font = UIFont.regular(size:15) labelWarning.textColor = UIColor(white:1, alpha:0.6) labelWarning.text = NSLocalizedString("VHandler_labelWarning", comment:"") self.labelWarning = labelWarning let buttonDone:UIButton = UIButton() buttonDone.translatesAutoresizingMaskIntoConstraints = false buttonDone.clipsToBounds = true buttonDone.backgroundColor = UIColor.gridBlue buttonDone.setTitleColor( UIColor.white, for:UIControlState.normal) buttonDone.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonDone.setTitle( NSLocalizedString("VHandler_buttonDone", comment:""), for:UIControlState.normal) buttonDone.titleLabel!.font = UIFont.bold(size:14) buttonDone.layer.cornerRadius = kButtonHeight / 2.0 buttonDone.addTarget( self, action:#selector(actionDone(sender:)), for:UIControlEvents.touchUpInside) addSubview(labelTitle) addSubview(labelWarning) addSubview(viewField) addSubview(buttonDone) NSLayoutConstraint.topToTop( view:labelTitle, toView:self) NSLayoutConstraint.height( view:labelTitle, constant:kTitleHeight) NSLayoutConstraint.equalsHorizontal( view:labelTitle, toView:self) NSLayoutConstraint.topToBottom( view:viewField, toView:labelTitle) NSLayoutConstraint.height( view:viewField, constant:kFieldHeight) NSLayoutConstraint.width( view:viewField, constant:kFieldWidth) layoutFieldLeft = NSLayoutConstraint.leftToLeft( view:viewField, toView:self) NSLayoutConstraint.topToBottom( view:labelWarning, toView:viewField) NSLayoutConstraint.height( view:labelWarning, constant:kWarningHeight) NSLayoutConstraint.equalsHorizontal( view:labelWarning, toView:self) NSLayoutConstraint.topToBottom( view:buttonDone, toView:labelWarning) NSLayoutConstraint.height( view:buttonDone, constant:kButtonHeight) NSLayoutConstraint.width( view:buttonDone, constant:kButtonWidth) layoutButtonLeft = NSLayoutConstraint.leftToLeft( view:buttonDone, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainField:CGFloat = width - kFieldWidth let fieldLeft:CGFloat = remainField / 2.0 layoutFieldLeft.constant = fieldLeft let remainButton:CGFloat = width - kButtonWidth let buttonLeft:CGFloat = remainButton / 2.0 layoutButtonLeft.constant = buttonLeft super.layoutSubviews() } //MARK: actions func actionDone(sender button:UIButton) { UIApplication.shared.keyWindow!.endEditing(true) controller.back() } }
c3963c5b88e47d76f893f50b4cd05f82
34.785276
82
0.647694
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Client/Helpers/UserActivityHandler.swift
mpl-2.0
1
/* 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 import CoreSpotlight import MobileCoreServices import WebKit private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing" private let searchableIndex = CSSearchableIndex(name: "firefox") class UserActivityHandler { private var tabObservers: TabObservers! init() { self.tabObservers = registerFor( .didLoseFocus, .didGainFocus, .didLoadPageMetadata, // .didLoadFavicon, // only useful when we fix Bug 1390200. .didClose, queue: .main) } deinit { unregister(tabObservers) } class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) { searchableIndex.deleteAllSearchableItems(completionHandler: completionHandler) } } extension UserActivityHandler: TabEventHandler { func tabDidGainFocus(_ tab: Tab) { tab.userActivity?.becomeCurrent() } func tabDidLoseFocus(_ tab: Tab) { tab.userActivity?.resignCurrent() } func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) { guard let url = tab.canonicalURL else { tabDidLoseFocus(tab) tab.userActivity = nil return } tab.userActivity?.invalidate() let userActivity = NSUserActivity(activityType: browsingActivityType) let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeHTML as String) userActivity.title = metadata.title userActivity.webpageURL = url userActivity.keywords = metadata.keywords userActivity.isEligibleForSearch = false userActivity.isEligibleForHandoff = true attributeSet.contentURL = url attributeSet.title = metadata.title attributeSet.contentDescription = metadata.description userActivity.contentAttributeSet = attributeSet tab.userActivity = userActivity userActivity.becomeCurrent() } func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with data: Data?) { guard let url = tab.canonicalURL, let userActivity = tab.userActivity, let attributeSet = userActivity.contentAttributeSet, !tab.isPrivate else { return } attributeSet.thumbnailData = data let searchableItem = CSSearchableItem(uniqueIdentifier: url.absoluteString, domainIdentifier: "webpages", attributeSet: attributeSet) searchableIndex.indexSearchableItems([searchableItem]) userActivity.needsSave = true } func tabDidClose(_ tab: Tab) { guard let userActivity = tab.userActivity else { return } tab.userActivity = nil userActivity.invalidate() } }
e99d8f5e52919ab2c40e6929b8da8b4a
30.816327
141
0.642399
false
false
false
false
salesforce-ux/design-system-ios
refs/heads/master
Demo-Swift/slds-sample-app/demo/views/AccountHeaderView.swift
bsd-3-clause
1
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class AccountHeaderView: UIView { var headerIcon = UIImageView() var headerTitle = UILabel() //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func draw(_ rect: CGRect) { let aPath = UIBezierPath() aPath.move(to: CGPoint(x:0, y:self.frame.height)) aPath.addLine(to: CGPoint(x:self.frame.width, y:self.frame.height)) aPath.close() aPath.lineWidth = 1.0 UIColor.sldsBorderColor(.colorBorderSeparatorAlt2).set() aPath.stroke() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override init (frame : CGRect) { super.init(frame : frame) self.makeLayout() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– convenience init () { self.init(frame:CGRect.zero) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func makeLayout() { self.backgroundColor = UIColor.sldsBackgroundColor(.colorBackground) headerIcon = UIImageView(image: UIImage.sldsStandardIcon(.account, withSize: SLDSSquareIconMedium)) self.addSubview(headerIcon) self.constrainChild(headerIcon, xAlignment: .left, yAlignment: .top, xOffset: 10, yOffset: 10) headerTitle = UILabel() headerTitle.font = UIFont.sldsFont(.regular, with: .large) headerTitle.textColor = UIColor.sldsTextColor(.colorTextDefault) self.addSubview(headerTitle) headerTitle.constrainRightOf(headerIcon, yAlignment: .top, xOffset: 15) } }
b0fc12b1bb984ee7b10d29c8dca3fb90
32.457143
97
0.442784
false
false
false
false
cotkjaer/Silverback
refs/heads/master
Silverback/UITextView.swift
mit
1
// // UITextView.swift // Silverback // // Created by Christian Otkjær on 10/01/16. // Copyright © 2016 Christian Otkjær. All rights reserved. // import UIKit //MARK: - Auto update extension UITextView { public var preferredHeightForCurrentWidth : CGFloat { return heightThatFits(width: bounds.width) } public func heightThatFits(width fixedWidth: CGFloat) -> CGFloat { let boundingSize = CGSize(width: fixedWidth, height: CGFloat.max) let bestFit = sizeThatFits(boundingSize) return bestFit.height // let fixedWidth = textView.frame.size.width // textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) // let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) // var newFrame = textView.frame // newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) // textView.frame = newFrame; } }
d173d8d91b285ea3a8fc8f0f1e3f13b0
31.1875
103
0.637864
false
false
false
false
AlbertXYZ/HDCP
refs/heads/master
HDCP/HDCP/AppDelegate.swift
mit
1
// // AppDelegate.swift // HDCP // // Created by 徐琰璋 on 16/1/4. // Copyright © 2016年 batonsoft. All rights reserved. // import UIKit import CoreData import Alamofire import RxSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //设置导航栏和标签栏样式 setUpBarStyle(); //ShareSDK 初始化 HDShareSDKManager.initializeShareSDK(); //欢迎导航页面 showWelcome(); //监听网络变化 networkMonitoring(); //缓存参数设置 setCache(); //用户数据初始化 loadUserInfo(); add3DTouch(); 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. HDCoreDataManager.sharedInstance.saveContext() } // MARK: - 欢迎界面 func showWelcome() { /** * 判断欢迎界面是否已经执行 */ let userDefault = UserDefaults.standard let appVersion: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String if (userDefault.string(forKey: Constants.HDAppVersion)) == nil { //第一次进入 userDefault.setValue(appVersion, forKey: Constants.HDAppVersion) userDefault.synchronize() self.window?.rootViewController = WelcomeController() } else { //版本升级后,根据版本号来判断是否进入 let version: String = (userDefault.string(forKey: Constants.HDAppVersion))! if ( appVersion == version) { // UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) self.window?.rootViewController = MainViewController() } else { userDefault.setValue(appVersion, forKey: Constants.HDAppVersion) userDefault.synchronize() self.window?.rootViewController = WelcomeController() } } } // MARK: - 设置导航栏和标签栏样式 func setUpBarStyle() { /** * 导航栏样式 */ UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "Heiti SC", size: 18.0)!] UINavigationBar.appearance().barTintColor = Constants.HDMainColor // UINavigationBar.appearance().barTintColor = CoreUtils.HDColor(245, g: 161, b: 0, a: 1) /** * 状态栏字体设置白色 */ // UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) /** * 底部TabBar的颜色 */ UITabBar.appearance().shadowImage = UIImage() UITabBar.appearance().tintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) UITabBar.appearance().backgroundColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) UITabBar.appearance().barTintColor = CoreUtils.HDfromHexValue(0xFFFFFF, alpha: 1.0) // UITabBar.appearance().selectedImageTintColor = UIColor.clearColor() /** * 底部TabBar字体正常状态颜色 */ UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainTextColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.normal) /** * 底部TabBar字体选择状态颜色 */ UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Constants.HDMainColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13)], for: UIControl.State.selected) } // MARK: - 网络监听 func networkMonitoring() { // let reachability: Reachability // do { // reachability = try Reachability.reachabilityForInternetConnection() // } catch { // print("Unable to create Reachability") // return // } // // // reachability.whenReachable = { reachability in // // this is called on a background thread, but UI updates must // // be on the main thread, like this: // dispatch_async(dispatch_get_main_queue()) { // if reachability.isReachableViaWiFi() { // print("Reachable via WiFi") // } else { // print("Reachable via Cellular") // } // } // } // reachability.whenUnreachable = { reachability in // // this is called on a background thread, but UI updates must // // be on the main thread, like this: // dispatch_async(dispatch_get_main_queue()) { // print("Not reachable") // } // } // // do { // try reachability.startNotifier() // } catch { // print("Unable to start notifier") // } } // MARK: - 缓存参数设置 func setCache() { //是否将图片缓存到内存 // SDImageCache.shared().shouldCacheImagesInMemory = true // //缓存将保留5天 // SDImageCache.shared().maxCacheAge = 5*24*60*60 // //缓存最大占有内存100MB // SDImageCache.shared().maxCacheSize = UInt(1024*1024*100) } // MARK: - 初始化当前登录用户数据 func loadUserInfo() { //判断用户是否已登录 let defaults = UserDefaults.standard let sign = defaults.object(forKey: Constants.HDSign) if let _ = sign { //初始化用户数据 HDUserInfoManager.shareInstance.load() } } // MARK: - 添加3DTouch功能 func add3DTouch() { if (UIDevice().systemVersion as NSString).doubleValue > 8.0 { let ggShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_04"); let dtShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_on_02"); let myShortcutIcon = UIApplicationShortcutIcon(templateImageName: "tab_icon_off_05"); let ggShortcutItem = UIApplicationShortcutItem(type: "TAB_GG", localizedTitle: "逛逛", localizedSubtitle: "", icon: ggShortcutIcon, userInfo: nil); let dtShortcutItem = UIApplicationShortcutItem(type: "TAB_DT", localizedTitle: "动态", localizedSubtitle: "", icon: dtShortcutIcon, userInfo: nil); let myShortcutItem = UIApplicationShortcutItem(type: "TAB_CENTER", localizedTitle: "个人中心", localizedSubtitle: "", icon: myShortcutIcon, userInfo: nil); UIApplication.shared.shortcutItems = [ggShortcutItem, dtShortcutItem, myShortcutItem]; } } // MARK: - 3DTouch事件处理 func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { if shortcutItem.type == "TAB_GG" { let userDefualt = UserDefaults.standard; userDefualt.set("1", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } if shortcutItem.type == "TAB_DT" { let userDefualt = UserDefaults.standard; userDefualt.set("3", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } if shortcutItem.type == "TAB_CENTER" { let userDefualt = UserDefaults.standard; userDefualt.set("4", forKey: Constants.HDPushIndex) userDefualt.synchronize() self.window?.rootViewController = MainViewController() } } }
bb4b1d2719ba507487bda0ac25d73d21
35.952381
285
0.644652
false
false
false
false
mikker/Dispatcher
refs/heads/master
Dispatcher.swift
mit
1
public class Dispatcher { public typealias Callback = Any? -> Void public var tokenGenerator: TokenStream.Generator = TokenStream(prefix: "ID_").generate() var callbacks: [String: Callback] = [:] var isPending: [String: (Bool)] = [:] var isHandled: [String: (Bool)] = [:] var isDispatching: Bool = false var pendingPayload: Any? public init() {} // Public public func register(callback: Callback) -> String { if let id = tokenGenerator.next() { callbacks[id] = callback return id } preconditionFailure("Dispatcher.register(...): Failed to generate token for registration.") } public func unregister(id: String) { precondition(callbacks.keys.contains(id), "Dispatcher.unregister(...): `\(id)` does not map to a registered callback.") callbacks.removeValueForKey(id) } public func waitFor(ids: [String]) { precondition(isDispatching, "Dispatcher.waitFor(...): Must be invoked while dispatching.") for id in ids { if (isPending[id]!) { precondition(isHandled[id] != nil, "Dispatcher.waitFor(...): Circular dependency detected while waiting for `\(id)`.") continue } invokeCallback(id) } } public func dispatch(payload: Any?) { precondition(!isDispatching, "Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.") startDispatching(payload) defer { stopDispatching() } for id in callbacks.keys { if isPending[id]! { continue } invokeCallback(id) } } // Private private func invokeCallback(id: String) { isPending[id] = true callbacks[id]!(pendingPayload) isHandled[id] = true } private func startDispatching(payload: Any?) { for id in callbacks.keys { isPending[id] = false isHandled[id] = false } pendingPayload = payload isDispatching = true } private func stopDispatching() { pendingPayload = nil isDispatching = false } } // TokenStream extension Dispatcher { public struct TokenStream { let prefix: String } } extension Dispatcher.TokenStream: CollectionType { public typealias Index = Int public var startIndex: Int { return 0 } public var endIndex: Int { return Int.max } public subscript(index: Int) -> String { get { return "\(prefix)\(index)" } } public func generate() -> IndexingGenerator<Dispatcher.TokenStream> { return IndexingGenerator(self) } }
b87c1d8af8daa69c4b21db187881ec4e
26.77
134
0.57889
false
false
false
false
beneiltis/SwiftCharts
refs/heads/master
Examples/Examples/Examples/TargetExample.swift
apache-2.0
5
// // TargetExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class TargetExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints: [ChartPoint] = [(2, 2), (4, 4), (7, 1), (8, 11), (12, 3)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))} let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueFloat($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 0.5, animDelay: 0) let targetGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in if chartPointModel.index != 3 { return nil } return ChartPointTargetingView(chartPoint: chartPointModel.chartPoint, screenLoc: chartPointModel.screenLoc, animDuration: 0.5, animDelay: 1, frame: chart.bounds, layer: layer) } let chartPointsTargetLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: targetGenerator) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLineLayer, chartPointsTargetLayer ] ) self.view.addSubview(chart.view) self.chart = chart } }
1add802b1e2badfa5f3d3954ef630daa
47.919355
258
0.682493
false
false
false
false
frootloops/swift
refs/heads/master
stdlib/public/core/BidirectionalCollection.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements, with bidirectional /// index traversal. /// /// In most cases, it's best to ignore this protocol and use the /// `BidirectionalCollection` protocol instead, because it has a more complete /// interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead") public typealias BidirectionalIndexable = BidirectionalCollection /// A collection that supports backward as well as forward traversal. /// /// Bidirectional collections offer traversal backward from any valid index, /// not including a collection's `startIndex`. Bidirectional collections can /// therefore offer additional operations, such as a `last` property that /// provides efficient access to the last element and a `reversed()` method /// that presents the elements in reverse order. In addition, bidirectional /// collections have more efficient implementations of some sequence and /// collection methods, such as `suffix(_:)`. /// /// Conforming to the BidirectionalCollection Protocol /// ================================================== /// /// To add `BidirectionalProtocol` conformance to your custom types, implement /// the `index(before:)` method in addition to the requirements of the /// `Collection` protocol. /// /// Indices that are moved forward and backward in a bidirectional collection /// move by the same amount in each direction. That is, for any index `i` into /// a bidirectional collection `c`: /// /// - If `i >= c.startIndex && i < c.endIndex`, /// `c.index(before: c.index(after: i)) == i`. /// - If `i > c.startIndex && i <= c.endIndex` /// `c.index(after: c.index(before: i)) == i`. public protocol BidirectionalCollection: Collection where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection { // FIXME(ABI): Associated type inference requires this. associatedtype Element // FIXME(ABI): Associated type inference requires this. associatedtype Index // FIXME(ABI): Associated type inference requires this. associatedtype SubSequence = Slice<Self> // FIXME(ABI): Associated type inference requires this. associatedtype Indices = DefaultIndices<Self> /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } // TODO: swift-3-indexing-model: tests. /// The last element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let lastNumber = numbers.last { /// print(lastNumber) /// } /// // Prints "50" /// /// - Complexity: O(1) var last: Element? { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence { get } // FIXME(ABI): Associated type inference requires this. subscript(position: Index) -> Element { get } // FIXME(ABI): Associated type inference requires this. var startIndex: Index { get } // FIXME(ABI): Associated type inference requires this. var endIndex: Index { get } } /// Default implementation for bidirectional collections. extension BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func formIndex(before i: inout Index) { i = index(before: i) } @_inlineable // FIXME(sil-serialize-all) public func index(_ i: Index, offsetBy n: Int) -> Index { if n >= 0 { return _advanceForward(i, by: n) } var i = i for _ in stride(from: 0, to: n, by: -1) { formIndex(before: &i) } return i } @_inlineable // FIXME(sil-serialize-all) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { if n >= 0 { return _advanceForward(i, by: n, limitedBy: limit) } var i = i for _ in stride(from: 0, to: n, by: -1) { if i == limit { return nil } formIndex(before: &i) } return i } @_inlineable // FIXME(sil-serialize-all) public func distance(from start: Index, to end: Index) -> Int { var start = start var count = 0 if start < end { while start != end { count += 1 formIndex(after: &start) } } else if start > end { while start != end { count -= 1 formIndex(before: &start) } } return count } } extension BidirectionalCollection where SubSequence == Self { /// Removes and returns the last element of the collection. /// /// You can use `popLast()` to remove the last element of a collection that /// might be empty. The `removeLast()` method must be used only on a /// nonempty collection. /// /// - Returns: The last element of the collection if the collection has one /// or more elements; otherwise, `nil`. /// /// - Complexity: O(1). @_inlineable // FIXME(sil-serialize-all) public mutating func popLast() -> Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. To remove the last element of a /// collection that might be empty, use the `popLast()` method instead. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @_inlineable // FIXME(sil-serialize-all) @discardableResult public mutating func removeLast() -> Element { let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes the given number of elements from the end of the collection. /// /// - Parameter n: The number of elements to remove. `n` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable // FIXME(sil-serialize-all) public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))] } } extension BidirectionalCollection { /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off `n` elements from the end. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop. @_inlineable // FIXME(sil-serialize-all) public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let end = index( endIndex, offsetBy: numericCast(-n), limitedBy: startIndex) ?? startIndex return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains the entire collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is equal to `maxLength`. @_inlineable // FIXME(sil-serialize-all) public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = index( endIndex, offsetBy: numericCast(-maxLength), limitedBy: startIndex) ?? startIndex return self[start..<endIndex] } }
b6d094b402d6ee7f60312dbeee690db7
35.047923
116
0.639014
false
false
false
false
306244907/Weibo
refs/heads/master
JLSina/JLSina/Classes/View(视图和控制器)/Compose撰写微博/JLComposeViewController.swift
mit
1
// // JLComposeViewController.swift // JLSina // // Created by 盘赢 on 2017/12/5. // Copyright © 2017年 JinLong. All rights reserved. // import UIKit import SVProgressHUD //撰写微博控制器 /* 加载视图控制器的时候,如果XIB和控制器重名,默认的构造函数会优先加载XIB */ class JLComposeViewController: UIViewController { ///文本编辑视图 @IBOutlet weak var textView: JLComposeTextView! ///底部工具栏 @IBOutlet weak var toolBar: UIToolbar! ///发布按钮 @IBOutlet var sendButton: UIButton! //标题标签 - 换行热键 option + 回车 ///逐行选中文本并且设置属性 ///如果要想调整行间距,增加空行,设置空行的字体,lineHeight @IBOutlet var titleLabel: UILabel! ///工具栏底部约束 @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint! ///表情输入视图 lazy var emoticonView = CZEmoticonInputView.inputView { [weak self](emoticon) in //FIXME: - self?.textView.insertEmoticon(em: emoticon) } //MARK: - 视图生命周期 override func viewDidLoad() { super.viewDidLoad() setupUI() //监听键盘通知 - UIWindow.h NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //激活键盘 textView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //关闭键盘 textView.resignFirstResponder() } //MARK: - 键盘监听 @objc private func keyboardChanged(n: Notification) { // print(n.userInfo) //1,目标rect guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return } //2,设置底部约束的高度 let offset = view.bounds.height - rect.origin.y //3,更新底部约束 toolBarBottomCons.constant = offset //动画更新约束 UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } } @objc private func close() { dismiss(animated: true, completion: nil) } //MARK: - 监听方法 //发布微博 @IBAction func postStatus() { //1,获取发送给服务器的表情微博文字 let text = textView.emtionText + "www.epermarket.com" //2,发布微博, 想法带图片的,只需设置图片有没有就行 //FIXME: - 临时测试发布带图片的微博 let image: UIImage? = nil //UIImage(named: "icon_small_kangaroo_loading_1") JLNetworkManager.shared.postStatus(text: text , image:image ) { (result, isSuccess) in // print(result) //修改指示器样式 SVProgressHUD.setDefaultStyle(.dark) let message = isSuccess ? "发布成功" : "网络不给力" SVProgressHUD.showInfo(withStatus: message) //如果成功,延迟一段时间关闭当前窗口 //FIXME: 反向判断。! if !isSuccess { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { //恢复样式 SVProgressHUD.setDefaultStyle(.light) self.close() } } } } ///切换表情键盘 @objc private func emoticonKeyboard () { //textView.inputView 就是文本框的输入视图 //如果使用系统默认的键盘,输入视图为 nil //1,测试键盘视图 - 视图的宽度可以随便,就是屏幕的宽度, // let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 253)) // keyboardView.backgroundColor = UIColor.blue //2,设置键盘视图 textView.inputView = (textView.inputView == nil) ? emoticonView : nil //3,!!!刷新键盘视图 textView.reloadInputViews() } } //MARK: - UITextViewDelegate /* 通知: 一对多, 只要有注册的监听者,在注销监听之前,都可以接收到通知 代理: 一对一,最后设置的代理对象有效! 苹果日常开发中,代理监听方式是最多的! - 代理是发生事件时,直接让代理执行协议方法 代理的效率更高 直接的反向传值 - 通知是发生事件时,将通知发给通知中心,通知中心再‘广播’通知 通知相对要低一些 如果层次嵌套的非常深,可以使用通知传值 */ extension JLComposeViewController: UITextViewDelegate { /// 文本视图文字变化 func textViewDidChange(_ textView: UITextView) { sendButton.isEnabled = textView.hasText } } private extension JLComposeViewController { func setupUI() { view.backgroundColor = UIColor.white setupNavtionBar() setupToolBar() } ///设置工具栏 func setupToolBar() { let itemSettings = [ ["imageName": "compose_toolbar_picture"], ["imageName": "compose_mentionbutton_background"], ["imageName": "compose_trendbutton_background"], ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"], ["imageName": "compose_add_background"] ] //遍历数组 var items = [UIBarButtonItem]() for s in itemSettings { guard let imageName = s["imageName"] else { continue } let image = UIImage(named: imageName) let imageHL = UIImage(named: imageName + "_highlighted") let btn = UIButton() btn.setImage(image, for: []) btn.setImage(imageHL, for: .highlighted) btn.sizeToFit() //判断actionName if let actionName = s["actionName"] { //给按钮添加监听方法 btn.addTarget(self, action: Selector(actionName), for: .touchUpInside) } //追加按钮 items .append(UIBarButtonItem(customView: btn)) //追加弹簧 items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) } // 删除末尾弹簧 items.removeLast() toolBar.items = items } //设置导航栏 func setupNavtionBar() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close)) //设置发布按钮 navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton) //设置标题视图 navigationItem.titleView = titleLabel sendButton.isEnabled = false } }
6ffe1de426a3eb4ddccc3a6ecca6b39f
26.869565
115
0.557878
false
false
false
false
LesCoureurs/Coulomb
refs/heads/master
Courir/Pods/Coulomb/NetworkLib/CoulombNetwork.swift
mit
2
// // CoulombNetwork.swift // Coulomb // // Created by Ian Ngiaw on 3/14/16. // Copyright © 2016 nus.cs3217.group5. All rights reserved. // import MultipeerConnectivity import UIKit public protocol CoulombNetworkDelegate: class { func foundHostsChanged(foundHosts: [MCPeerID]) func invitationToConnectReceived(peer: MCPeerID, handleInvitation: (Bool) -> Void) func connectedPeersInSessionChanged(peers: [MCPeerID]) func connectedToPeer(peer: MCPeerID) func connectingToPeer(peer: MCPeerID) func disconnectedFromSession(peer: MCPeerID) func handleDataPacket(data: NSData, peerID: MCPeerID) } public class CoulombNetwork: NSObject { // MARK: Public settings /// Toggle on/off to print DLog messages to console public var debugMode = false public var autoAcceptGuests = true public var maxNumPeerInRoom = 4 // MARK: Private settings static let defaultTimeout: NSTimeInterval = 7 private var serviceAdvertiser: MCNearbyServiceAdvertiser? private var serviceBrowser: MCNearbyServiceBrowser? private var foundHosts = [MCPeerID]() private let myPeerId: MCPeerID private var host: MCPeerID? private let serviceType: String public weak var delegate: CoulombNetworkDelegate? private lazy var session: MCSession = { let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: .Required) session.delegate = self return session }() public init(serviceType: String, myPeerId: MCPeerID) { self.serviceType = serviceType self.myPeerId = myPeerId } deinit { stopAdvertisingHost() stopSearchingForHosts() session.disconnect() } // MARK: Methods for host /// Start advertising. /// Assign advertiser delegate public func startAdvertisingHost() { stopSearchingForHosts() self.host = myPeerId serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: ["peerType": "host"], serviceType: serviceType) self.serviceAdvertiser?.delegate = self self.serviceAdvertiser?.startAdvertisingPeer() } /// Stop advertising. /// Unassign advertiser delegate public func stopAdvertisingHost() { serviceAdvertiser?.stopAdvertisingPeer() serviceAdvertiser?.delegate = nil } // MARK: Methods for guest /// Start looking for discoverable hosts public func startSearchingForHosts() { self.host = nil serviceBrowser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: serviceType) serviceBrowser?.delegate = self foundHosts = [] serviceBrowser?.startBrowsingForPeers() } /// Stop looking for hosts public func stopSearchingForHosts() { serviceBrowser?.stopBrowsingForPeers() } /// Send inivitation to connect to a host public func connectToHost(host: MCPeerID, context: NSData? = nil, timeout: NSTimeInterval = defaultTimeout) { guard foundHosts.contains(host) else { return } DLog("%@", "connect to host: \(host)") serviceBrowser?.invitePeer(host, toSession: session, withContext: context, timeout: timeout) // If the session is still without host, assign a new one if self.host == nil { self.host = host } } /// Get the list of discovered hosts public func getFoundHosts() -> [MCPeerID] { return foundHosts } // MARK: Methods for session /// Called when deliberately disconnect. /// Disconnect from current session, browse for another host public func disconnect() { session.disconnect() host = nil DLog("%@", "disconnected from \(session.hashValue)") } /// Send data to every peer in session public func sendData(data: NSData, mode: MCSessionSendDataMode) -> Bool { do { try session.sendData(data, toPeers: session.connectedPeers, withMode: mode) } catch { return false } return true } /// Return my peer ID public func getMyPeerID() -> MCPeerID { return myPeerId } /// Debug mode private func DLog(message: String, _ function: String) { if debugMode { NSLog(message, function) } } } extension CoulombNetwork: MCNearbyServiceAdvertiserDelegate { /// Invitation is received from guest public func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) { DLog("%@", "didReceiveInvitationFromPeer \(peerID)") let acceptGuest = { (accepted: Bool) -> Void in invitationHandler(accepted, self.session) } if autoAcceptGuests { acceptGuest(true) } else { delegate?.invitationToConnectReceived(peerID, handleInvitation: acceptGuest) } } } extension CoulombNetwork: MCNearbyServiceBrowserDelegate { /// Peer is found in browser public func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { DLog("%@", "foundPeer: \(peerID)") guard let discoveryInfo = info else { return } guard discoveryInfo["peerType"] == "host" else { return } foundHosts.append(peerID) delegate?.foundHostsChanged(foundHosts) } /// Peer is lost in browser public func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { guard foundHosts.contains(peerID) else { return } DLog("%@", "lostPeer: \(peerID)") let index = foundHosts.indexOf(peerID)! foundHosts.removeAtIndex(index) delegate?.foundHostsChanged(foundHosts) } } extension CoulombNetwork: MCSessionDelegate { // Handles MCSessionState changes: NotConnected, Connecting and Connected. public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { DLog("%@", "peer \(peerID) didChangeState: \(state.stringValue())") if state != .Connecting { if state == .Connected { DLog("%@", "connected to \(session.hashValue)") // If currently a guest, stop looking for host stopSearchingForHosts() if self.host == peerID { if session.connectedPeers.count >= maxNumPeerInRoom { disconnect() return } else { // Pass to delegate delegate?.connectedToPeer(peerID) } } } else { DLog("%@", "not connected to \(session.hashValue)") // If self is disconnected from current host if self.host == peerID { DLog("%@", "disconnected from host") session.disconnect() delegate?.disconnectedFromSession(peerID) return } } // If self did not disconnect deliberately if self.host != nil { delegate?.connectedPeersInSessionChanged(session.connectedPeers) } } else { delegate?.connectingToPeer(peerID) } } // Handles incomming NSData public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { delegate?.handleDataPacket(data, peerID: peerID) } // Handles incoming NSInputStream public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } // Handles finish receiving resource public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { } // Handles start receiving resource public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { } } // MARK: For Dlog messages extension MCSessionState { func stringValue() -> String { switch(self) { case .NotConnected: return "NotConnected" case .Connecting: return "Connecting" case .Connected: return "Connected" } } }
1ed04bcc17584d7f9917441043dd5bff
32.507353
133
0.600132
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Plans/PlansLoadingIndicatorView.swift
gpl-2.0
2
import UIKit import WordPressShared // Circle View is 100x100 pixels private struct Config { // Icon images are 256 pixels high struct Scale { static let free: CGFloat = 0.25 static let premium: CGFloat = 0.35 static let business: CGFloat = 0.3 } // Distance from view center struct OffsetX { static let free: CGFloat = -20 static let premium: CGFloat = 0 static let business: CGFloat = 20 } // Final vertical offset from the center struct OffsetY { static let free: CGFloat = 30 static let premium: CGFloat = 12 static let business: CGFloat = 25 } // Initial vertical offset from bottom of the circle view's bounding box struct InitialOffsetY { static let free: CGFloat = 0 static let premium: CGFloat = 0 static let business: CGFloat = 0 } // The total duration of the animations, measured in seconds struct Duration { // Make this larger than 1 to slow down all animations static let durationScale: TimeInterval = 1.2 static let free: TimeInterval = 1.4 static let premium: TimeInterval = 1 static let business: TimeInterval = 1.2 } // The amount of time (measured in seconds) to wait before beginning the animations struct Delay { static let initial: TimeInterval = 0.3 static let free: TimeInterval = 0.35 static let premium: TimeInterval = 0.0 static let business: TimeInterval = 0.2 } // The damping ratio for the spring animation as it approaches its quiescent state. // To smoothly decelerate the animation without oscillation, use a value of 1. Employ a damping ratio closer to zero to increase oscillation. struct SpringDamping { static let free: CGFloat = 0.5 static let premium: CGFloat = 0.65 static let business: CGFloat = 0.5 } // The initial spring velocity. For smooth start to the animation, match this value to the view’s velocity as it was prior to attachment. // A value of 1 corresponds to the total animation distance traversed in one second. For example, if the total animation distance is 200 points and you want the start of the animation to match a view velocity of 100 pt/s, use a value of 0.5. struct InitialSpringVelocity { static let free: CGFloat = 0.1 static let premium: CGFloat = 0.01 static let business: CGFloat = 0.1 } struct DefaultSize { static let width: CGFloat = 100 static let height: CGFloat = 100 } } // =========================================================================== private extension CGRect { init(center: CGPoint, size: CGSize) { self.init() self.origin = CGPoint(x: center.x - size.width / 2, y: center.y - size.height / 2) self.size = size } } private extension CGSize { func scaleBy(_ scale: CGFloat) -> CGSize { return self.applying(CGAffineTransform(scaleX: scale, y: scale)) } } private extension UIView { var boundsCenter: CGPoint { return CGPoint(x: bounds.midX, y: bounds.midY) } } class PlansLoadingIndicatorView: UIView { fileprivate let freeView = UIImageView(image: UIImage(named: "plan-free-loading")!) fileprivate let premiumView = UIImageView(image: UIImage(named: "plan-premium-loading")!) fileprivate let businessView = UIImageView(image: UIImage(named: "plan-business-loading")!) fileprivate let circleView = UIView() convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: Config.DefaultSize.width, height: Config.DefaultSize.height)) } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .neutral(.shade5) circleView.clipsToBounds = true circleView.addSubview(premiumView) circleView.addSubview(freeView) circleView.addSubview(businessView) addSubview(circleView) freeView.frame = targetFreeFrame premiumView.frame = targetPremiumFrame businessView.frame = targetBusinessFrame circleView.backgroundColor = UIColor(red: 211/255, green: 222/255, blue: 230/255, alpha: 1) circleView.layer.cornerRadius = 50 setInitialPositions() } fileprivate var targetFreeFrame: CGRect { let freeCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.free, y: Config.OffsetY.free)) let freeSize = freeView.sizeThatFits(bounds.size).scaleBy(Config.Scale.free) return CGRect(center: freeCenter, size: freeSize) } fileprivate var targetPremiumFrame: CGRect { let premiumCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.premium, y: Config.OffsetY.premium)) let premiumSize = premiumView.sizeThatFits(bounds.size).scaleBy(Config.Scale.premium) return CGRect(center: premiumCenter, size: premiumSize) } fileprivate var targetBusinessFrame: CGRect { let businessCenter = boundsCenter.applying(CGAffineTransform(translationX: Config.OffsetX.business, y: Config.OffsetY.business)) let businessSize = businessView.sizeThatFits(bounds.size).scaleBy(Config.Scale.business) return CGRect(center: businessCenter, size: businessSize) } fileprivate func setInitialPositions() { let freeOffset = Config.InitialOffsetY.free + bounds.size.height - targetFreeFrame.origin.y freeView.transform = CGAffineTransform(translationX: 0, y: freeOffset) let premiumOffset = Config.InitialOffsetY.premium + bounds.size.height - targetPremiumFrame.origin.y premiumView.transform = CGAffineTransform(translationX: 0, y: premiumOffset) let businessOffset = Config.InitialOffsetY.business + bounds.size.height - targetBusinessFrame.origin.y businessView.transform = CGAffineTransform(translationX: 0, y: businessOffset) } override func layoutSubviews() { super.layoutSubviews() let size = min(bounds.width, bounds.height) circleView.frame = CGRect(center: boundsCenter, size: CGSize(width: size, height: size)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview() animateAfterDelay(Config.Delay.initial) } @objc func animateAfterDelay(_ delay: TimeInterval) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { [weak self] in self?.animate() } ) } @objc func animate() { UIView.performWithoutAnimation { self.setInitialPositions() } UIView.animate( withDuration: Config.Duration.free * Config.Duration.durationScale, delay: Config.Delay.free * Config.Duration.durationScale, usingSpringWithDamping: Config.SpringDamping.free, initialSpringVelocity: Config.InitialSpringVelocity.free, options: .curveEaseOut, animations: { [unowned freeView] in freeView.transform = CGAffineTransform.identity }) UIView.animate( withDuration: Config.Duration.premium * Config.Duration.durationScale, delay: Config.Delay.premium * Config.Duration.durationScale, usingSpringWithDamping: Config.SpringDamping.premium, initialSpringVelocity: Config.InitialSpringVelocity.premium, options: .curveEaseOut, animations: { [unowned premiumView] in premiumView.transform = CGAffineTransform.identity }) UIView.animate( withDuration: Config.Duration.business * Config.Duration.durationScale, delay: Config.Delay.business * Config.Duration.durationScale, usingSpringWithDamping: Config.SpringDamping.business, initialSpringVelocity: Config.InitialSpringVelocity.business, options: .curveEaseOut, animations: { [unowned businessView] in businessView.transform = CGAffineTransform.identity }) } }
f369646a4951eafaffab533211d5ae51
39.009615
245
0.665946
false
true
false
false
YunsChou/LovePlay
refs/heads/master
LovePlay-Swift3/Pods/HandyJSON/Source/Measuable.swift
mit
4
// // Measuable.swift // HandyJSON // // Created by zhouzhuo on 15/07/2017. // Copyright © 2017 aliyun. All rights reserved. // import Foundation typealias Byte = Int8 public protocol _Measurable {} extension _Measurable { // locate the head of a struct type object in memory mutating func headPointerOfStruct() -> UnsafeMutablePointer<Byte> { return withUnsafeMutablePointer(to: &self) { return UnsafeMutableRawPointer($0).bindMemory(to: Byte.self, capacity: MemoryLayout<Self>.stride) } } // locating the head of a class type object in memory mutating func headPointerOfClass() -> UnsafeMutablePointer<Byte> { let opaquePointer = Unmanaged.passUnretained(self as AnyObject).toOpaque() let mutableTypedPointer = opaquePointer.bindMemory(to: Byte.self, capacity: MemoryLayout<Self>.stride) return UnsafeMutablePointer<Byte>(mutableTypedPointer) } // locating the head of an object mutating func headPointer() -> UnsafeMutablePointer<Byte> { if Self.self is AnyClass { return self.headPointerOfClass() } else { return self.headPointerOfStruct() } } func isNSObjectType() -> Bool { return (type(of: self) as? NSObject.Type) != nil } func getBridgedPropertyList() -> Set<String> { if let anyClass = type(of: self) as? AnyClass { return _getBridgedPropertyList(anyClass: anyClass) } return [] } func _getBridgedPropertyList(anyClass: AnyClass) -> Set<String> { if !(anyClass is HandyJSON.Type) { return [] } var propertyList = Set<String>() if let superClass = class_getSuperclass(anyClass), superClass != NSObject.self { propertyList = propertyList.union(_getBridgedPropertyList(anyClass: superClass)) } let count = UnsafeMutablePointer<UInt32>.allocate(capacity: 1) if let props = class_copyPropertyList(anyClass, count) { for i in 0 ..< count.pointee { let name = String(cString: property_getName(props.advanced(by: Int(i)).pointee)) propertyList.insert(name) } } return propertyList } // memory size occupy by self object static func size() -> Int { return MemoryLayout<Self>.size } // align static func align() -> Int { return MemoryLayout<Self>.alignment } // Returns the offset to the next integer that is greater than // or equal to Value and is a multiple of Align. Align must be // non-zero. static func offsetToAlignment(value: Int, align: Int) -> Int { let m = value % align return m == 0 ? 0 : (align - m) } }
2e8a3755845570e403a0f0e40c2ecf6c
30.134831
110
0.629737
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Source/Model/AccountStore.swift
gpl-3.0
1
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation private let log = ZMSLog(tag: "Accounts") /// Persistence layer for `Account` objects. /// Objects are stored in files named after their identifier like this: /// /// ``` /// - Root url passed to init /// - Accounts /// - 47B3C313-E3FA-4DE4-8DBE-5BBDB6A0A14B /// - 0F5771BB-2103-4E45-9ED2-E7E6B9D46C0F /// ``` public final class AccountStore: NSObject { private static let directoryName = "Accounts" private let fileManager = FileManager.default private let directory: URL // The url to the directory in which accounts are stored in /// Creates a new `AccountStore`. /// `Account` objects will be stored in a subdirectory of the passed in url. /// - parameter root: The root url in which the storage will use to store its data public required init(root: URL) { directory = root.appendingPathComponent(AccountStore.directoryName) super.init() FileManager.default.createAndProtectDirectory(at: directory) } // MARK: - Storing and Retrieving /// Loads all stored accounts. /// - returns: All accounts stored in this `AccountStore`. func load() -> Set<Account> { return Set<Account>(loadURLs().compactMap(Account.load)) } /// Tries to load a stored account with the given `UUID`. /// - parameter uuid: The `UUID` of the user the account belongs to. /// - returns: The `Account` stored for the passed in `UUID`, or `nil` otherwise. func load(_ uuid: UUID) -> Account? { return Account.load(from: url(for: uuid)) } /// Stores an `Account` in the account store. /// - parameter account: The account which should be saved (or updated). /// - returns: Whether or not the operation was successful. @discardableResult func add(_ account: Account) -> Bool { do { try account.write(to: url(for: account)) return true } catch { log.error("Unable to store account \(account), error: \(error)") return false } } /// Deletes an `Account` from the account store. /// - parameter account: The account which should be deleted. /// - returns: Whether or not the operation was successful. @discardableResult func remove(_ account: Account) -> Bool { do { guard contains(account) else { return false } try fileManager.removeItem(at: url(for: account)) return true } catch { log.error("Unable to delete account \(account), error: \(error)") return false } } /// Deletes the persistence layer of an `AccountStore` from the file system. /// Mostly useful for cleaning up after tests or for complete account resets. /// - parameter root: The root url of the store that should be deleted. @discardableResult static func delete(at root: URL) -> Bool { do { try FileManager.default.removeItem(at: root.appendingPathComponent(directoryName)) return true } catch { log.error("Unable to remove all accounts at \(root): \(error)") return false } } /// Check if an `Account` is already stored in this `AccountStore`. /// - parameter account: The account which should be deleted. /// - returns: Whether or not the account is stored in this `AccountStore`. func contains(_ account: Account) -> Bool { return fileManager.fileExists(atPath: url(for: account).path) } // MARK: - Private Helper /// Loads the urls to all stored accounts. /// - returns: The urls to all accounts stored in this `AccountStore`. private func loadURLs() -> Set<URL> { do { let uuidName: (String) -> Bool = { UUID(uuidString: $0) != nil } let paths = try fileManager.contentsOfDirectory(atPath: directory.path) return Set<URL>(paths.filter(uuidName).map(directory.appendingPathComponent)) } catch { log.error("Unable to load accounts from \(directory), error: \(error)") return [] } } /// Create a local url for an `Account` inside this `AccountStore`. /// - parameter account: The account for which the url should be generated. /// - returns: The `URL` for the given account. private func url(for account: Account) -> URL { return url(for: account.userIdentifier) } /// Create a local url for an `Account` with the given `UUID` inside this `AccountStore`. /// - parameter uuid: The uuid of the user for which the url should be generated. /// - returns: The `URL` for the given uuid. private func url(for uuid: UUID) -> URL { return directory.appendingPathComponent(uuid.uuidString) } }
5c4231b480c4a51358928541a39379da
38.875912
94
0.646714
false
false
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/Swift/Components/FeatureFlag/Core/FeatureFlag+Providers.swift
mit
1
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import Foundation // MARK: - Registration extension FeatureFlag { /// The registered list of providers. private static var provider = CompositeFeatureFlagProvider([ ProcessInfoEnvironmentVariablesFeatureFlagProvider() ]) /// Register the given provider if it's not already registered. /// /// - Note: This method ensures there are no duplicate providers. public static func register(_ provider: FeatureFlagProvider) { self.provider.add(provider) } } // MARK: - FeatureFlag.Key Convenience extension FeatureFlag.Key { private var currentValue: FeatureFlag.Value? { FeatureFlag.provider.value(forKey: self) } /// Returns the value of the key from registered list of feature flag providers. /// /// - Returns: The value for the key. public func value() -> Bool { currentValue?.get() ?? false } /// Returns the value of the key from registered list of feature flag providers. /// /// - Returns: The value for the key. public func value<T>() -> T? { currentValue?.get() } /// Returns the value of the key from registered list of feature flag providers. /// /// - Parameter defaultValue: The value returned if the providers list doesn't /// contain value. /// - Returns: The value for the key. public func value<T>(default defaultValue: @autoclosure () -> T) -> T { currentValue?.get() ?? defaultValue() } /// Returns the value of the key from registered list of feature flag providers. /// /// - Parameter defaultValue: The value returned if the providers list doesn't /// contain value. /// - Returns: The value for the key. public func value<T>(default defaultValue: @autoclosure () -> T) -> T where T: RawRepresentable, T.RawValue == String { currentValue?.get() ?? defaultValue() } /// Returns the value of the key, decoded from a JSON object, from registered /// list of feature flag providers. /// /// - Parameters: /// - type: The type of the value to decode from the string. /// - decoder: The decoder used to decode the data. If set to `nil`, it uses /// ``JSONDecoder`` with `convertFromSnakeCase` key decoding strategy. /// - Returns: A value of the specified type, if the decoder can parse the data. public func decodedValue<T>(_ type: T.Type = T.self, decoder: JSONDecoder? = nil) -> T? where T: Decodable { currentValue?.get(type, decoder: decoder) } }
1aaeb71156763bc6b35394b9b5a363b0
33.813333
123
0.649177
false
false
false
false
mcarter6061/FetchedResultsCoordinator
refs/heads/master
Example/Tests/CollectionViewTests.swift
mit
1
// Copyright © 2016 Mark Carter. All rights reserved. import XCTest import Quick import Nimble @testable import FetchedResultsCoordinator import CoreData class CollectionViewTests: QuickSpec { override func spec() { describe("With a collection view") { let indexPathZero = NSIndexPath( forRow:0, inSection:0 ) let indexPathOne = NSIndexPath( forRow:1, inSection:0 ) let indexSet = NSMutableIndexSet(index: 5) var sut: SpyCollectionView! var changes:ChangeSet! beforeEach({ sut = SpyCollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout()) changes = ChangeSet() }) it("reloads data") { sut.reloadData() } it("applies no changes") { changes.objectChanges = [] sut.apply(changes) let expected = CollectionViewInvocation.PerformBatchUpdates expect(sut.capturedCalls).to(equal([expected])) } it("updates table when section inserted") { changes.insertedSections = indexSet sut.apply( changes ) let expected = CollectionViewInvocation.InsertSections(indexSet) expect(sut.capturedCalls).to(contain(expected)) } it("updates table when section inserted") { changes.deletedSections = indexSet sut.apply( changes ) let expected = CollectionViewInvocation.DeleteSections(indexSet) expect(sut.capturedCalls).to(contain(expected)) } it("updates table when data inserted") { changes.objectChanges = [.Insert(indexPathZero)] sut.apply( changes ) let expected = CollectionViewInvocation.InsertItemssAtIndexPaths(indexPaths:[indexPathZero]) expect(sut.capturedCalls).to(contain(expected)) } it("updates table when data deleted") { changes.objectChanges = [.Delete(indexPathZero)] sut.apply( changes ) let expected = CollectionViewInvocation.DeleteItemssAtIndexPaths(indexPaths:[indexPathZero]) expect(sut.capturedCalls).to(contain(expected)) } it("updates table when data moved") { changes.objectChanges = [.Move(from:indexPathZero,to:indexPathOne)] sut.apply( changes ) let expectedA:CollectionViewInvocation = .DeleteItemssAtIndexPaths(indexPaths:[indexPathZero]) let expectedB:CollectionViewInvocation = .InsertItemssAtIndexPaths(indexPaths:[indexPathOne]) expect(sut.capturedCalls).to(contain(expectedA,expectedB)) } it("updates table when data updated") { changes.objectChanges = [.Update(indexPathZero)] sut.apply( changes ) let expected = CollectionViewInvocation.ReloadItemssAtIndexPaths(indexPaths:[indexPathZero]) expect(sut.capturedCalls).to(contain(expected)) } it("doesn't update table when cell reloaded") { changes.objectChanges = [.CellConfigure( {} )] sut.apply(changes) let rejected = CollectionViewInvocation.ReloadItemssAtIndexPaths(indexPaths:[indexPathZero]) expect(sut.capturedCalls).toNot(contain(rejected)) } it("calls reload cell function when cell reloaded") { var calledReload = false changes.objectChanges = [.CellConfigure( {calledReload = true} )] sut.apply(changes) expect(calledReload).to(beTrue()) } // TODO: finish porting over tests from tableview objc tests. } } }
0044a756e0674d6ebcd73cc4c7391b24
38.626168
110
0.548007
false
false
false
false
bengottlieb/ios
refs/heads/master
FiveCalls/FiveCallsUITests/FiveCallsUITests.swift
mit
1
// // FiveCallsUITests.swift // FiveCallsUITests // // Created by Ben Scheirman on 2/8/17. // Copyright © 2017 5calls. All rights reserved. // import XCTest @testable import FiveCalls class FiveCallsUITests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchEnvironment = ["UI_TESTING" : "1"] loadJSONFixtures(application: app) setupSnapshot(app) app.launch() } override func tearDown() { super.tearDown() } func testTakeScreenshots() { snapshot("0-welcome") let label = app.staticTexts["Turn your passive participation into active resistance. Facebook likes and Twitter retweets can’t create the change you want to see. Calling your Government on the phone can."] label.swipeLeft() snapshot("1-welcome2") app.buttons["Get Started"].tap() app.buttons["Set Location"].tap() app.textFields["Zip or Address"].tap() app.typeText("77429") app.buttons["Submit"].tap() snapshot("2-issues") app.tables.cells.staticTexts["Defend the Affordable Care Act"].tap() snapshot("3-issue-detail") let issueTable = app.tables.element(boundBy: 0) issueTable.swipeUp() issueTable.swipeUp() issueTable.swipeUp() app.cells.staticTexts["Ted Cruz"].tap() snapshot("4-call-script") } private func loadJSONFixtures(application: XCUIApplication) { let bundle = Bundle(for: FiveCallsUITests.self) application.launchEnvironment["GET:/issues"] = bundle.path(forResource: "GET-issues", ofType: "json") application.launchEnvironment["GET:/report"] = bundle.path(forResource: "GET-report", ofType: "json") application.launchEnvironment["POST:/report"] = bundle.path(forResource: "POST-report", ofType: "json") } }
b33da4ac5cca817826af4a63c6fa6775
30.625
213
0.62747
false
true
false
false
daltoniam/Starscream
refs/heads/master
Sources/Framer/HTTPHandler.swift
apache-2.0
1
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPHandler.swift // Starscream // // Created by Dalton Cherry on 1/24/19. // Copyright © 2019 Vluxe. 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 Foundation public enum HTTPUpgradeError: Error { case notAnUpgrade(Int, [String: String]) case invalidData } public struct HTTPWSHeader { static let upgradeName = "Upgrade" static let upgradeValue = "websocket" static let hostName = "Host" static let connectionName = "Connection" static let connectionValue = "Upgrade" static let protocolName = "Sec-WebSocket-Protocol" static let versionName = "Sec-WebSocket-Version" static let versionValue = "13" static let extensionName = "Sec-WebSocket-Extensions" static let keyName = "Sec-WebSocket-Key" static let originName = "Origin" static let acceptName = "Sec-WebSocket-Accept" static let switchProtocolCode = 101 static let defaultSSLSchemes = ["wss", "https"] /// Creates a new URLRequest based off the source URLRequest. /// - Parameter request: the request to "upgrade" the WebSocket request by adding headers. /// - Parameter supportsCompression: set if the client support text compression. /// - Parameter secKeyName: the security key to use in the WebSocket request. https://tools.ietf.org/html/rfc6455#section-1.3 /// - returns: A URLRequest request to be converted to data and sent to the server. public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest { guard let url = request.url, let parts = url.getParts() else { return request } var req = request if request.value(forHTTPHeaderField: HTTPWSHeader.originName) == nil { var origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) } req.setValue(origin, forHTTPHeaderField: HTTPWSHeader.originName) } req.setValue(HTTPWSHeader.upgradeValue, forHTTPHeaderField: HTTPWSHeader.upgradeName) req.setValue(HTTPWSHeader.connectionValue, forHTTPHeaderField: HTTPWSHeader.connectionName) req.setValue(HTTPWSHeader.versionValue, forHTTPHeaderField: HTTPWSHeader.versionName) req.setValue(secKeyValue, forHTTPHeaderField: HTTPWSHeader.keyName) if let cookies = HTTPCookieStorage.shared.cookies(for: url), !cookies.isEmpty { let headers = HTTPCookie.requestHeaderFields(with: cookies) for (key, val) in headers { req.setValue(val, forHTTPHeaderField: key) } } if supportsCompression { let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" req.setValue(val, forHTTPHeaderField: HTTPWSHeader.extensionName) } let hostValue = req.allHTTPHeaderFields?[HTTPWSHeader.hostName] ?? "\(parts.host):\(parts.port)" req.setValue(hostValue, forHTTPHeaderField: HTTPWSHeader.hostName) return req } // generateWebSocketKey 16 random characters between a-z and return them as a base64 string public static func generateWebSocketKey() -> String { return Data((0..<16).map{ _ in UInt8.random(in: 97...122) }).base64EncodedString() } } public enum HTTPEvent { case success([String: String]) case failure(Error) } public protocol HTTPHandlerDelegate: AnyObject { func didReceiveHTTP(event: HTTPEvent) } public protocol HTTPHandler { func register(delegate: HTTPHandlerDelegate) func convert(request: URLRequest) -> Data func parse(data: Data) -> Int } public protocol HTTPServerDelegate: AnyObject { func didReceive(event: HTTPEvent) } public protocol HTTPServerHandler { func register(delegate: HTTPServerDelegate) func parse(data: Data) func createResponse(headers: [String: String]) -> Data } public struct URLParts { let port: Int let host: String let isTLS: Bool } public extension URL { /// isTLSScheme returns true if the scheme is https or wss var isTLSScheme: Bool { guard let scheme = self.scheme else { return false } return HTTPWSHeader.defaultSSLSchemes.contains(scheme) } /// getParts pulls host and port from the url. func getParts() -> URLParts? { guard let host = self.host else { return nil // no host, this isn't a valid url } let isTLS = isTLSScheme var port = self.port ?? 0 if self.port == nil { if isTLS { port = 443 } else { port = 80 } } return URLParts(port: port, host: host, isTLS: isTLS) } }
e7328413e210ce36921b33645031055e
37.486486
129
0.635358
false
false
false
false
deege/deegeu-swift-share-extensions
refs/heads/master
deegeu-swift-share-extensions/BlueViewController.swift
mit
1
// // BlueViewController.swift // deegeu-swift-share-extensions // // Created by Daniel Spiess on 10/23/15. // Copyright © 2015 Daniel Spiess. All rights reserved. // import UIKit class BlueViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! let suiteName = "group.deegeu.swift.share.extension" let blueDefaultKey = "BlueColorImage" // Simply reads the selected image from NSUserDefaults and displays the // image override func viewDidLoad() { super.viewDidLoad() if let prefs = UserDefaults(suiteName: suiteName) { if let imageData = prefs.object(forKey: blueDefaultKey) as? Data { DispatchQueue.main.async(execute: { () -> Void in self.imageView.image = UIImage(data: imageData) }) } } } }
cf869f211848f8afdf48d34337ffcde5
28.586207
78
0.635198
false
false
false
false
firebase/friendlypix-ios
refs/heads/master
FriendlyPix/UIImage+Circle.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SDWebImage import Firebase extension UIImage { var circle: UIImage? { let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height)) //let square = CGSize(width: 36, height: 36) let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square)) imageView.contentMode = .scaleAspectFill imageView.image = self imageView.layer.cornerRadius = square.width / 2 imageView.layer.masksToBounds = true UIGraphicsBeginImageContext(imageView.bounds.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.render(in: context) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func resizeImage(_ dimension: CGFloat) -> UIImage { var width: CGFloat var height: CGFloat var newImage: UIImage let size = self.size let aspectRatio = size.width / size.height if aspectRatio > 1 { // Landscape image width = dimension height = dimension / aspectRatio } else { // Portrait image height = dimension width = dimension * aspectRatio } if #available(iOS 10.0, *) { let renderFormat = UIGraphicsImageRendererFormat.default() let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat) newImage = renderer.image { _ in self.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) } } else { UIGraphicsBeginImageContext(CGSize(width: width, height: height)) self.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() } return newImage } func resizeImage(_ dimension: CGFloat, with quality: CGFloat) -> Data? { return resizeImage(dimension).jpegData(compressionQuality: quality) } static func circleImage(with url: URL, to imageView: UIImageView) { let urlString = url.absoluteString let trace = Performance.startTrace(name: "load_profile_pic") if let image = SDImageCache.shared.imageFromCache(forKey: urlString) { trace?.incrementMetric("cache", by: 1) trace?.stop() imageView.image = image return } SDWebImageDownloader.shared.downloadImage(with: url, options: .highPriority, progress: nil) { image, _, error, _ in trace?.incrementMetric("download", by: 1) trace?.stop() if let error = error { print(error) return } if let image = image { let circleImage = image.circle SDImageCache.shared.store(circleImage, forKey: urlString, completion: nil) imageView.image = circleImage } } } static func circleButton(with url: URL, to button: UIBarButtonItem) { let urlString = url.absoluteString let trace = Performance.startTrace(name: "load_profile_pic") if let image = SDImageCache.shared.imageFromCache(forKey: urlString) { trace?.incrementMetric("cache", by: 1) trace?.stop() button.image = image.resizeImage(36).withRenderingMode(.alwaysOriginal) return } SDWebImageDownloader.shared.downloadImage(with: url, options: .highPriority, progress: nil) { image, _, _, _ in trace?.incrementMetric("download", by: 1) trace?.stop() if let image = image { let circleImage = image.circle button.tintColor = .red SDImageCache.shared.store(circleImage, forKey: urlString, completion: nil) button.image = circleImage?.resizeImage(36).withRenderingMode(.alwaysOriginal) } } } }
3cbd12a2436c5178aff46974d22c0edc
36.101695
115
0.665372
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
refs/heads/master
MobilePeopleDirectory/ServerAsyncCallback.swift
gpl-3.0
1
// // ServerSyncCallback.swift // MobilePeopleDirectory // // Created by alejandro soto on 2/3/15. // Copyright (c) 2015 Rivet Logic. All rights reserved. // import UIKit import CoreData class ServerAsyncCallback:NSObject, LRCallback { private var _syncable:ServerSyncableProtocol private var _primaryKey:String private var _itemsCountKey:String private var _listKey:String private var _errorHandler: ((ServerFetchResult!) -> Void)! var appHelper = AppHelper() init(syncable:ServerSyncableProtocol, primaryKey:String, itemsCountKey:String, listKey:String, errorHandler: ((ServerFetchResult!) -> Void)!) { self._syncable = syncable self._primaryKey = primaryKey self._itemsCountKey = itemsCountKey self._listKey = listKey self._errorHandler = errorHandler } func onFailure(error: NSError!) { switch (error.code) { //case -1001: default: self._errorHandler(ServerFetchResult.ConnectivityIssue) break; } } func onSuccess(result: AnyObject!) { var response = result as! NSDictionary var items = response[self._listKey] as! NSArray var activeItemsCount = response[self._itemsCountKey] as! NSInteger println("Items retrieved from server : \(items.count)") var managedObjectContext = appHelper.getManagedContext() for item in items { // checks if item exists if self._syncable.itemExists(item[self._primaryKey] as! NSInteger) { var existentItem = self._syncable.getItemById(item[self._primaryKey] as! NSInteger) as NSManagedObject // update item with latest data existentItem = self._syncable.fillItem(item as! NSDictionary, managedObject: existentItem) managedObjectContext!.save(nil) } else { self._syncable.addItem(item as! NSDictionary) } } // if items unsynced retrieve entire data from server if (self._areItemsUnsynced(activeItemsCount)) { //self._syncable.removeAllItems() var session = SessionContext.createSessionFromCurrentSession() var asyncCallback = ServerAsyncCallback(syncable: self._syncable, primaryKey: self._primaryKey, itemsCountKey: self._itemsCountKey, listKey: self._listKey, errorHandler: self._errorHandler) session?.callback = asyncCallback //self._syncable.getServerData(0.0, session: &session!) } } private func _areItemsUnsynced(serverActiveItemsCount:NSInteger) -> Bool { let storedItemsCount = self._syncable.getItemsCount() return (storedItemsCount != serverActiveItemsCount) } }
5ed51f52845a1b1c86c3c117035c4a63
37.052632
147
0.628976
false
false
false
false
IngmarStein/swift
refs/heads/master
test/attr/attr_discardableResult.swift
apache-2.0
4
// RUN: %target-parse-verify-swift // --------------------------------------------------------------------------- // Mark function's return value as discardable and silence warning // --------------------------------------------------------------------------- @discardableResult func f1() -> [Int] { } func f2() -> [Int] { } func f3() { } func f4<R>(blah: () -> R) -> R { return blah() } func testGlobalFunctions() -> [Int] { f1() // okay f2() // expected-warning {{result of call to 'f2()' is unused}} _ = f2() // okay f3() // okay f4 { 5 } // expected-warning {{result of call to 'f4(blah:)' is unused}} f4 { } // okay return f2() // okay } class C1 { @discardableResult static func f1Static() -> Int { } static func f2Static() -> Int { } @discardableResult class func f1Class() -> Int { } class func f2Class() -> Int { } @discardableResult init() { } init(foo: Int) { } @discardableResult func f1() -> Int { } func f2() -> Int { } @discardableResult func f1Optional() -> Int? { } func f2Optional() -> Int? { } @discardableResult func me() -> Self { return self } func reallyMe() -> Self { return self } } class C2 : C1 {} func testFunctionsInClass(c1 : C1, c2: C2) { C1.f1Static() // okay C1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}} _ = C1.f2Static() // okay C1.f1Class() // okay C1.f2Class() // expected-warning {{result of call to 'f2Class()' is unused}} _ = C1.f2Class() // okay C1() // okay, marked @discardableResult _ = C1() // okay C1(foo: 5) // expected-warning {{result of 'C1' initializer is unused}} _ = C1(foo: 5) // okay c1.f1() // okay c1.f2() // expected-warning {{result of call to 'f2()' is unused}} _ = c1.f2() // okay c1.f1Optional() // okay c1.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} _ = c1.f2Optional() // okay c1.me() // okay c2.me() // okay c1.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}} c2.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}} _ = c1.reallyMe() // okay _ = c2.reallyMe() // okay } struct S1 { @discardableResult static func f1Static() -> Int { } static func f2Static() -> Int { } @discardableResult init() { } init(foo: Int) { } @discardableResult func f1() -> Int { } func f2() -> Int { } @discardableResult func f1Optional() -> Int? { } func f2Optional() -> Int? { } } func testFunctionsInStruct(s1 : S1) { S1.f1Static() // okay S1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}} _ = S1.f2Static() // okay S1() // okay, marked @discardableResult _ = S1() // okay S1(foo: 5) // expected-warning {{result of 'S1' initializer is unused}} _ = S1(foo: 5) // okay s1.f1() // okay s1.f2() // expected-warning {{result of call to 'f2()' is unused}} _ = s1.f2() // okay s1.f1Optional() // okay s1.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} _ = s1.f2Optional() // okay } protocol P1 { @discardableResult func me() -> Self func reallyMe() -> Self } func testFunctionsInExistential(p1 : P1) { p1.me() // okay p1.reallyMe() // expected-warning {{result of call to 'reallyMe()' is unused}} _ = p1.reallyMe() // okay } let x = 4 "Hello \(x+1) world" // expected-warning {{expression of type 'String' is unused}} func f(a : () -> Int) { 42 // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} 4 + 5 // expected-warning {{result of operator '+' is unused}} a() // expected-warning {{result of call is unused, but produces 'Int'}} } @warn_unused_result func g() -> Int { } // expected-warning {{'warn_unused_result' attribute behavior is now the default}} {{1-21=}} class X { @warn_unused_result // expected-warning {{'warn_unused_result' attribute behavior is now the default}} {{3-23=}} @objc func h() -> Int { } } func testOptionalChaining(c1: C1?, s1: S1?) { c1?.f1() // okay c1!.f1() // okay c1?.f1Optional() // okay c1!.f1Optional() // okay c1?.f2() // expected-warning {{result of call to 'f2()' is unused}} c1!.f2() // expected-warning {{result of call to 'f2()' is unused}} c1?.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} c1!.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} s1?.f1() // okay s1!.f1() // okay s1?.f1Optional() // okay s1!.f1Optional() // okay s1?.f2() // expected-warning {{result of call to 'f2()' is unused}} s1!.f2() // expected-warning {{result of call to 'f2()' is unused}} s1?.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} s1!.f2Optional() // expected-warning {{result of call to 'f2Optional()' is unused}} }
ec09d0982f6ec6592029e20de3372011
27.820225
132
0.555945
false
false
false
false
seongkyu-sim/BaseVCKit
refs/heads/master
BaseVCKit/Classes/extensions/UILabelExtensions.swift
mit
1
// // UILabelExtensions.swift // BaseVCKit // // Created by frank on 2015. 11. 10.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit public extension UILabel { static func configureLabel(color:UIColor, size:CGFloat, weight: UIFont.Weight = UIFont.Weight.regular) -> UILabel { let label = UILabel() label.textAlignment = NSTextAlignment.left label.font = UIFont.systemFont(ofSize: size, weight: weight) label.textColor = color label.numberOfLines = 0 return label } // MARK: - Attributed func setAttributedText(fullText: String, highlightText: String, highlightColor: UIColor? = nil, highlightFontWeight: UIFont.Weight? = nil) { let range = (fullText as NSString).range(of: highlightText) let attributedString = NSMutableAttributedString(string:fullText) if let highlightColor = highlightColor { // height color attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: highlightColor , range: range) } // set bold var originFontSize = CGFloat(15) if let originFont = self.font { originFontSize = originFont.pointSize } var font = UIFont.systemFont(ofSize: originFontSize, weight: UIFont.Weight.medium) if let highlightFontWeight = highlightFontWeight { font = UIFont.systemFont(ofSize: originFontSize, weight: highlightFontWeight) } attributedString.addAttribute(NSAttributedString.Key.font, value: font , range: range) self.attributedText = attributedString } // MARK: - Strikethrough line func renderStrikethrough(text:String?, color:UIColor = UIColor.black) { guard let text = text else { return } let attributedText = NSMutableAttributedString(string: text , attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue, NSAttributedString.Key.strikethroughColor: color]) attributedText.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: NSMakeRange(0, attributedText.length)) self.attributedText = attributedText } // MARK: - Ellipse Indecator func startEllipseAnimate(withText txt: String = "") { defaultTxt = txt stopEllipseAnimate() ellipseTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { timer in self.ellipseUpdate(loading: true) } } func stopEllipseAnimate() { if let aTimer = ellipseTimer { aTimer.invalidate() ellipseTimer = nil } ellipseUpdate(loading: false) } private struct AssociatedKeys { static var ellipseTimerKey = "ellipseTimer" static var defaultTxtKey = "defaultTxtKey" } private var ellipseTimer: Timer? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ellipseTimerKey) as? Timer } set { willChangeValue(forKey: "ellipseTimer") objc_setAssociatedObject(self, &AssociatedKeys.ellipseTimerKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) didChangeValue(forKey: "ellipseTimer") } } private var defaultTxt: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.defaultTxtKey) as? String } set { if let newValue = newValue { willChangeValue(forKey: "defaultTxt") objc_setAssociatedObject(self, &AssociatedKeys.defaultTxtKey, newValue as NSString?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) didChangeValue(forKey: "defaultTxt") } } } private func ellipseUpdate(loading: Bool) { guard let defaultTxt = defaultTxt else { return } guard loading else { self.text = defaultTxt return } if self.text == defaultTxt { self.text = defaultTxt + "." }else if self.text == defaultTxt + "." { self.text = defaultTxt + ".." }else if self.text == defaultTxt + ".." { self.text = defaultTxt + "..." }else { self.text = defaultTxt } } }
0ff6309896e900f156f6d00f7f9d84d5
32.695313
210
0.634593
false
false
false
false
kyotaw/ZaifSwift
refs/heads/master
ZaifSwiftTests/ZaifSwiftTests.swift
mit
1
// // ZaifSwiftTests.swift // ZaifSwiftTests // // Created by 渡部郷太 on 6/30/16. // Copyright © 2016 watanabe kyota. All rights reserved. // import XCTest import ZaifSwift private let api = PrivateApi(apiKey: key_full, secretKey: secret_full) class ZaifSwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testGetInfo() { // successfully complete let successExpectation = self.expectation(description: "get_info success") api.getInfo() { (err, res) in XCTAssertNil(err, "get_info success. err is nil") XCTAssertNotNil(res, "get_info success. res is not nil") successExpectation.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // keys has no permission for get_info let noPermissionExpectation = self.expectation(description: "no permission error") let api2 = ZaifSwift.PrivateApi(apiKey: key_no_info, secretKey: secret_no_info) api2.getInfo() { (err, res) in XCTAssertNotNil(err, "no permission. err is not nil") switch err!.errorType { case ZaifSwift.ZSErrorType.INFO_API_NO_PERMISSION: XCTAssertTrue(true, "no permission exception") default: XCTFail() } noPermissionExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) //invalid key let invalidKeyExpectaion = self.expectation(description: "invalid key error") let key_invalid = "INVALID" let api6 = PrivateApi(apiKey: key_invalid, secretKey: secret_full) api6.getInfo() { (err, res) in XCTAssertNotNil(err, "invalid key. err is not nil") XCTAssertTrue(true) /* switch err!.errorType { case ZaifSwift.ZSErrorType.INVALID_API_KEY: XCTAssertTrue(true) default: XCTFail() } */ invalidKeyExpectaion.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) //invalid secret let invalidSecretExpectaion = self.expectation(description: "invalid secret error") let secret_invalid = "INVALID" let api5 = ZaifSwift.PrivateApi(apiKey: key_no_trade, secretKey: secret_invalid) api5.getInfo() { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZaifSwift.ZSErrorType.INVALID_SIGNATURE: XCTAssertTrue(true) default: XCTFail() } invalidSecretExpectaion.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // nonce exceeds limit let nonceExceedExpectaion = self.expectation(description: "nonce exceed limit error") let nonce = SerialNonce(initialValue: IntMax.max) let _ = try! nonce.getNonce() let api7 = PrivateApi(apiKey: key_full, secretKey: secret_full, nonce: nonce) api7.getInfo() { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.NONCE_EXCEED_LIMIT: XCTAssertTrue(true) default: XCTFail() } nonceExceedExpectaion.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // nonce out of range let nonceOutOfRangeExpectaion = self.expectation(description: "nonce out of range error") let nonce2 = SerialNonce(initialValue: IntMax.max) let api8 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce2) api8.getInfo() { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.NONCE_EXCEED_LIMIT: XCTAssertTrue(true) default: XCTFail() } nonceOutOfRangeExpectaion.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // nonce not incremented let nonceNotIncremented = self.expectation(description: "nonce not incremented error") let nonce3 = SerialNonce(initialValue: 1) let api9 = PrivateApi(apiKey: key_limit, secretKey: secret_limit, nonce: nonce3) api9.getInfo() { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.NONCE_NOT_INCREMENTED: XCTAssertTrue(true) default: XCTFail() } nonceNotIncremented.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // connection error /* let connectionErrorExpectation = self.expectationWithDescription("connection error") let api5 = PrivateApi(apiKey: key_full, secretKey: secret_full) api5.getInfo() { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.CONNECTION_ERROR: XCTAssertTrue(true) default: XCTAssertTrue(true) } connectionErrorExpectation.fulfill() } self.waitForExpectationsWithTimeout(10.0, handler: nil) */ } func testTradeBtcJpy() { // keys has no permission for trade let noPermissionExpectation = self.expectation(description: "no permission error") let api_no_trade = PrivateApi(apiKey: key_no_trade, secretKey: secret_no_trade) let dummyOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001) api_no_trade.trade(dummyOrder) { (err, res) in XCTAssertNotNil(err, "no permission. err is not nil") switch err!.errorType { case ZSErrorType.TRADE_API_NO_PERMISSION: XCTAssertTrue(true, "no permission exception") default: XCTFail() } noPermissionExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // buy btc_jpy let btcJpyExpectation = self.expectation(description: "buy btc_jpy order success") let btcOrder = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001) api.trade(btcOrder) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) btcJpyExpectation.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // btc_jpy invalid price (border) let btcJpyExpectation20 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder20 = Trade.Buy.Btc.In.Jpy.createOrder(5, amount: 0.0001) api.trade(btcOrder20) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) btcJpyExpectation20.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // buy btc_jpy with limit let btcJpyExpectation4 = self.expectation(description: "buy btc_jpy order with limit success") let btcOrder4 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60005) api.trade(btcOrder4) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) btcJpyExpectation4.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // btc_jpy invalid price let btcJpyExpectation2 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder2 = Trade.Buy.Btc.In.Jpy.createOrder(60001, amount: 0.0001) api.trade(btcOrder2) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 5") default: XCTFail() } btcJpyExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid price (border) let btcJpyExpectation22 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder22 = Trade.Buy.Btc.In.Jpy.createOrder(4, amount: 0.0001) api.trade(btcOrder22) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 5") default: XCTFail() } btcJpyExpectation22.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid price (minus) let btcJpyExpectation11 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder11 = Trade.Buy.Btc.In.Jpy.createOrder(-60000, amount: 0.0001) api.trade(btcOrder11) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 5") default: XCTFail() } btcJpyExpectation11.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid price (zero) let btcJpyExpectation12 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder12 = Trade.Buy.Btc.In.Jpy.createOrder(0, amount: 0.0001) api.trade(btcOrder12) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 5") default: XCTFail() } btcJpyExpectation12.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid limit let btcJpyExpectation3 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder3 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 60002) api.trade(btcOrder3) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 5") default: XCTFail() } btcJpyExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid limit (minus) let btcJpyExpectation13 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder13 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: -60005) api.trade(btcOrder13) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 5") default: XCTFail() } btcJpyExpectation13.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid limit (zero) let btcJpyExpectation14 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder14 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.0001, limit: 0) api.trade(btcOrder14) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 5") default: XCTFail() } btcJpyExpectation14.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid amount let btcJpyExpectation5 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder5 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00011) api.trade(btcOrder5) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 0.0001") default: XCTFail() } btcJpyExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid amount (minus) let btcJpyExpectation15 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder15 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: -0.0001) api.trade(btcOrder15) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 0.0001") default: XCTFail() } btcJpyExpectation15.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid amount (zero) let btcJpyExpectation16 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder16 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0) api.trade(btcOrder16) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 0.0001") default: XCTFail() } btcJpyExpectation16.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // sell btc_jpy let btcJpyExpectation6 = self.expectation(description: "sell btc_jpy order success") let btcOrder6 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001) api.trade(btcOrder6) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) btcJpyExpectation6.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // sell btc_jpy with limit let btcJpyExpectation7 = self.expectation(description: "sell btc_jpy order with limit success") let btcOrder7 = Trade.Sell.Btc.For.Jpy.createOrder(80000, amount: 0.0001, limit: 79995) api.trade(btcOrder7) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) btcJpyExpectation7.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // btc_jpy invalid price let btcJpyExpectation8 = self.expectation(description: "btc_jpy order invalid price error") let btcOrder8 = Trade.Sell.Btc.For.Jpy.createOrder(79999, amount: 0.0001) api.trade(btcOrder8) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 5") default: XCTFail() } btcJpyExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid limit let btcJpyExpectation9 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder9 = Trade.Buy.Btc.In.Jpy.createOrder(80000, amount: 0.0001, limit: 79998) api.trade(btcOrder9) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 5") default: XCTFail() } btcJpyExpectation9.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // btc_jpy invalid amount let btcJpyExpectation10 = self.expectation(description: "btc_jpy order invalid limit error") let btcOrder10 = Trade.Buy.Btc.In.Jpy.createOrder(60000, amount: 0.00009) api.trade(btcOrder10) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 0.0001") default: XCTFail() } btcJpyExpectation10.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testTradeMonaJpy() { // buy mona_jpy let monaJpyExpectation = self.expectation(description: "buy mona_jpy order success") let monaOrder = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1) api.trade(monaOrder) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaJpyExpectation.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // mona_jpy invalid price (min) let monaJpyExpectation60 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder60 = Trade.Buy.Mona.In.Jpy.createOrder(0.1, amount: 1) api.trade(monaOrder60) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaJpyExpectation60.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // buy mona_jpy with limit let monaJpyExpectation2 = self.expectation(description: "buy mona_jpy order with limit success") let monaOrder2 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 4.1) api.trade(monaOrder2) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaJpyExpectation2.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // mona_jpy invalid price let monaJpyExpectation3 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder3 = Trade.Buy.Mona.In.Jpy.createOrder(4.01, amount: 1) api.trade(monaOrder3) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.1") default: XCTFail() } monaJpyExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid price (border) let monaJpyExpectation34 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder34 = Trade.Buy.Mona.In.Jpy.createOrder(0.09, amount: 1) api.trade(monaOrder34) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.1") default: XCTFail() } monaJpyExpectation34.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid price (minus) let monaJpyExpectation33 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder33 = Trade.Buy.Mona.In.Jpy.createOrder(-4.0, amount: 1) api.trade(monaOrder33) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.1") default: XCTFail() } monaJpyExpectation33.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid price (zero) let monaJpyExpectation7 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder7 = Trade.Buy.Mona.In.Jpy.createOrder(0, amount: 1) api.trade(monaOrder7) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.1") default: XCTFail() } monaJpyExpectation7.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid limit let monaJpyExpectation4 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder4 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 3.99) api.trade(monaOrder4) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.1") default: XCTFail() } monaJpyExpectation4.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid limit (minus) let monaJpyExpectation8 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder8 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: -4.1) api.trade(monaOrder8) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.1") default: XCTFail() } monaJpyExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid limit (zero) let monaJpyExpectation9 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder9 = Trade.Buy.Mona.In.Jpy.createOrder(4.0, amount: 1, limit: 0) api.trade(monaOrder9) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.1") default: XCTFail() } monaJpyExpectation9.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid amount (minus) let monaJpyExpectation10 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder10 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: -1) api.trade(monaOrder10) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaJpyExpectation10.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid amount (zero) let monaJpyExpectation5 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder5 = Trade.Buy.Mona.In.Jpy.createOrder(4.2, amount: 0) api.trade(monaOrder5) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaJpyExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // sell mona_jpy let monaJpyExpectation11 = self.expectation(description: "sell mona_jpy order success") let monaOrder11 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1) api.trade(monaOrder11) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaJpyExpectation11.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // sell mona_jpy with limit let monaJpyExpectation12 = self.expectation(description: "sell mona_jpy order with limit success") let monaOrder12 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 5.9) api.trade(monaOrder12) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaJpyExpectation12.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // mona_jpy invalid price let monaJpyExpectation13 = self.expectation(description: "mona_jpy order invalid price error") let monaOrder13 = Trade.Sell.Mona.For.Jpy.createOrder(6.01, amount: 1) api.trade(monaOrder13) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.1") default: XCTFail() } monaJpyExpectation13.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid limit let monaJpyExpectation14 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder14 = Trade.Sell.Mona.For.Jpy.createOrder(6.0, amount: 1, limit: 3.91) api.trade(monaOrder14) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.1") default: XCTFail() } monaJpyExpectation14.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy invalid amount let monaJpyExpectation15 = self.expectation(description: "mona_jpy order invalid limit error") let monaOrder15 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0) api.trade(monaOrder15) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaJpyExpectation15.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testTradeMonaBtc() { // buy mona_btc let monaBtcExpectation = self.expectation(description: "buy mona_btc order success") let monaOrder = Trade.Buy.Mona.In.Btc.createOrder(0.00000321, amount: 1) api.trade(monaOrder) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaBtcExpectation.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // buy mona_btc (min) let monaBtcExpectation22 = self.expectation(description: "buy mona_btc order success") let monaOrder22 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1) api.trade(monaOrder22) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaBtcExpectation22.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // buy mona_btc with limit let monaBtcExpectation2 = self.expectation(description: "buy mona_btc order with limit success") let monaOrder2 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.00010001) api.trade(monaOrder2) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaBtcExpectation2.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // mona_btc invalid price let monaBtcExpectation3 = self.expectation(description: "mona_btc order invalid price error") let monaOrder3 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1) api.trade(monaOrder3) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.00000001") default: XCTFail() } monaBtcExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid price (border) let monaBtcExpectation44 = self.expectation(description: "mona_btc order invalid price error") let monaOrder44 = Trade.Buy.Mona.In.Btc.createOrder(0.000000009, amount: 1) api.trade(monaOrder44) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.00000001") default: XCTFail() } monaBtcExpectation44.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid price (minus) let monaBtcExpectation4 = self.expectation(description: "mona_btc order invalid price error") let monaOrder4 = Trade.Buy.Mona.In.Btc.createOrder(-0.00000001, amount: 1) api.trade(monaOrder4) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.00000001") default: XCTFail() } monaBtcExpectation4.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid price (zero) let monaBtcExpectation5 = self.expectation(description: "mona_btc order invalid price error") let monaOrder5 = Trade.Buy.Mona.In.Btc.createOrder(0, amount: 1) api.trade(monaOrder5) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.00000001") default: XCTFail() } monaBtcExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid limit let monaBtcExpectation6 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder6 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0.000000019) api.trade(monaOrder6) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.00000001") default: XCTFail() } monaBtcExpectation6.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid limit (minus) let monaBtcExpectation7 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder7 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: -0.00000002) api.trade(monaOrder7) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.00000001") default: XCTFail() } monaBtcExpectation7.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid limit (zero) let monaBtcExpectation8 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder8 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 1, limit: 0) api.trade(monaOrder8) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.00000001") default: XCTFail() } monaBtcExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid amount (minus) let monaBtcExpectation10 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder10 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: -1) api.trade(monaOrder10) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaBtcExpectation10.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid amount (zero) let monaBtcExpectation55 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder55 = Trade.Buy.Mona.In.Btc.createOrder(0.00000001, amount: 0) api.trade(monaOrder55) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaBtcExpectation55.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // sell mona_btc let monaBtcExpectation32 = self.expectation(description: "sell mona_btc order success") let monaOrder32 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1) api.trade(monaOrder32) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaBtcExpectation32.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // sell mona_btc with limit let monaBtcExpectation19 = self.expectation(description: "sell mona_btc order with limit success") let monaOrder19 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 5.9) api.trade(monaOrder19) { (err, res) in XCTAssertNil(err) XCTAssertNotNil(res) monaBtcExpectation19.fulfill() } self.waitForExpectations(timeout: 10.0, handler: nil) usleep(200) // mona_btc invalid price let monaBtcExpectation40 = self.expectation(description: "mona_btc order invalid price error") let monaOrder40 = Trade.Sell.Mona.For.Btc.createOrder(0.000000019, amount: 1) api.trade(monaOrder40) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "price unit must be 0.00000001") default: XCTFail() } monaBtcExpectation40.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid limit let monaBtcExpectation64 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder64 = Trade.Sell.Mona.For.Btc.createOrder(6.0, amount: 1, limit: 0.000000009) api.trade(monaOrder64) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "limit unit must be 0.00000001") default: XCTFail() } monaBtcExpectation64.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc invalid amount let monaBtcExpectation54 = self.expectation(description: "mona_btc order invalid limit error") let monaOrder54 = Trade.Sell.Mona.For.Jpy.createOrder(6.2, amount: 0) api.trade(monaOrder54) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.INVALID_ORDER(let message): XCTAssertEqual(message, "amount unit must be 1") default: XCTFail() } monaBtcExpectation54.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testHistory() { // query using 'from' and 'count'. 'from' minus value let fromQueryExpectation2 = self.expectation(description: "query using 'from' and 'count'") let query2 = HistoryQuery(from: -1, count: 10) api.tradeHistory(query2) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } fromQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'from' zero value let fromQueryExpectation3 = self.expectation(description: "query using 'from' and 'count'") let query3 = HistoryQuery(from: 0, count: 10) api.tradeHistory(query3) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 10) fromQueryExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'from' valid value let fromQueryExpectation = self.expectation(description: "query using 'from' and 'count'") let query = HistoryQuery(from: 1, count: 10) api.tradeHistory(query) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 10) fromQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'from' valid value let fromQueryExpectation4 = self.expectation(description: "query using 'from' and 'count'") let query4 = HistoryQuery(from: 10, count: 10) api.tradeHistory(query4) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 10) fromQueryExpectation4.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'from' not specified let fromQueryExpectation41 = self.expectation(description: "query using 'from' and 'count'") let query41 = HistoryQuery(count: 10) api.tradeHistory(query41) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 10) fromQueryExpectation41.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'count' minus value let fromQueryExpectation5 = self.expectation(description: "query using 'from' and 'count'") let query5 = HistoryQuery(from: 0, count: -1) api.tradeHistory(query5) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } fromQueryExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'count' zero value let fromQueryExpectation6 = self.expectation(description: "query using 'from' and 'count'") let query6 = HistoryQuery(from: 0, count: 0) api.tradeHistory(query6) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } fromQueryExpectation6.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'count' valid value let fromQueryExpectation7 = self.expectation(description: "query using 'from' and 'count'") let query7 = HistoryQuery(from: 1, count: 1) api.tradeHistory(query7) { (err, res) in //print(res) XCTAssertNil(err) XCTAssertEqual(res!["return"].dictionary?.count, 1) fromQueryExpectation7.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'count' valid value let fromQueryExpectation8 = self.expectation(description: "query using 'from' and 'count'") let query8 = HistoryQuery(from: 1, count: 2) api.tradeHistory(query8) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 2) fromQueryExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from' and 'count'. 'count' not specified let fromQueryExpectation9 = self.expectation(description: "query using 'from' and 'count'") let query9 = HistoryQuery(from: 1, count: 2) api.tradeHistory(query9) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) fromQueryExpectation9.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id' let idQueryExpectation = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery = HistoryQuery(fromId: 6915724, endId: 7087911) api.tradeHistory(idQuery) { (err, res) in //print(res) XCTAssertEqual(res!["return"].dictionary?.count, 8) idQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'from_id' minus value let idQueryExpectation2 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery2 = HistoryQuery(fromId: -1, endId: 7087911) api.tradeHistory(idQuery2) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } idQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'from_id' 0 value let idQueryExpectation3 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery3 = HistoryQuery(fromId: 0, endId: 7087911) api.tradeHistory(idQuery3) { (err, res) in XCTAssertNil(err) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) idQueryExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'from_id' not specified let idQueryExpectation4 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery4 = HistoryQuery(endId: 7087911) api.tradeHistory(idQuery4) { (err, res) in XCTAssertNil(err) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) idQueryExpectation4.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'end_id' minus value let idQueryExpectation5 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery5 = HistoryQuery(fromId: 6915724, endId: -1) api.tradeHistory(idQuery5) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } idQueryExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'end_id' zero value let idQueryExpectation6 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery6 = HistoryQuery(fromId: 6915724, endId: 0) api.tradeHistory(idQuery6) { (err, res) in XCTAssertNil(err) //print(res) let noEntry = res!["return"].dictionary?.count == 0 XCTAssertTrue(noEntry) idQueryExpectation6.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'end_id' not specified let idQueryExpectation7 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery7 = HistoryQuery(fromId: 6915724) api.tradeHistory(idQuery7) { (err, res) in XCTAssertNil(err) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) idQueryExpectation7.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'from_id' and 'end_id'. 'end_id' is greater than 'from_id' let idQueryExpectation8 = self.expectation(description: "query using 'from_id' and 'end_id'") let idQuery8 = HistoryQuery(fromId: 7087911 , endId: 6915724) api.tradeHistory(idQuery8) { (err, res) in XCTAssertNil(err) //print(res) let noEntry = res!["return"].dictionary?.count == 0 XCTAssertTrue(noEntry) idQueryExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end' let sinceQueryExpectation = self.expectation(description: "query using 'since' and 'end'") let sinceQuery = HistoryQuery(since: 1467014263, end: 1467540926) api.tradeHistory(sinceQuery) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) sinceQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'since' minus value let sinceQueryExpectation2 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery2 = HistoryQuery(since: -1, end: 1467540926) api.tradeHistory(sinceQuery2) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } sinceQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'since' zero value let sinceQueryExpectation3 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery3 = HistoryQuery(since: 0, end: 1467540926) api.tradeHistory(sinceQuery3) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) sinceQueryExpectation3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'since' valid value let sinceQueryExpectation4 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery4 = HistoryQuery(since: 1, end: 1467540926) api.tradeHistory(sinceQuery4) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) sinceQueryExpectation4.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'since' not spcified let sinceQueryExpectation5 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery5 = HistoryQuery(end: 1467540926) api.tradeHistory(sinceQuery5) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) sinceQueryExpectation5.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'end' minus value let sinceQueryExpectation6 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery6 = HistoryQuery(since: 1467014263, end: -1) api.tradeHistory(sinceQuery6) { (err, res) in XCTAssertNotNil(err) switch err!.errorType { case ZSErrorType.PROCESSING_ERROR: XCTAssertTrue(true) default: XCTFail() } sinceQueryExpectation6.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'end' zero value let sinceQueryExpectation7 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery7 = HistoryQuery(since: 1467014263, end: 0) api.tradeHistory(sinceQuery7) { (err, res) in //print(res) let noEntry = res!["return"].dictionary?.count == 0 XCTAssertTrue(noEntry) sinceQueryExpectation7.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'end' valid value let sinceQueryExpectation8 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery8 = HistoryQuery(since: 1467014263, end: 1) api.tradeHistory(sinceQuery8) { (err, res) in //print(res) let noEntry = res!["return"].dictionary?.count == 0 XCTAssertTrue(noEntry) sinceQueryExpectation8.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'end' not specified let sinceQueryExpectation9 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery9 = HistoryQuery(since: 1467014263) api.tradeHistory(sinceQuery9) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) sinceQueryExpectation9.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query using 'since' and 'end'. 'since' is greater than 'end' let sinceQueryExpectation10 = self.expectation(description: "query using 'since' and 'end'") let sinceQuery10 = HistoryQuery(since: 1467540926, end: 1467014263) api.tradeHistory(sinceQuery10) { (err, res) in //print(res) let noEntry = res!["return"].dictionary?.count == 0 XCTAssertTrue(noEntry) sinceQueryExpectation10.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for btc_jpy. asc order let btcQueryExpectation = self.expectation(description: "query for btc_jpy") let btcQuery = HistoryQuery(order: .ASC, currencyPair: .BTC_JPY) api.tradeHistory(btcQuery) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "btc_jpy") btcQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for btc_jpy. desc order let btcQueryExpectation2 = self.expectation(description: "query for btc_jpy") let btcQuery2 = HistoryQuery(order: .DESC, currencyPair: .BTC_JPY) api.tradeHistory(btcQuery2) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "btc_jpy") btcQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for mona_jpy. asc order let monaQueryExpectation = self.expectation(description: "query for mona_jpy") let monaQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_JPY) api.tradeHistory(monaQuery) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_jpy") monaQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for mona_jpy. desc order let monaQueryExpectation2 = self.expectation(description: "query for mona_jpy") let monaQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_JPY) api.tradeHistory(monaQuery2) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_jpy") monaQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for mona_btc. asc order let monaBtcQueryExpectation = self.expectation(description: "query for mona_btc") let monaBtcQuery = HistoryQuery(order: .ASC, currencyPair: .MONA_BTC) api.tradeHistory(monaBtcQuery) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_btc") monaBtcQueryExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // query for mona_btc. desc order let monaBtcQueryExpectation2 = self.expectation(description: "query for mona_btc") let monaBtcQuery2 = HistoryQuery(order: .DESC, currencyPair: .MONA_BTC) api.tradeHistory(monaBtcQuery2) { (err, res) in //print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_btc") monaBtcQueryExpectation2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testActiveOrders() { // btc_jpy let btcExpectation = self.expectation(description: "active orders of btc_jpy") api.activeOrders(.BTC_JPY) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "btc_jpy") btcExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // mona_jpy let monaExpectation = self.expectation(description: "active orders of mona_jpy") api.activeOrders(.MONA_JPY) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_jpy") monaExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // mona_btc let monaBtcExpectation = self.expectation(description: "active orders of mona_btc") api.activeOrders(.MONA_BTC) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "mona_btc") monaBtcExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // xem_jpy let xemExpectation = self.expectation(description: "active orders of xem_jpy") api.activeOrders(.XEM_JPY) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) let pair = res!["return"].dictionary?.first?.1["currency_pair"].stringValue XCTAssertEqual(pair, "xem_jpy") xemExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // all let allExpectation = self.expectation(description: "active orders of all") api.activeOrders() { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) allExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testCancelOrder() { var orderIds: [String] = [] let allExpectation = self.expectation(description: "active orders of all") api.activeOrders() { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) for (orderId, _) in res!["return"].dictionaryValue { orderIds.append(orderId) } allExpectation.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) let cancelExpectation = self.expectation(description: "cancel orders") var count = orderIds.count let semaphore = DispatchSemaphore(value: 1) for orderId in orderIds { api.cancelOrder(Int(orderId)!) { (err, res) in print(res) let hasEntry = (res!["return"].dictionary?.count)! > 0 XCTAssertTrue(hasEntry) var resOrderId = res!["return"].dictionaryValue["order_id"] XCTAssertEqual(resOrderId?.stringValue, orderId) semaphore.wait(timeout: DispatchTime.distantFuture) count -= 1 if count == 0 { cancelExpectation.fulfill() } semaphore.signal() } } self.waitForExpectations(timeout: 5.0, handler: nil) let invalid = self.expectation(description: "invalid order id") api.cancelOrder(-1) { (err, res) in print(res) XCTAssertNotNil(err) invalid.fulfill() } self.waitForExpectations(timeout: 50.0, handler: nil) let invalid2 = self.expectation(description: "invalid order id") api.cancelOrder(0) { (err, res) in print(res) XCTAssertNotNil(err) invalid2.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) let invalid3 = self.expectation(description: "invalid order id") api.cancelOrder(999) { (err, res) in print(res) XCTAssertNotNil(err) invalid3.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testStream() { // btc_jpy let streamExpectation = self.expectation(description: "stream of btc_jpy") let stream = StreamingApi.stream(.BTC_JPY) { _,_ in print("opened btc_jpy") } var count = 10 stream.onData() { (_, res) in print(res) count -= 1 if count <= 0 { streamExpectation.fulfill() stream.onData(callback: nil) } } stream.onError() { (err, _) in print(err) } self.waitForExpectations(timeout: 50.0, handler: nil) let colseExp = self.expectation(description: "") stream.close() { (_, res) in print(res) colseExp.fulfill() } self.waitForExpectations(timeout: 50.0, handler: nil) // reopen let streamExpectationRe = self.expectation(description: "stream of btc_jpy") stream.open() { (_, _) in print("reopened") } count = 10 stream.onData() { (_, res) in print(res) count -= 1 if count <= 0 { streamExpectationRe.fulfill() stream.onData(callback: nil) } } stream.onError() { (err, _) in print(err) } self.waitForExpectations(timeout: 50.0, handler: nil) let colseExpRe = self.expectation(description: "") stream.close() { (_, res) in print(res) colseExpRe.fulfill() } self.waitForExpectations(timeout: 50.0, handler: nil) // mona_jpy let streamExpectation2 = self.expectation(description: "stream of mona_jpy") let stream2 = StreamingApi.stream(.MONA_JPY) { _,_ in print("opened mona_jpy") } count = 1 stream2.onData() { (_, res) in print(res) count -= 1 if count <= 0 { streamExpectation2.fulfill() stream2.onData(callback: nil) } } self.waitForExpectations(timeout: 5000.0, handler: nil) let colseExp2 = self.expectation(description: "") stream2.onClose() { (_, res) in print(res) colseExp2.fulfill() } stream2.close() self.waitForExpectations(timeout: 50.0, handler: nil) // mona_btc let streamExpectation3 = self.expectation(description: "stream of mona_btc") let stream3 = StreamingApi.stream(.MONA_BTC) { _,_ in print("opened mona_btc") } count = 1 stream3.onData() { (_, res) in print(res) count -= 1 if count <= 0 { streamExpectation3.fulfill() stream3.onData(callback: nil) } } self.waitForExpectations(timeout: 5000.0, handler: nil) let colseExp3 = self.expectation(description: "") stream3.onClose() { (_, res) in print(res) colseExp3.fulfill() } stream3.close() self.waitForExpectations(timeout: 50.0, handler: nil) // xem_jpy let streamExpectation4 = self.expectation(description: "stream of xem_jpy") let stream4 = StreamingApi.stream(.XEM_JPY) { _,_ in print("opened xem_jpy") } count = 1 stream4.onData() { (_, res) in print(res) count -= 1 if count <= 0 { streamExpectation4.fulfill() stream4.onData(callback: nil) } } self.waitForExpectations(timeout: 5000.0, handler: nil) let colseExp4 = self.expectation(description: "") stream4.onClose() { (_, res) in print(res) colseExp4.fulfill() } stream4.close() self.waitForExpectations(timeout: 50.0, handler: nil) } func testLastPrice() { // btc_jpy let btcLastPrice = self.expectation(description: "last price of btc_jpy") PublicApi.lastPrice(.BTC_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let price = res?["last_price"].int XCTAssertNotNil(price) btcLastPrice.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy let monaLastPrice = self.expectation(description: "last price of mona_jpy") PublicApi.lastPrice(.MONA_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let price = res?["last_price"].int XCTAssertNotNil(price) monaLastPrice.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc let monaBtcLastPrice = self.expectation(description: "last price for mona_btc") PublicApi.lastPrice(.MONA_BTC) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let price = res?["last_price"].int XCTAssertNotNil(price) monaBtcLastPrice.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // xem_jpy let xemLastPrice = self.expectation(description: "last price for xem_jpy") PublicApi.lastPrice(.XEM_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let price = res?["last_price"].int XCTAssertNotNil(price) xemLastPrice.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testTicker() { // btc_jpy let btcTicker = self.expectation(description: "ticker for btc_jpy") PublicApi.ticker(.BTC_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) btcTicker.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy let monaTicker = self.expectation(description: "ticker for mona_jpy") PublicApi.ticker(.MONA_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) monaTicker.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc let monaBtcTicker = self.expectation(description: "ticker for mona_btc") PublicApi.ticker(.MONA_BTC) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) monaBtcTicker.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // xem_jpy let xemTicker = self.expectation(description: "ticker for xem_jpy") PublicApi.ticker(.XEM_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) xemTicker.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testTrades() { // btc_jpy let btcTrades = self.expectation(description: "trades of btc_jpy") PublicApi.trades(.BTC_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) let cp = res?[[0, "currency_pair"]].stringValue XCTAssertEqual(cp, "btc_jpy") btcTrades.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy let monaTrades = self.expectation(description: "trades of mona_jpy") PublicApi.trades(.MONA_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) let cp = res?[[0, "currency_pair"]].stringValue XCTAssertEqual(cp, "mona_jpy") monaTrades.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc let monaBtcTrades = self.expectation(description: "trades of mona_btc") PublicApi.trades(.MONA_BTC) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) let cp = res?[[0, "currency_pair"]].stringValue XCTAssertEqual(cp, "mona_btc") monaBtcTrades.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // xem_jpy let xemTrades = self.expectation(description: "trades of xem_jpy") PublicApi.trades(.XEM_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasEntry = (res?.count)! > 0 XCTAssertTrue(hasEntry) let cp = res?[[0, "currency_pair"]].stringValue XCTAssertEqual(cp, "xem_jpy") xemTrades.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testDepth() { // btc_jpy let btcDepth = self.expectation(description: "depth of btc_jpy") PublicApi.depth(.BTC_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasAsks = (res?["asks"].count)! > 0 XCTAssertTrue(hasAsks) XCTAssertNotNil(res) let hasBids = (res?["bids"].count)! > 0 XCTAssertTrue(hasBids) btcDepth.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_jpy let monaDepth = self.expectation(description: "depth of mona_jpy") PublicApi.depth(.MONA_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasAsks = (res?["asks"].count)! > 0 XCTAssertTrue(hasAsks) XCTAssertNotNil(res) let hasBids = (res?["bids"].count)! > 0 XCTAssertTrue(hasBids) monaDepth.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) usleep(200) // mona_btc let monaBtcDepth = self.expectation(description: "depth of mona_btc") PublicApi.depth(.MONA_BTC) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasAsks = (res?["asks"].count)! > 0 XCTAssertTrue(hasAsks) XCTAssertNotNil(res) let hasBids = (res?["bids"].count)! > 0 XCTAssertTrue(hasBids) monaBtcDepth.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) // xem_jpy let xemDepth = self.expectation(description: "depth of xem_jpy") PublicApi.depth(.XEM_JPY) { (err, res) in print(res) XCTAssertNil(err) XCTAssertNotNil(res) let hasAsks = (res?["asks"].count)! > 0 XCTAssertTrue(hasAsks) XCTAssertNotNil(res) let hasBids = (res?["bids"].count)! > 0 XCTAssertTrue(hasBids) xemDepth.fulfill() } self.waitForExpectations(timeout: 5.0, handler: nil) } func testSerialNonce() { // invalid initial value test var nonce = SerialNonce(initialValue: -1) var value = try! nonce.getNonce() XCTAssertEqual(value, "1", "initial value -1") value = try! nonce.getNonce() XCTAssertEqual(value, "2", "initial value -1, 1 increment") nonce = SerialNonce(initialValue: 0) value = try! nonce.getNonce() XCTAssertEqual(value, "1", "initial value 0") value = try! nonce.getNonce() XCTAssertEqual(value, "2", "initial value 0, 1 increment") // valid initial value test nonce = SerialNonce(initialValue: 1) value = try! nonce.getNonce() XCTAssertEqual(value, "1", "initial value 1") value = try! nonce.getNonce() XCTAssertEqual(value, "2", "initial value 1, 1 increment") nonce = SerialNonce(initialValue: 2) value = try! nonce.getNonce() XCTAssertEqual(value, "2", "initial value 2") value = try! nonce.getNonce() XCTAssertEqual(value, "3", "initial value 2, 1 increment") // max initial value test nonce = SerialNonce(initialValue: IntMax.max) value = try! nonce.getNonce() XCTAssertEqual(value, IntMax.max.description, "initial value max") XCTAssertThrowsError(try nonce.getNonce()) { (error) in switch error as! ZSErrorType { case .NONCE_EXCEED_LIMIT: XCTAssertTrue(true) default: XCTFail() } } } func testTimeNonce() { let nonce = TimeNonce() var prev = try! nonce.getNonce() sleep(1) var cur = try! nonce.getNonce() XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second") prev = cur sleep(2) cur = try! nonce.getNonce() XCTAssertTrue(Int64(prev)! < Int64(cur)!, "one request in a second") prev = cur var count = 10 while count > 0 { cur = try! nonce.getNonce() XCTAssertTrue(Int64(prev)! < Int64(cur)!, "multiple request in a second") prev = cur if Int64(cur) == IntMax.max { break } count -= 1 } /* XCTAssertThrowsError(try nonce.getNonce()) { (error) in switch error as! ZSErrorType { case .NONCE_EXCEED_LIMIT: XCTAssertTrue(true) default: XCTFail() } } */ } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
b271c88fddf3f228cf54f56cced503c1
37.443741
111
0.566348
false
false
false
false
Ezfen/iOS.Apprentice.1-4
refs/heads/master
MyLocations/MyLocations/HudView.swift
mit
1
// // HudView.swift // MyLocations // // Created by 阿澤🍀 on 16/8/22. // Copyright © 2016年 Ezfen Inc. All rights reserved. // import UIKit class HudView: UIView { var text = "" class func hudInView(view: UIView, animated: Bool) -> HudView { let hudView = HudView(frame: view.bounds) hudView.opaque = false view.addSubview(hudView) view.userInteractionEnabled = false hudView.backgroundColor = UIColor.clearColor() hudView.showAnimated(animated) return hudView } override func drawRect(rect: CGRect) { let boxWidth: CGFloat = 96 let boxHeight: CGFloat = 96 let boxRect = CGRect(x: round((bounds.size.width - boxWidth)/2), y: round((bounds.size.height - boxHeight) / 2), width: boxWidth, height: boxHeight) let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10) UIColor(white: 0.3, alpha: 0.8).setFill() roundedRect.fill() if let image = UIImage(named: "Checkmark") { let imagePoint = CGPoint(x: center.x - round(image.size.width / 2), y: center.y - round(image.size.height / 2) - boxHeight / 8) image.drawAtPoint(imagePoint) } let attribs = [NSFontAttributeName: UIFont.systemFontOfSize(16), NSForegroundColorAttributeName: UIColor.whiteColor() ] let textSize = text.sizeWithAttributes(attribs) let textPoint = CGPoint(x: center.x - round(textSize.width / 2), y:center.y - round(textSize.height / 2) + boxHeight / 4) text.drawAtPoint(textPoint, withAttributes: attribs) } func showAnimated(animated: Bool) { if animated { alpha = 0 transform = CGAffineTransformMakeScale(1.3, 1.3) UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: { () -> Void in self.alpha = 1 self.transform = CGAffineTransformIdentity }, completion: nil) } } }
a3acc0d26f8e852738edb37203625718
32.515152
151
0.579566
false
false
false
false
barteljan/RocketChatAdapter
refs/heads/master
Pod/Classes/CommandHandler/SendMessageCommandHandler.swift
mit
1
// // SendMessageCommandHandler.swift // Pods // // Created by Jan Bartel on 13.03.16. // // import Foundation import SwiftDDP import VISPER_CommandBus public class SendMessageCommandHandler: CommandHandlerProtocol { let parser : MessageParserProtocol public init(parser : MessageParserProtocol){ self.parser = parser } public func isResponsible(command: Any!) -> Bool { return command is SendMessageCommandProtocol } public func process<T>(command: Any!, completion: ((result: T?, error: ErrorType?) -> Void)?) throws{ let myCommand = command as! SendMessageCommandProtocol var messageObject : [String : NSObject] messageObject = [ "rid":myCommand.channelId, "msg":myCommand.message ] Meteor.call("sendMessage", params: [messageObject]) { (result, error) -> () in if error != nil { completion?(result: nil,error: error) return } if(result == nil){ completion?(result:nil,error: RocketChatAdapterError.RequiredResponseFieldWasEmpty(field: "result",fileName: __FILE__,function: __FUNCTION__,line: __LINE__,column: __COLUMN__)) return } print(result) let messageResult = self.parser.parseMessage(result as! [String:AnyObject]) //completion?(result: (result as! T?), error: nil) completion?(result:(messageResult.message as! T), error: messageResult.error) } } }
c8c711fb6e1f850f98941d022019401b
28.333333
192
0.565789
false
false
false
false
tylow/surftranslate
refs/heads/master
SURF_Translate/CardTableViewController.swift
agpl-3.0
1
// // CardTableViewController.swift // SURF_Translate // // Created by Legeng Liu on 6/2/16. // Copyright © 2016 SURF. All rights reserved. // import UIKit //for delegate protocol CardTableVCDelegate: class { func updateDeck(card:Card) func deleteFromDeck(indexPath: NSIndexPath) } class CardTableViewController: UITableViewController, UINavigationControllerDelegate { //MARK: properties var cards = [Card]() //keeps track of all the Card objects //search let searchController = UISearchController(searchResultsController: nil) var filteredCards = [Card]() //delegate weak var delegate: CardTableVCDelegate? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.rightBarButtonItem = self.editButtonItem() //may or may not need this; can date persist only Decks /* if let savedCards = loadCards(){ cards += savedCards } */ /* //adding some sample Cards let card1 = Card(firstPhrase: "1", secondPhrase: "2", numTimesUsed: 0) let card2 = Card(firstPhrase: "English", secondPhrase: "Arabic", numTimesUsed: 0) let card3 = Card(firstPhrase: "I need water", secondPhrase: "أحتاج إلى الماء", numTimesUsed:0) cards += [card1, card2, card3] */ //search searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = true definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar } //able to search both top and bottom string func filterContentForSearchText(searchText:String){ filteredCards = cards.filter { card in return (card.firstPhrase.lowercaseString.containsString(searchText.lowercaseString)) || (card.secondPhrase.lowercaseString.containsString(searchText.lowercaseString)) } tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active && searchController.searchBar.text != ""{ return filteredCards.count } else { return cards.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "CardTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CardTableViewCell var card: Card if searchController.active && searchController.searchBar.text != "" { card = filteredCards[indexPath.row] } else { card = cards[indexPath.row] } cell.topPhrase.text = card.firstPhrase cell.bottomPhrase.text = card.secondPhrase return cell } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { delegate?.deleteFromDeck(indexPath) cards.removeAtIndex(indexPath.row) //saveCards() //data persistence tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "AddCard"{ print ("adding new card") } /* let card: Card if searchController.active && searchController.searchBar.text != ""{ card = filteredCards[indexPath.row] } else { card = cards[indexPath.row] } */ } @IBAction func unwindToCardList(sender: UIStoryboardSegue){ if let sourceViewController = sender.sourceViewController as? NewCardViewController, newCard = sourceViewController.newCard { //need to implement fav function later let newIndexPath = NSIndexPath(forRow: cards.count, inSection: 0) cards.append(newCard) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) delegate?.updateDeck(newCard) //data persistence //saveCards() } } /* //MARK: NSCoding func saveCards(){ let isSucessfulSave = NSKeyedArchiver.archiveRootObject(cards, toFile: Card.ArchiveURL.path!) if !isSucessfulSave{ print("failed to save cards") } } func loadCards() -> [Card]? { return NSKeyedUnarchiver.unarchiveObjectWithFile(Card.ArchiveURL.path!) as? [Card] } */ } extension CardTableViewController: UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) } }
af6763a8634b90e9fcb10fce5d4e1220
31.985075
178
0.643439
false
false
false
false
cafielo/iOS_BigNerdRanch_5th
refs/heads/master
Chap9_Homepwner/Homepwner/ItemsViewController.swift
mit
1
// // ItemsViewController.swift // Homepwner // // Created by Joonwon Lee on 7/31/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class ItemsViewController: UITableViewController { var itemStore: ItemStore! override func viewDidLoad() { super.viewDidLoad() let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0) tableView.contentInset = insets tableView.scrollIndicatorInsets = insets } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemStore.allItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) let item = itemStore.allItems[indexPath.row] cell.textLabel?.text = item.name cell.detailTextLabel?.text = "$\(item.valueInDollars)" return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
995b90399a19bab06733a8f13f02f752
32.91954
157
0.682481
false
false
false
false
soflare/XWebApp
refs/heads/master
XWebApp/XWAPluginBinding.swift
apache-2.0
1
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import WebKit import XWebView @objc public class XWAPluginBinding { struct Descriptor { var pluginID: String var argument: AnyObject! = nil var channelName: String! = nil var mainThread: Bool = false var lazyBinding: Bool = false init(pluginID: String, argument: AnyObject! = nil) { self.pluginID = pluginID self.argument = argument } } private var bindings = [String: Descriptor]() private let inventory: XWAPluginInventory private let pluginQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) public init(inventory: XWAPluginInventory) { self.inventory = inventory } public func addBinding(spec: AnyObject, forNamespace namespace: String) { if let str = spec as? String where !str.isEmpty { // simple spec var descriptor = Descriptor(pluginID: str) if last(descriptor.pluginID) == "?" { descriptor.pluginID = dropLast(descriptor.pluginID) descriptor.lazyBinding = true } if last(descriptor.pluginID) == "!" { descriptor.pluginID = dropLast(descriptor.pluginID) descriptor.mainThread = true } bindings[namespace] = descriptor } else if let pluginID = spec["Plugin"] as? String { // full spec var descriptor = Descriptor(pluginID: pluginID, argument: spec["argument"]) descriptor.channelName = spec["channelName"] as? String descriptor.mainThread = spec["mainThread"] as? Bool ?? false descriptor.lazyBinding = spec["lazyBinding"] as? Bool ?? false bindings[namespace] = descriptor } else { println("ERROR: Unknown binding spec for namespace '\(namespace)'") } } public func prebind(webView: WKWebView) { for (namespace, _) in filter(bindings, { !$0.1.lazyBinding }) { bind(webView, namespace: namespace) } } func bind(namespace: AnyObject!, argument: AnyObject?, _Promise: XWVScriptObject) { let scriptObject = objc_getAssociatedObject(self, unsafeAddressOf(XWVScriptObject)) as? XWVScriptObject if let namespace = namespace as? String, let webView = scriptObject?.channel.webView { if let obj = bind(webView, namespace: namespace) { _Promise.callMethod("resolve", withArguments: [obj], resultHandler: nil) } else { _Promise.callMethod("reject", withArguments: nil, resultHandler: nil) } } } private func bind(webView: WKWebView, namespace: String) -> XWVScriptObject? { if let spec = bindings[namespace], let plugin: AnyClass = inventory[spec.pluginID] { if let object: AnyObject = instantiateClass(plugin, withArgument: spec.argument) { let queue = spec.mainThread ? dispatch_get_main_queue() : pluginQueue let channel = XWVChannel(name: spec.channelName, webView: webView, queue: queue) return channel.bindPlugin(object, toNamespace: namespace) } println("ERROR: Failed to create instance of plugin '\(spec.pluginID)'.") } else if let spec = bindings[namespace] { println("ERROR: Plugin '\(spec.pluginID)' not found.") } else { println("ERROR: Namespace '\(namespace)' has no binding") } return nil } private func instantiateClass(cls: AnyClass, withArgument argument: AnyObject?) -> AnyObject? { //XWAPluginFactory.self // a trick to access static method of protocol if class_conformsToProtocol(cls, XWAPluginSingleton.self) { return cls.instance() } else if class_conformsToProtocol(cls, XWAPluginFactory.self) { if argument != nil && cls.createInstanceWithArgument != nil { return cls.createInstanceWithArgument!(argument) } return cls.createInstance() } var initializer = Selector("initWithArgument:") var args: [AnyObject]! if class_respondsToSelector(cls, initializer) { args = [ argument ?? NSNull() ] } else { initializer = Selector("init") if !class_respondsToSelector(cls, initializer) { return cls as AnyObject } } return XWVInvocation.construct(cls, initializer: initializer, arguments: args) } } extension XWAPluginBinding { subscript (namespace: String) -> Descriptor? { get { return bindings[namespace] } set { bindings[namespace] = newValue } } }
d1a7188f7c30aec4d801e219279e3c24
38.746269
111
0.623733
false
false
false
false
davidear/swiftsome
refs/heads/master
JokeClient-Swift/JokeClient-Swift/Utility/FileUtility.swift
mit
1
// // FileUtility.swift // JokeClient-Swift // // Created by YANGReal on 14-6-7. // Copyright (c) 2014年 YANGReal. All rights reserved. // import UIKit class FileUtility: NSObject { class func cachePath(fileName:String)->String { var arr = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) var path = arr[0] as! String return "\(path)/\(fileName)" } class func imageCacheToPath(path:String,image:NSData)->Bool { return image.writeToFile(path, atomically: true) } class func imageDataFromPath(path:String)->AnyObject { var exist = NSFileManager.defaultManager().fileExistsAtPath(path) if exist { //var urlStr = NSURL.fileURLWithPath(path) var data = NSData(contentsOfFile: path); //var img:UIImage? = UIImage(data:data!) //return img ?? NSNull() var img = UIImage(contentsOfFile: path) var url:NSURL? = NSURL.fileURLWithPath(path) var dd = NSFileManager.defaultManager().contentsAtPath(url!.path!) var jpg = UIImage(data:dd!) if img != nil { return img! } else { return NSNull() } } return NSNull() } }
ddd88e60de04f4ee8656198b5d09895e
24.181818
95
0.552347
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
examples/swift/SwiftClasses.playground/Pages/Initializers.xcplaygroundpage/Contents.swift
mit
3
//: ## Initializers //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) //: **** //: ### Default Initializers //: Classes and structures will have a default initializer if every stored property is initialized explicitly struct Point { var x = 0.0, y = 0.0 } let zero = Point() //: Structures also have a memeber-wise initializer struct Size { var width = 0, height = 0 } let square = Size(width: 100, height: 100) //: Classes don't have a memeber-wise initializer class Rectangle { var origin = Point() var size = Size() init(origin: Point, size: Size) { self.origin = origin self.size = size } } let rect = Rectangle(origin: zero, size: square) //: ### Designated and Convenience Initializers //: Classes have two types of initializers: //: - designated — fully initializes every property of the class //: - convenience — covers specific use case of initializetion parameters extension Rectangle { // Convenience initializers can be declared in extencions convenience init(center: Point, size: Size) { let originX = center.x - Double(size.width) / 2.0 let originY = center.y - Double(size.height) / 2.0 self.init(origin: Point(x: originX, y: originY), size: size) } } //: ### Initializers and Class Heirarchy //: If no designated initializers are declared, designated initializers of the superclass are inherited class DefaultTextBox: Rectangle { var text: String = "" } let def = DefaultTextBox(center: zero, size: square) def.text = "Hello!" //: Any designated initializer must call superclass initializer class TextBox: Rectangle { var text = "" init(text: String, origin: Point, size: Size) { self.text = text; super.init(origin: origin, size: size) } } //: Convenience initializers can not call super class initializer. They must call another initializer from the same class instead extension TextBox { convenience init(text: String, center: Point, size: Size) { let originX = center.x - Double(size.width) / 2 let originY = center.y - Double(size.height) / 2 self.init(text: text, origin: Point(x: originX, y: originY), size: size) } } //: ### Required Initializers //: You can require all subclasses to implement a specific initializer class Polygon { var points = [Point]() required init() {} } class RegularPolygon: Polygon { required init() {} } class Triangle: Polygon { required init() {} } //: ### Deinitializers class Star: Polygon { deinit { print("I was a Star!") } } //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) //: ****
b2bbb9696ebd6fc5b90508c4a5c0eecb
31.987805
129
0.663216
false
false
false
false
tjw/swift
refs/heads/master
stdlib/public/core/ContiguousArrayBuffer.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _sanityCheckFailure("creating instance of _EmptyArrayStorage") } #if _runtime(_ObjC) @inlinable override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { return 0 } @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { return _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, 0, 0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage : _EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline internal final class _ContiguousArrayStorage< Element > : _ContiguousArrayStorageBase { @inlinable // FIXME(sil-serialize-all) deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. @inlinable internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. @inlinable internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, count, count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @usableFromInline @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: _ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @inlinable internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _sanityCheck(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _sanityCheck(newValue >= 0) _sanityCheck( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _sanityCheck(bounds.lowerBound >= 0) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. NOTE: this does not mean /// the buffer is mutable; see the comment on isUniquelyReferenced. @inlinable internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isUniqueOrPinned(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @inlinable internal func _asCocoaArray() -> _NSArrayCore { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return _SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _sanityCheck(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @usableFromInline internal var _storage: _ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } internal typealias Indices = Range<Int> } extension Sequence { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) var p = result.firstElementAddress var i = source.startIndex for _ in 0..<count { // FIXME(performance): use _copyContents(initializing:). p.initialize(to: source[i]) source.formIndex(after: &i) p += 1 } _expectEnd(of: source, is: i) return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writting to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _sanityCheck(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _sanityCheck(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
a62a529c40787582218e1e6b42eb1930
30.360743
110
0.696397
false
false
false
false
jwfriese/FrequentFlyer
refs/heads/master
FrequentFlyer/Visuals/UnderlineTextField/UnderlineTextField.swift
apache-2.0
1
import UIKit class UnderlineTextField: UIView { private var contentView: UIView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let viewPackage = Bundle.main.loadNibNamed("UnderlineTextField", owner: self, options: nil) guard let loadedView = viewPackage?.first as? UIView else { print("Failed to load nib with name 'UnderlineTextField'") return } contentView = loadedView addSubview(contentView) contentView.bounds = bounds autoresizesSubviews = true autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] backgroundColor = UIColor.clear contentView.backgroundColor = UIColor.clear underline?.backgroundColor = Style.Colors.titledTextFieldUnderlineColor } override func layoutSubviews() { super.layoutSubviews() contentView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // Because this view contains the actual text view, explicitly give it a chance // to claim a touch it otherwise wouldn't. if let hitTextField = textField?.hitTest(point, with: event) { return hitTextField } return super.hitTest(point, with: event) } private weak var cachedTextField: UnderlineTextFieldTextField? weak var textField: UnderlineTextFieldTextField? { get { if cachedTextField != nil { return cachedTextField } let textField = contentView.subviews.filter { subview in return subview.isKind(of: UnderlineTextFieldTextField.self) }.first as? UnderlineTextFieldTextField cachedTextField = textField return cachedTextField } } private weak var cachedUnderline: Underline? private weak var underline: Underline? { get { if cachedUnderline != nil { return cachedUnderline } let underline = contentView.subviews.filter { subview in return subview.isKind(of: Underline.self) }.first as? Underline cachedUnderline = underline return cachedUnderline } } }
da9b2053092debe80e0f9196ee264d32
34.469697
99
0.648441
false
false
false
false
XLabKC/Badger
refs/heads/master
Badger/Badger/TeamCell.swift
gpl-2.0
1
import UIKit class TeamCell: BorderedCell { private var hasAwakened = false private var team: Team? @IBOutlet weak var teamCircle: TeamCircle! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var arrowImage: UIImageView! override func awakeFromNib() { self.hasAwakened = true self.updateView() } func setTeam(team: Team) { self.team = team self.updateView() } private func updateView() { if self.hasAwakened { if let team = self.team { self.teamCircle.setTeam(team) self.nameLabel.text = team.name } } } }
76a03ac4240d45e5d5d96cd07dfbdd39
21.896552
47
0.585843
false
false
false
false
younata/RSSClient
refs/heads/master
Tethys/ExplanationView.swift
mit
1
import UIKit import PureLayout public final class ExplanationView: UIView { public var title: String { get { return self.titleLabel.text ?? "" } set { self.titleLabel.text = newValue } } public var detail: String { get { return self.detailLabel.text ?? "" } set { self.detailLabel.text = newValue } } private let titleLabel = UILabel(forAutoLayout: ()) private let detailLabel = UILabel(forAutoLayout: ()) public override init(frame: CGRect) { super.init(frame: frame) self.titleLabel.textAlignment = .center self.titleLabel.numberOfLines = 0 self.titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline) self.detailLabel.textAlignment = .center self.detailLabel.numberOfLines = 0 self.detailLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) self.addSubview(self.titleLabel) self.addSubview(self.detailLabel) self.titleLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20), excludingEdge: .bottom) self.detailLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 8, bottom: 8, right: 8), excludingEdge: .top) self.detailLabel.autoPinEdge(.top, to: .bottom, of: self.titleLabel, withOffset: 8) self.layer.cornerRadius = 4 self.isAccessibilityElement = true self.isUserInteractionEnabled = false self.accessibilityTraits = [.staticText] self.applyTheme() } public required init?(coder aDecoder: NSCoder) { fatalError() } private func applyTheme() { self.titleLabel.textColor = Theme.textColor self.detailLabel.textColor = Theme.textColor } }
a8b57fd157f53efdec45e3940949bb2f
33.037736
113
0.670177
false
false
false
false
sendyhalim/iYomu
refs/heads/master
Yomu/Screens/MangaList/MangaCollectionViewModel.swift
mit
1
// // MangaCollectionViewModel.swift // Yomu // // Created by Sendy Halim on 6/16/17. // Copyright © 2017 Sendy Halim. All rights reserved. // import OrderedSet import class RealmSwift.Realm import RxCocoa import RxMoya import RxSwift import RxRealm import Swiftz struct SelectedIndex { let previousIndex: Int let index: Int } struct MangaCollectionViewModel { // MARK: Public var count: Int { return _mangas.value.count } // MARK: Output let fetching: Driver<Bool> let showEmptyDataSetLoading: Driver<Void> let reload: Driver<Void> // MARK: Private fileprivate let _selectedIndex = Variable(SelectedIndex(previousIndex: -1, index: -1)) fileprivate var _fetching = Variable(false) fileprivate var _mangas: Variable<OrderedSet<MangaViewModel>> = { let mangas = Database .queryMangas() .sorted { $0.position < $1.position } .map(MangaViewModel.init) return Variable(OrderedSet(elements: mangas)) }() fileprivate let deletedManga = PublishSubject<MangaViewModel>() fileprivate let addedManga = PublishSubject<MangaViewModel>() fileprivate let disposeBag = DisposeBag() init() { fetching = _fetching.asDriver() reload = _mangas .asDriver() .map { _ in () } deletedManga .map { manga in return Database.queryMangaRealm(id: manga.id) } .subscribe(Realm.rx.delete()) .disposed(by: disposeBag) addedManga .map { MangaRealm.from(manga: $0.manga) } .subscribe(Realm.rx.add(update: true)) .disposed(by: disposeBag) // We want to show empty data set loading view if manga count is 0 and we're in the fetching state showEmptyDataSetLoading = Driver .combineLatest( fetching, _mangas.asDriver().map { $0.count == 0 } ) .map { $0 && $1 } .filter(identity) .map { _ in () } } subscript(index: Int) -> MangaViewModel { return _mangas.value[index] } func fetch(id: String) -> Disposable { let api = MangaEdenAPI.mangaDetail(id) let request = MangaEden.request(api).share() let newMangaObservable = request .filterSuccessfulStatusCodes() .map(Manga.self) .map { var manga = $0 manga.id = id manga.position = self.count return MangaViewModel(manga: manga) } .filter { return !self._mangas.value.contains($0) } .share() let fetchingDisposable = request .map(const(false)) .startWith(true) .asDriver(onErrorJustReturn: false) .drive(_fetching) let resultDisposable = newMangaObservable.subscribe(onNext: { self.addedManga.on(.next($0)) self._mangas.value.append(element: $0) }) return CompositeDisposable(fetchingDisposable, resultDisposable) } func setSelectedIndex(_ index: Int) { let previous = _selectedIndex.value let selectedIndex = SelectedIndex(previousIndex: previous.index, index: index) _selectedIndex.value = selectedIndex } func move(fromIndex: Int, toIndex: Int) { let mangaViewModel = self[fromIndex] _mangas.value.remove(index: fromIndex) _mangas.value.insert(element: mangaViewModel, atIndex: toIndex) updateMangaPositions() } func remove(mangaViewModel: MangaViewModel) { let manga = _mangas.value.remove(element: mangaViewModel)! deletedManga.on(.next(manga)) updateMangaPositions() } private func updateMangaPositions() { let indexes: [Int] = [Int](0..<self.count) indexes.forEach { _mangas.value[$0].update(position: $0) } } }
69f6e12b5ddc132f9858276f9f687df1
23.513514
102
0.652977
false
false
false
false
AlbertXYZ/HDCP
refs/heads/dev
BarsAroundMe/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift
apache-2.0
47
// // Window.swift // RxSwift // // Created by Junior B. on 29/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class WindowTimeCountSink<Element, O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType where O.E == Observable<Element> { typealias Parent = WindowTimeCount<Element> typealias E = Element private let _parent: Parent let _lock = RecursiveLock() private var _subject = PublishSubject<Element>() private var _count = 0 private var _windowId = 0 private let _timerD = SerialDisposable() private let _refCountDisposable: RefCountDisposable private let _groupDisposable = CompositeDisposable() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent let _ = _groupDisposable.insert(_timerD) _refCountDisposable = RefCountDisposable(disposable: _groupDisposable) super.init(observer: observer, cancel: cancel) } func run() -> Disposable { forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) createTimer(_windowId) let _ = _groupDisposable.insert(_parent._source.subscribe(self)) return _refCountDisposable } func startNewWindowAndCompleteCurrentOne() { _subject.on(.completed) _subject = PublishSubject<Element>() forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable())) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { var newWindow = false var newId = 0 switch event { case .next(let element): _subject.on(.next(element)) do { let _ = try incrementChecked(&_count) } catch (let e) { _subject.on(.error(e as Swift.Error)) dispose() } if (_count == _parent._count) { newWindow = true _count = 0 _windowId += 1 newId = _windowId self.startNewWindowAndCompleteCurrentOne() } case .error(let error): _subject.on(.error(error)) forwardOn(.error(error)) dispose() case .completed: _subject.on(.completed) forwardOn(.completed) dispose() } if newWindow { createTimer(newId) } } func createTimer(_ windowId: Int) { if _timerD.isDisposed { return } if _windowId != windowId { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer let scheduledRelative = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in var newId = 0 self._lock.performLocked { if previousWindowId != self._windowId { return } self._count = 0 self._windowId = self._windowId &+ 1 newId = self._windowId self.startNewWindowAndCompleteCurrentOne() } self.createTimer(newId) return Disposables.create() } nextTimer.setDisposable(scheduledRelative) } } final class WindowTimeCount<Element> : Producer<Observable<Element>> { fileprivate let _timeSpan: RxTimeInterval fileprivate let _count: Int fileprivate let _scheduler: SchedulerType fileprivate let _source: Observable<Element> init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { _source = source _timeSpan = timeSpan _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Observable<Element> { let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
4f421c80bbcfb6ed396bb3a3672b4eb6
28.309211
157
0.561616
false
false
false
false
pvbaleeiro/movie-aholic
refs/heads/master
movieaholic/movieaholic/controller/main/ExploreFeedViewController.swift
mit
1
// // ExploreFeedViewController.swift // movieaholic // // Created by Victor Baleeiro on 23/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit import Foundation class ExploreFeedViewController: BaseTableController { //------------------------------------------------------------------------------------------------------------- // MARK: Propriedades //------------------------------------------------------------------------------------------------------------- let cellID = "cellID" var categories = ["Trending"] var moviesTrending: NSMutableArray! var moviesTrendingFiltered = NSMutableArray() var refreshControl: UIRefreshControl! var currentSearchText: String! = "" lazy var tbvMovies: UITableView = { let view = UITableView() view.translatesAutoresizingMaskIntoConstraints = false view.dataSource = self view.delegate = self view.register(CategoryTableViewCell.self, forCellReuseIdentifier: self.cellID) view.rowHeight = 300 view.separatorStyle = .none view.showsVerticalScrollIndicator = false view.allowsSelection = false return view }() //------------------------------------------------------------------------------------------------------------- // MARK: Ciclo de vida //------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() setLayout() setData() } //------------------------------------------------------------------------------------------------------------- // MARK: Sets //------------------------------------------------------------------------------------------------------------- func setLayout() { //Define layout table view view.addSubview(tbvMovies) tbvMovies.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true tbvMovies.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true tbvMovies.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true tbvMovies.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true //Refresh control para a tabela refreshControl = tbvMovies.addRefreshControl(target: self, action: #selector(doRefresh(_:))) refreshControl.tintColor = UIColor.primaryColor() refreshControl.attributedTitle = NSAttributedString(string: "Buscando dados...", attributes: [ NSAttributedStringKey.backgroundColor: UIColor.black.withAlphaComponent(0.6), NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 25) ]) } func setData() { buscaDados(forceUpdate: false) } //------------------------------------------------------------------------------------------------------------- // MARK: Acoes //------------------------------------------------------------------------------------------------------------- @objc func doRefresh(_ sender: UIRefreshControl) { //Busca dados buscaDados(forceUpdate: true) UIView.animate(withDuration: 0.1, animations: { self.view.tintColor = self.view.backgroundColor // store color self.view.backgroundColor = UIColor.white }) { (Bool) in self.view.backgroundColor = self.view.tintColor // restore color } } func buscaDados(forceUpdate: Bool) { //Buscar os dados APIMovie.getTrendingMovies(forceUpdate: forceUpdate) { (response) in switch response { case .onSuccess(let trendingMovies as NSMutableArray): //Obtem resposta e atribui à lista self.moviesTrending = trendingMovies self.tbvMovies.reloadData() self.refreshControl.endRefreshing() break case .onError(let erro): print(erro) self.refreshControl.endRefreshing() break case .onNoConnection(): print("Sem conexão") self.refreshControl.endRefreshing() break default: break } } } } //------------------------------------------------------------------------------------------------------------- // MARK: UITableViewDataSource //------------------------------------------------------------------------------------------------------------- extension ExploreFeedViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return categories.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (moviesTrending != nil) { return 1 } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CategoryTableViewCell cell.title = categories[indexPath.section] if (moviesTrendingFiltered.count > 0 || !self.currentSearchText.isEmpty) { cell.items = moviesTrendingFiltered as! [MovieTrending] } else { cell.items = moviesTrending as! [MovieTrending] } cell.indexPath = indexPath // needed for dismiss animation if let parent = parent as? CategoryTableViewCellDelegate { cell.delegate = parent } return cell } } extension ExploreFeedViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filter(searchText: searchBar.text!) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { filter(searchText: searchBar.text!) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.text = "" self.currentSearchText = "" self.moviesTrendingFiltered = NSMutableArray() self.tbvMovies.reloadData() } func filter(searchText: String) { //Filtrar filmes self.currentSearchText = searchText if !self.currentSearchText.isEmpty { let swiftArray = NSArray(array:moviesTrending) as! Array<MovieTrending> var swiftArrayFilter: Array<MovieTrending> swiftArrayFilter = swiftArray.filter { movie in return (movie.movie?.title?.lowercased().contains(self.currentSearchText.lowercased()))! } self.moviesTrendingFiltered = NSMutableArray(array: swiftArrayFilter) self.tbvMovies.reloadData() } else { self.moviesTrendingFiltered = NSMutableArray() self.tbvMovies.reloadData() } } }
4a88c9a72b5c6dd2647f83e150125e5e
36.167513
115
0.513521
false
false
false
false
Sidetalker/TapMonkeys
refs/heads/master
TapMonkeys/TapMonkeys/MonkeyViewController.swift
mit
1
// // MonkeyViewController.swift // TapMonkeys // // Created by Kevin Sullivan on 5/9/15. // Copyright (c) 2015 Kevin Sullivan. All rights reserved. // import UIKit class MonkeyViewController: UIViewController { @IBOutlet weak var dataHeader: DataHeader! var monkeyTable: MonkeyTableViewController? var nightMode = false override func viewDidLoad() { super.viewDidLoad() } override func prefersStatusBarHidden() -> Bool { return true } override func viewWillAppear(animated: Bool) { self.tabBarItem.badgeValue = nil let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("updateHeaders", object: self, userInfo: [ "letters" : 0, "animated" : true ]) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueMonkeyTable" { monkeyTable = segue.destinationViewController as? MonkeyTableViewController } } func toggleNightMode(nightMode: Bool) { self.nightMode = nightMode self.view.backgroundColor = self.nightMode ? UIColor.lightTextColor() : UIColor.blackColor() self.tabBarController?.tabBar.setNeedsDisplay() monkeyTable?.toggleNightMode(nightMode) } } class MonkeyTableViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, AnimatedLockDelegate, MonkeyBuyButtonDelegate { var nightMode = false override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 232 } func toggleNightMode(nightMode: Bool) { self.nightMode = nightMode self.view.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor() self.tableView.reloadData() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return count(monkeys) == 0 ? 0 : 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count(monkeys) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let saveData = load(self.tabBarController) if !saveData.monkeyCollapsed![indexPath.row] { return monkeys[indexPath.row].unlocked ? UITableViewAutomaticDimension : 232 } else { return monkeys[indexPath.row].unlocked ? 60 : 232 } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let saveData = load(self.tabBarController) let index = indexPath.row if saveData.monkeyCollapsed![index] { return } let curMonkey = monkeys[index] if !curMonkey.unlocked { if let lockView = cell.contentView.viewWithTag(8) as? AnimatedLockView { // We're good to go I guess } else { let lockView = AnimatedLockView(frame: cell.contentView.frame) lockView.tag = 8 lockView.index = indexPath.row lockView.delegate = self lockView.type = .Monkey lockView.nightMode = nightMode lockView.customize(load(self.tabBarController)) cell.contentView.addSubview(lockView) } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let saveData = load(self.tabBarController) let index = indexPath.row let curMonkey = monkeys[index] if !saveData.monkeyCollapsed![index] { if let cell = self.tableView.dequeueReusableCellWithIdentifier("cellMonkey") as? UITableViewCell, pic = cell.viewWithTag(1) as? UIImageView, name = cell.viewWithTag(2) as? UILabel, owned = cell.viewWithTag(3) as? UILabel, frequency = cell.viewWithTag(4) as? UILabel, total = cell.viewWithTag(5) as? AutoUpdateLabel, buyButton = cell.viewWithTag(6) as? MonkeyBuyButton, description = cell.viewWithTag(7) as? UILabel { let curPrice = curMonkey.getPrice(1).0 pic.image = UIImage(named: curMonkey.imageName) pic.alpha = nightMode ? 0.5 : 1.0 buyButton.monkeyIndex = index buyButton.delegate = self buyButton.nightMode = nightMode buyButton.setNeedsDisplay() total.index = index total.controller = self.tabBarController as? TabBarController total.type = .Monkey name.text = curMonkey.name description.text = curMonkey.description owned.text = "Owned: \(curMonkey.count)" frequency.text = "Letters/sec: \(curMonkey.lettersPerSecondCumulative())" total.text = "Total Letters: \(curMonkey.totalProduced)" name.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() description.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() owned.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() frequency.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() total.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() cell.contentView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor() if let lockView = cell.contentView.viewWithTag(8) as? AnimatedLockView { lockView.index = index lockView.type = .Monkey lockView.customize(load(self.tabBarController)) if curMonkey.unlocked { lockView.removeFromSuperview() } } else { if pic.gestureRecognizers == nil { let briefHold = UILongPressGestureRecognizer(target: self, action: "heldPic:") pic.addGestureRecognizer(briefHold) } } return cell } } else { if let cell = self.tableView.dequeueReusableCellWithIdentifier("cellMonkeyMini") as? UITableViewCell, pic = cell.viewWithTag(1) as? UIImageView, name = cell.viewWithTag(2) as? UILabel { pic.image = UIImage(named: curMonkey.imageName) pic.alpha = nightMode ? 0.5 : 1.0 name.text = curMonkey.name name.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() cell.contentView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor() if pic.gestureRecognizers == nil { let briefHold = UILongPressGestureRecognizer(target: self, action: "heldPic:") pic.addGestureRecognizer(briefHold) } return cell } } return UITableViewCell() } func heldPic(sender: UILongPressGestureRecognizer) { if sender.state != UIGestureRecognizerState.Began { return } var saveData = load(self.tabBarController) let location = sender.locationInView(self.tableView) let indexPath = tableView.indexPathForRowAtPoint(location) let index = indexPath!.row self.tableView.beginUpdates() saveData.monkeyCollapsed![index] = !saveData.monkeyCollapsed![index] save(self.tabBarController, saveData) self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic) self.tableView.endUpdates() } func tappedLock(view: AnimatedLockView) { var saveData = load(self.tabBarController) let index = view.index for cost in monkeys[index].unlockCost { if saveData.incomeCounts![Int(cost.0)] < Int(cost.1) { return } } for cost in monkeys[index].unlockCost { saveData.incomeCounts![Int(cost.0)] -= Int(cost.1) incomes[Int(cost.0)].count -= Int(cost.1) } view.unlock() saveData.monkeyUnlocks![index] = true monkeys[index].unlocked = true if index + 1 <= count(monkeys) - 1 { var paths = [NSIndexPath]() self.tableView.beginUpdates() for i in index + 1...count(monkeys) - 1 { paths.append(NSIndexPath(forRow: i, inSection: 0)) } self.tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.None) self.tableView.endUpdates() } save(self.tabBarController, saveData) } // REFACTOR you wrote this all stupid cause you wanted to move on func buyTapped(monkeyIndex: Int) { var saveData = load(self.tabBarController) var monkey = monkeys[monkeyIndex] if monkey.canPurchase(1, data: saveData) { var price = monkey.getPrice(1).0 * -1 saveData = monkey.purchase(1, data: saveData)! monkeys[monkeyIndex] = monkey save(self.tabBarController, saveData) let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("updateHeaders", object: self, userInfo: [ "money" : price, "animated" : false ]) nc.postNotificationName("updateMonkeyProduction", object: self, userInfo: nil) delay(0.2, { self.tableView.reloadData() // self.tableView.beginUpdates() // // self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: monkeyIndex, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None) // // self.tableView.endUpdates() }) } } } protocol MonkeyBuyButtonDelegate { func buyTapped(monkeyIndex: Int) } class MonkeyBuyButton: UIView { // 0 is 1 only, 1 is 1 | 10, 2 is 1 | 10 | 100 // Like, maybe var state = 0 var monkeyIndex = -1 var nightMode = false var delegate: MonkeyBuyButtonDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clearColor() let tap = UILongPressGestureRecognizer(target: self, action: "tappedMe:") tap.minimumPressDuration = 0.0 self.addGestureRecognizer(tap) } override func drawRect(rect: CGRect) { let price = monkeys[monkeyIndex].getPrice(1).0 let text = currencyFormatter.stringFromNumber(price)! let color = nightMode ? UIColor.lightTextColor() : UIColor.blackColor() TapStyle.drawBuy(frame: rect, colorBuyBorder: color, colorBuyText: color, buyText: text) } func tappedMe(sender: UITapGestureRecognizer) { if sender.state == UIGestureRecognizerState.Began { UIView.animateWithDuration(0.15, animations: { self.transform = CGAffineTransformMakeScale(0.91, 0.91) }) } else if sender.state == UIGestureRecognizerState.Ended { self.delegate?.buyTapped(self.monkeyIndex) UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in self.transform = CGAffineTransformIdentity }, completion: { (Bool) -> Void in }) } } }
40d55b6ae79c9511b409ffa18b15c23f
36.504425
195
0.576025
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
refs/heads/develop
Carthage/Checkouts/RxSwift/RxExample/RxExample-iOSTests/UIImagePickerController+RxTests.swift
mit
12
// // UIImagePickerController+RxTests.swift // RxExample // // Created by Segii Shulga on 1/6/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) import RxSwift import RxCocoa import XCTest import UIKit import RxExample_iOS class UIImagePickerControllerTests: RxTest { } extension UIImagePickerControllerTests { func testDidFinishPickingMediaWithInfo() { var completed = false var info:[String:AnyObject]? let pickedInfo = [UIImagePickerControllerOriginalImage : UIImage()] autoreleasepool { let imagePickerController = UIImagePickerController() _ = imagePickerController.rx.didFinishPickingMediaWithInfo .subscribe(onNext: { (i) -> Void in info = i }, onCompleted: { completed = true }) imagePickerController.delegate! .imagePickerController!(imagePickerController,didFinishPickingMediaWithInfo:pickedInfo) } XCTAssertTrue(info?[UIImagePickerControllerOriginalImage] === pickedInfo[UIImagePickerControllerOriginalImage]) XCTAssertTrue(completed) } func testDidCancel() { var completed = false var canceled = false autoreleasepool { let imagePickerController = UIImagePickerController() _ = imagePickerController.rx.didCancel .subscribe(onNext: { (i) -> Void in canceled = true }, onCompleted: { completed = true }) imagePickerController.delegate!.imagePickerControllerDidCancel!(imagePickerController) } XCTAssertTrue(canceled) XCTAssertTrue(completed) } } #endif
dba91a19b250d906d097f831b60c563b
25.378378
119
0.574795
false
true
false
false
jshultz/ios9-swift2-memorable-places
refs/heads/master
memorable-places/LocationViewController.swift
mit
1
// // LocationViewController.swift // memorable-places // // Created by Jason Shultz on 10/18/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit import CoreData class LocationViewController: UIViewController { var place: Places? = nil @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var streetLabel: UILabel! @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } //-- fetch data from CoreData --// func fetchLocation () { if place != nil { titleLabel.text = place?.title descriptionLabel.text = place?.user_description streetLabel.text = place?.street cityLabel.text = place?.locality stateLabel.text = place?.administrativeArea } } override func viewWillAppear(animated: Bool) { fetchLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "mapSegue" { let mapController:MapViewController = segue.destinationViewController as! MapViewController mapController.place = place } else if segue.identifier == "editPlace" { let editController:EditLocationViewController = segue.destinationViewController as! EditLocationViewController editController.place = place } } }
84028309b3fac685bbe8bc3f7d9517b3
27.555556
122
0.651751
false
false
false
false
nwdl/the-more-you-know-ios
refs/heads/master
TheMoreYouKnow/ZeroAutoLayoutViewController.swift
mit
1
// // ZeroAutoLayoutViewController.swift // TheMoreYouKnow // // Created by Nate Walczak on 5/21/15. // Copyright (c) 2015 Detroit Labs, LLC. All rights reserved. // import UIKit class ZeroAutoLayoutViewController : UIViewController { @IBOutlet weak var upperLeftView: UIView! @IBOutlet weak var upperLeftViewCenterXLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var upperLeftViewCenterYLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var upperRightView: UIView! @IBOutlet weak var upperRightViewCenterXLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var upperRightViewCenterYLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var bottomViewCenterYLayoutConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // onlyShowUpperViews() // red and green // onlyShowUpperLeftView() // red // onlyShowUpperRightView() // green // onlyShowUpperLeftViewAndBottomView() // red and blue // onlyShowUpperRightViewAndBottomView() // green and blue // onlyShowBottomViews() // blue } func onlyShowUpperViews() { upperLeftViewCenterYLayoutConstraint.constant = 0 upperRightViewCenterYLayoutConstraint.constant = 0 bottomView.hidden = true } func onlyShowUpperLeftView() { upperLeftViewCenterXLayoutConstraint.constant = 0 upperLeftViewCenterYLayoutConstraint.constant = 0 upperRightView.hidden = true bottomView.hidden = true } func onlyShowUpperRightView() { upperLeftView.hidden = true upperRightViewCenterXLayoutConstraint.constant = 0 upperRightViewCenterYLayoutConstraint.constant = 0 bottomView.hidden = true } func onlyShowUpperLeftViewAndBottomView() { upperLeftViewCenterXLayoutConstraint.constant = 0 upperRightView.hidden = true } func onlyShowUpperRightViewAndBottomView() { upperLeftView.hidden = true upperRightViewCenterXLayoutConstraint.constant = 0 } func onlyShowBottomViews() { upperLeftView.hidden = true upperRightView.hidden = true bottomViewCenterYLayoutConstraint.constant = 0 } }
926a168f680bc17b126dd8a623bdbebb
31.774648
81
0.703051
false
false
false
false
DuostecDalian/Meijiabang
refs/heads/master
KickYourAss/KickYourAss/RegisterTextCell.swift
mit
3
// // RegisterTextCell.swift // KickYourAss // // Created by eagle on 15/1/29. // Copyright (c) 2015年 宇周. All rights reserved. // import UIKit class RegisterTextCell: UITableViewCell { @IBOutlet private weak var icyImageView: UIImageView! @IBOutlet weak var icyTextField: UITextField! enum RegisterTextCellType: Int{ case PhoneNumber = 0 case Password case ConfirmPassword } var currentType: RegisterTextCellType = .PhoneNumber { didSet { switch currentType { case .PhoneNumber: icyImageView.image = UIImage(named: "loginUser") icyTextField.secureTextEntry = false icyTextField.placeholder = "输入手机号" icyTextField.keyboardType = UIKeyboardType.NumberPad case .Password: icyImageView.image = UIImage(named: "loginPassword") icyTextField.secureTextEntry = true icyTextField.placeholder = "输入密码" icyTextField.keyboardType = UIKeyboardType.ASCIICapable case .ConfirmPassword: icyImageView.image = UIImage(named: "loginConfirmPassword") icyTextField.secureTextEntry = true icyTextField.placeholder = "确认密码" icyTextField.keyboardType = UIKeyboardType.ASCIICapable } } } class var identifier: String { return "RegisterTextCellIdentifier" } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
8b0066b35a28cd507432b122aacc4906
29.655172
75
0.615298
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/People/WPStyleGuide+People.swift
gpl-2.0
2
import Foundation import WordPressShared extension WPStyleGuide { public struct People { public struct RoleBadge { // MARK: Metrics public static let padding = CGFloat(4) public static let borderWidth = CGFloat(1) public static let cornerRadius = CGFloat(2) // MARK: Typography public static var font: UIFont { return WPStyleGuide.fontForTextStyle(.caption2) } // MARK: Colors public static let textColor = UIColor.white } // MARK: Colors public static let superAdminColor = WPStyleGuide.fireOrange() public static let adminColor = WPStyleGuide.darkGrey() public static let editorColor = WPStyleGuide.darkBlue() public static let otherRoleColor = WPStyleGuide.wordPressBlue() } }
3927084c260394c87806a44894da8cc4
31.296296
71
0.620413
false
false
false
false
pyromobile/nubomedia-ouatclient-src
refs/heads/master
ios/LiveTales/uoat/LoginSignupViewController.swift
apache-2.0
1
// // LoginSignupViewController.swift // uoat // // Created by Pyro User on 10/5/16. // Copyright © 2016 Zed. All rights reserved. // import UIKit class LoginSignupViewController: UIViewController { weak var user:User! weak var delegate:LoginSignupDelegate? required init?(coder aDecoder: NSCoder) { self.preparedKeyboard = false self.adjustedKeyboard = false super.init(coder: aDecoder) } deinit { self.user = nil self.delegate = nil NSNotificationCenter.defaultCenter().removeObserver( self ) print("LoginSignupViewController - deInit....OK") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //Load resources //Arrow image (flipped). let leftArrowActiveImage:UIImage = Utils.flipImage(named: "btn_next_available", orientation: .Down) self.closeButton.setBackgroundImage( leftArrowActiveImage, forState: .Normal ) self.closeButton.setBackgroundImage( leftArrowActiveImage, forState: .Highlighted ) //Title header. //.:Log In let loginAttrString = NSMutableAttributedString(string: self.loginHeader.text!, attributes: [NSStrokeWidthAttributeName: -7.0, NSFontAttributeName: UIFont(name: "ArialRoundedMTBold", size: 22)!, NSStrokeColorAttributeName: UIColor.whiteColor(), NSForegroundColorAttributeName: self.loginHeader.textColor ]) self.loginHeader.attributedText! = loginAttrString //.:Sign Up let signupAttrString = NSMutableAttributedString(string: self.signupHeader.text!, attributes: [NSStrokeWidthAttributeName: -7.0, NSFontAttributeName: UIFont(name: "ArialRoundedMTBold", size: 22)!, NSStrokeColorAttributeName: UIColor.whiteColor(), NSForegroundColorAttributeName: self.signupHeader.textColor ]) self.signupHeader.attributedText! = signupAttrString //Keyboard self.loginUserField.addTarget(self, action: #selector(LoginSignupViewController.cleanKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) self.loginPasswordField.addTarget(self, action: #selector(LoginSignupViewController.cleanKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) self.signupUserField.addTarget(self, action: #selector(LoginSignupViewController.prepareKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) self.signupPasswordField.addTarget(self, action: #selector(LoginSignupViewController.prepareKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) self.signupPasswordRepeatField.addTarget(self, action: #selector(LoginSignupViewController.prepareKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) //Add blur efect to hide the last view. let blurEffectView:UIVisualEffectView = Utils.blurEffectView(self.view, radius: 10) self.view.addSubview(blurEffectView) self.view.sendSubviewToBack(blurEffectView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { 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. } */ func prepareKeyboard( sender:UITextField ) { if( !self.preparedKeyboard ) { self.preparedKeyboard = true //Keyboard. NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(LoginSignupViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(LoginSignupViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil ) } } func cleanKeyboard( sender:UITextField ) { self.preparedKeyboard = false //Keyboard. NSNotificationCenter.defaultCenter().removeObserver( self ) } func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) { guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } let keyboardFrame = value.CGRectValue() let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 0) * (show ? -1 : 1) self.view.frame.offsetInPlace(dx: 0, dy: adjustmentHeight ) } func keyboardWillShow(notification: NSNotification) { if(!self.adjustedKeyboard) { self.adjustedKeyboard = true adjustInsetForKeyboardShow(true, notification: notification) } } func keyboardWillHide(notification: NSNotification) { self.adjustedKeyboard = false adjustInsetForKeyboardShow(false, notification: notification) } /*=============================================================*/ /* UI Section */ /*=============================================================*/ @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var loginHeader: UILabel! @IBOutlet weak var loginUserField: UITextField! @IBOutlet weak var loginPasswordField: UITextField! @IBOutlet weak var signupHeader: UILabel! @IBOutlet weak var signupUserField: UITextField! @IBOutlet weak var signupPasswordField: UITextField! @IBOutlet weak var signupPasswordRepeatField: UITextField! //--------------------------------------------------------------- // UI Actions //--------------------------------------------------------------- @IBAction func back() { //Hide keyboard. self.view.endEditing( true ); self.dismissViewControllerAnimated(true, completion: {}) } @IBAction func login() { if( NetworkWatcher.internetAvailabe ) { if( self.loginUserField.text?.isEmpty == false && self.loginPasswordField.text?.isEmpty == false ) { let user:String = self.loginUserField.text! let password:String = self.loginPasswordField.text! self.doLogin( user, password:password ) } else { Utils.alertMessage( self, title:"Warning!", message:"You must fill two fields.", onAlertClose:nil ) } } else { //Hide keyboard. self.view.endEditing( true ); Utils.alertMessage(self, title: "Attention", message: "Internet connection lost!", onAlertClose: { [unowned self] (action) in self.dismissViewControllerAnimated( true, completion:{} ) }) } } @IBAction func signup() { if( NetworkWatcher.internetAvailabe ) { if( self.signupUserField.text?.isEmpty == false && self.signupPasswordField.text?.isEmpty == false && self.signupPasswordRepeatField.text?.isEmpty == false ) { if( self.signupPasswordField.text == signupPasswordRepeatField.text ) { let user:String = self.signupUserField.text! let password:String = self.signupPasswordField.text! self.doSignup( user, password:password ) } else { Utils.alertMessage( self, title:"Error!", message:"The passwords not missmatch", onAlertClose:nil ) } } else { Utils.alertMessage( self, title:"Warning!", message:"You must fill three fields.", onAlertClose:nil ) } } else { Utils.alertMessage(self, title: "Attention", message: "Internet connection lost!", onAlertClose: { [unowned self] (action) in //Hide keyboard. self.view.endEditing( true ); self.dismissViewControllerAnimated(true, completion: {}) }) } } /*=============================================================*/ /* Private Section */ /*=============================================================*/ private func doLogin( userName:String, password: String ) { UserModel.login( userName, password:Utils.md5(string:password)) { [weak self](isOK, userId, nick, code) in if( isOK ) { //Hide keyboard. self!.view.endEditing( true ); self!.user.setProfile( userId, name:userName, password:password, secretCode: code ) self!.user.nick = nick self!.dismissViewControllerAnimated(true, completion: {[weak self] in self!.delegate?.onLoginSignupReady() }) } else { Utils.alertMessage( self!, title:"Error", message:"User or password wrong!", onAlertClose:nil ) } } } private func doSignup( userName:String, password:String ) { let secretCode:String = Utils.randomString(10) UserModel.signup( userName, password:Utils.md5(string:password), secretCode:secretCode ) { [weak self](isOK,userId) in if( isOK ) { //Hide keyboard. self!.view.endEditing( true ); self!.user.setProfile( userId, name:userName, password:password, secretCode:secretCode ) self!.user.nick = "Guest" self!.dismissViewControllerAnimated( true, completion:{[weak self] in self!.delegate?.onLoginSignupReady() }) } else { Utils.alertMessage( self!, title:"Error", message:"User or password wrong!", onAlertClose:nil ) } } } private var preparedKeyboard:Bool private var adjustedKeyboard:Bool }
dedc9444e55525a10d5c99793052eef4
38.374074
188
0.586022
false
false
false
false
fnazarios/weather-app
refs/heads/dev
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Map.swift
apache-2.0
4
// // Map.swift // Rx // // Created by Krunoslav Zaher on 3/15/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class MapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType { typealias ResultType = O.E typealias Element = SourceType typealias Parent = Map<SourceType, ResultType> private let _parent: Parent init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func performMap(element: SourceType) throws -> ResultType { abstractMethod() } func on(event: Event<SourceType>) { switch event { case .Next(let element): do { let mappedElement = try performMap(element) forwardOn(.Next(mappedElement)) } catch let e { forwardOn(.Error(e)) dispose() } case .Error(let error): forwardOn(.Error(error)) dispose() case .Completed: forwardOn(.Completed) dispose() } } } class MapSink1<SourceType, O: ObserverType> : MapSink<SourceType, O> { typealias ResultType = O.E override init(parent: Map<SourceType, ResultType>, observer: O) { super.init(parent: parent, observer: observer) } override func performMap(element: SourceType) throws -> ResultType { return try _parent._selector1!(element) } } class MapSink2<SourceType, O: ObserverType> : MapSink<SourceType, O> { typealias ResultType = O.E private var _index = 0 override init(parent: Map<SourceType, ResultType>, observer: O) { super.init(parent: parent, observer: observer) } override func performMap(element: SourceType) throws -> ResultType { return try _parent._selector2!(element, try incrementChecked(&_index)) } } class Map<SourceType, ResultType>: Producer<ResultType> { typealias Selector1 = (SourceType) throws -> ResultType typealias Selector2 = (SourceType, Int) throws -> ResultType private let _source: Observable<SourceType> private let _selector1: Selector1? private let _selector2: Selector2? init(source: Observable<SourceType>, selector: Selector1) { _source = source _selector1 = selector _selector2 = nil } init(source: Observable<SourceType>, selector: Selector2) { _source = source _selector2 = selector _selector1 = nil } override func run<O: ObserverType where O.E == ResultType>(observer: O) -> Disposable { if let _ = _selector1 { let sink = MapSink1(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } else { let sink = MapSink2(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } } }
3539407a170ecb4047350184eb5578a4
27.271028
91
0.596892
false
false
false
false
hooman/swift
refs/heads/main
libswift/Sources/SIL/Type.swift
apache-2.0
3
//===--- Type.swift - Value type ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SILBridging public struct Type { var bridged: BridgedType public var isAddress: Bool { SILType_isAddress(bridged) != 0 } public var isObject: Bool { !isAddress } }
f7d8cc2239ec837912e6acf8dd11471d
34.05
80
0.590585
false
false
false
false
thdtjsdn/realm-cocoa
refs/heads/master
RealmSwift-swift2.0/Object.swift
apache-2.0
1
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** In Realm you define your model classes by subclassing `Object` and adding properties to be persisted. You then instantiate and use your custom subclasses instead of using the Object class directly. ```swift class Dog: Object { dynamic var name: String = "" dynamic var adopted: Bool = false let siblings = List<Dog> } ``` ### Supported property types - `String` - `Int` - `Float` - `Double` - `Bool` - `NSDate` - `NSData` - `Object` subclasses for to-one relationships - `List<T: Object>` for to-many relationships ### Querying You can gets `Results` of an Object subclass via tha `objects(_:)` free function or the `objects(_:)` instance method on `Realm`. ### Relationships See our [Cocoa guide](http://realm.io/docs/cocoa) for more details. */ public class Object: RLMObjectBase { // MARK: Initializers /** Initialize a standalone (unpersisted) Object. Call `add(_:)` on a `Realm` to add standalone objects to a realm. :see: Realm().add(_:) */ public required override init() { super.init() } /** Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`. Call `add(_:)` on a `Realm` to add standalone objects to a realm. :param: value The value used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. */ public init(value: AnyObject) { super.init(value: value, schema: RLMSchema.sharedSchema()) } // MARK: Properties /// The `Realm` this object belongs to, or `nil` if the object /// does not belong to a realm (the object is standalone). public var realm: Realm? { if let rlmReam = RLMObjectBaseRealm(self) { return Realm(rlmReam) } return nil } /// The `ObjectSchema` which lists the persisted properties for this object. public var objectSchema: ObjectSchema { return ObjectSchema(RLMObjectBaseObjectSchema(self)) } /// Indicates if an object can no longer be accessed. public override var invalidated: Bool { return super.invalidated } /// Returns a human-readable description of this object. public override var description: String { return super.description } // MARK: Object customization /** Override to designate a property as the primary key for an `Object` subclass. Only properties of type String and Int can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set which incurs some overhead. Indexes are created automatically for primary key properties. :returns: Name of the property designated as the primary key, or `nil` if the model has no primary key. */ public class func primaryKey() -> String? { return nil } /** Override to return an array of property names to ignore. These properties will not be persisted and are treated as transient. :returns: `Array` of property names to ignore. */ public class func ignoredProperties() -> [String] { return [] } /** Return an array of property names for properties which should be indexed. Only supported for string and int properties. :returns: `Array` of property names to index. */ public class func indexedProperties() -> [String] { return [] } // MARK: Inverse Relationships /** Get an `Array` of objects of type `className` which have this object as the given property value. This can be used to get the inverse relationship value for `Object` and `List` properties. :param: className The type of object on which the relationship to query is defined. :param: property The name of the property which defines the relationship. :returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property. */ public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] { // FIXME: use T.className() return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T] } // MARK: Private functions // FIXME: None of these functions should be exposed in the public interface. /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) } /** Returns the value for the property identified by the given key. :param: key The name of one of the receiver's properties. :returns: The value for the property identified by `key`. */ public override func valueForKey(key: String) -> AnyObject? { if let list = listProperty(key) { return list } return super.valueForKey(key) } /** Sets the property of the receiver specified by the given key to the given value. :param: value The value for the property identified by `key`. :param: key The name of one of the receiver's properties. */ public override func setValue(value: AnyObject?, forKey key: String) { if let list = listProperty(key) { if let value = value as? NSFastEnumeration { list._rlmArray.removeAllObjects() list._rlmArray.addObjects(value) } return } super.setValue(value, forKey: key) } /// Returns or sets the value of the property with the given name. public subscript(key: String) -> AnyObject? { get { if let list = listProperty(key) { return list } return RLMObjectBaseObjectForKeyedSubscript(self, key) } set(value) { if let list = listProperty(key) { if let value = value as? NSFastEnumeration { list._rlmArray.removeAllObjects() list._rlmArray.addObjects(value) } return } RLMObjectBaseSetObjectForKeyedSubscript(self, key, value) } } // Helper for getting a list property for the given key private func listProperty(key: String) -> RLMListBase? { if let prop = RLMObjectBaseObjectSchema(self)?[key] { if prop.type == .Array { return object_getIvar(self, prop.swiftListIvar) as! RLMListBase? } } return nil } // MARK: Equatable /// Returns whether both objects are equal. /// Objects are considered equal when they are both from the same Realm /// and point to the same underlying object in the database. public override func isEqual(object: AnyObject?) -> Bool { return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase); } } /// Object interface which allows untyped getters and setters for Objects. public final class DynamicObject : Object { private var listProperties = [String: List<DynamicObject>]() // Override to create List<DynamicObject> on access private override func listProperty(key: String) -> RLMListBase? { if let prop = RLMObjectBaseObjectSchema(self)?[key] { if prop.type == .Array { if let list = listProperties[key] { return list } let list = List<DynamicObject>() listProperties[key] = list return list } } return nil } /// :nodoc: public override func valueForUndefinedKey(key: String) -> AnyObject? { return self[key] } /// :nodoc: public override func setValue(value: AnyObject?, forUndefinedKey key: String) { self[key] = value } @objc private class func shouldPersistToRealm() -> Bool { return false; } } /// :nodoc: /// Internal class. Do not use directly. public class ObjectUtil: NSObject { @objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.ignoredProperties() as NSArray? } return nil } @objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.indexedProperties() as NSArray? } return nil } // Get the names of all properties in the object which are of type List<> @objc private class func getGenericListPropertyNames(obj: AnyObject) -> NSArray { let reflection = reflect(obj) var properties = [String]() // Skip the first property (super): // super is an implicit property on Swift objects for i in 1..<reflection.count { let mirror = reflection[i].1 if mirror.valueType is RLMListBase.Type { properties.append(reflection[i].0) } } return properties } @objc private class func initializeListProperty(object: RLMObjectBase?, property: RLMProperty?, array: RLMArray?) { let list = (object as! Object)[property!.name]! as! RLMListBase list._rlmArray = array } @objc private class func getOptionalPropertyNames(object: AnyObject) -> NSArray { let reflection = reflect(object) var properties = [String]() // Skip the first property (super): // super is an implicit property on Swift objects for i in 1..<reflection.count { let mirror = reflection[i].1 if mirror.disposition == .Optional { properties.append(reflection[i].0) } } return properties } @objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? { return nil } }
4b1470c99a5c831f2e0acb8aed2045ba
32.651652
126
0.633678
false
false
false
false
embryoconcepts/TIY-Assignments
refs/heads/master
37 -- Venue Menu/VenueMenu/VenueMenu/FavoriteVenuesTableViewController.swift
cc0-1.0
1
// // FavoriteVenuesTableViewController.swift // VenueMenu // // Created by Jennifer Hamilton on 11/25/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData protocol VenueSearchDelegate { func venueWasSelected(venue: NSManagedObject) } class FavoriteVenuesTableViewController: UITableViewController, VenueSearchDelegate { var venues = Array<NSManagedObject>() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() title = "Favorite Venues" let fetchRequest = NSFetchRequest(entityName: "Venue") do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Venue] venues = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return venues.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("VenueTableViewCell", forIndexPath: indexPath) as! VenueTableViewCell let aVenue = venues[indexPath.row] cell.venueLabel.text = aVenue.valueForKey("name") as? String // cell.ratingLabel.text = aVenue.valueForKey("rating") as? String return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aVenue = venues[indexPath.row] venues.removeAtIndex(indexPath.row) managedObjectContext.deleteObject(aVenue) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowSearchModal" { let destVC = segue.destinationViewController as! UINavigationController let modalVC = destVC.viewControllers[0] as! VenueSearchViewController modalVC.delegate = self } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let venueDetailVC = storyboard?.instantiateViewControllerWithIdentifier("VenueDetailViewController") as! VenueDetailViewController venueDetailVC.indexRow = indexPath.row venueDetailVC.venuesForDetailView = venues navigationController?.pushViewController(venueDetailVC, animated: true) } // MARK: - Add Contact Delegate func venueWasSelected(venue: NSManagedObject) { // let aVenue = NSEntityDescription.insertNewObjectForEntityForName("Venue", inManagedObjectContext: managedObjectContext) as! Venue // let venueEntity = NSEntityDescription.entityForName("Venue", inManagedObjectContext: managedObjectContext) // let aVenue = NSManagedObject(entity: venueEntity!, insertIntoManagedObjectContext: managedObjectContext) managedObjectContext.insertObject(venue) venues.append(venue) saveContext() tableView.reloadData() } // MARK: - Private functions private func saveContext() { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }
6708df0fae0289e4d9d75cef7ec833d9
30.678571
157
0.670349
false
false
false
false
eridbardhaj/Weather
refs/heads/master
Weather/AppDelegate/AppDelegate.swift
mit
1
// // AppDelegate.swift // Weather // // Created by Erid Bardhaj on 4/27/15. // Copyright (c) 2015 STRV. All rights reserved. // import UIKit import CoreLocation import WatchKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //Get current location LocationManager.shared.getCurrentLocation() //Control UIApperance to customise layout changeLayout() 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: - WatchKit func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) { //Make the call to API WeatherNetwork.getForecastWeatherByCoordinates(DataManager.shared.m_city_lat, lng: DataManager.shared.m_city_lng, responseHandler: { (error, array) -> (Void) in if error == ErrorType.None { var response: NSDictionary = NSDictionary(dictionary: ["response" : array as! AnyObject]) reply(response as [NSObject : AnyObject]) } else { //Handle Error reply(nil) } }) } //MARK: - Custom Settings func changeLayout() { //Navigation Bar customization UINavigationBar.appearance().setBackgroundImage(UIImage.new(), forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 18.0)!, NSForegroundColorAttributeName: Constants.Colors.blackColor()] UINavigationBar.appearance().backItem?.backBarButtonItem?.tintColor = Constants.Colors.lightBlue() //UIBarButtonItem Attributes var barAttribs = [NSFontAttributeName : UIFont(name: "ProximaNova-Regular", size: 16.0)!, NSForegroundColorAttributeName: Constants.Colors.lightBlue()] UIBarButtonItem.appearance().setTitleTextAttributes(barAttribs, forState: UIControlState.Normal) UIBarButtonItem.appearance().tintColor = Constants.Colors.lightBlue() //UITabBar Attributes var tabAttribsNormal = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 10.0)!, NSForegroundColorAttributeName: Constants.Colors.blackColor()] var tabAttribsSelected = [NSFontAttributeName : UIFont(name: "ProximaNova-Semibold", size: 10.0)!, NSForegroundColorAttributeName: Constants.Colors.lightBlue(), ] UITabBarItem.appearance().setTitleTextAttributes(tabAttribsNormal, forState: UIControlState.Normal) UITabBarItem.appearance().setTitleTextAttributes(tabAttribsSelected, forState: UIControlState.Selected) //Changing image tint color UITabBar.appearance().tintColor = Constants.Colors.lightBlue() UITabBar.appearance().backgroundImage = UIImage() } }
334fdae360163675cb72249bc85d368e
47.76
285
0.698728
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Managers/Model/AuthSettingsManagerPersistencyExtension.swift
mit
1
// // AuthSettingsManagerPersistencyExtension.swift // Rocket.Chat // // Created by Rafael Streit on 14/11/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift extension AuthSettingsManager { static func persistPublicSettings(settings: AuthSettings, realm: Realm? = Realm.current, completion: (MessageCompletionObject<AuthSettings>)? = nil) { let unmanagedSettings = AuthSettings(value: settings) shared.internalSettings = unmanagedSettings realm?.execute({ realm in // Delete all the AuthSettings objects, since we don't // support multiple-server per database realm.delete(realm.objects(AuthSettings.self)) }) realm?.execute({ realm in realm.add(settings) if let auth = AuthManager.isAuthenticated(realm: realm) { auth.settings = settings realm.add(auth, update: true) } }) ServerManager.updateServerInformation(from: unmanagedSettings) completion?(unmanagedSettings) } static func updatePublicSettings( serverVersion: Version? = nil, apiHost: URL? = nil, apiSSLCertificatePath: URL? = nil, apiSSLCertificatePassword: String = "", _ auth: Auth?, completion: (MessageCompletionObject<AuthSettings>)? = nil) { let api: API? if let apiHost = apiHost { if let serverVersion = serverVersion { api = API(host: apiHost, version: serverVersion) } else { api = API(host: apiHost) } } else { api = API.current() } if let certificatePathURL = apiSSLCertificatePath { api?.sslCertificatePath = certificatePathURL api?.sslCertificatePassword = apiSSLCertificatePassword } let realm = Realm.current let options: APIRequestOptionSet = [.paginated(count: 0, offset: 0)] api?.fetch(PublicSettingsRequest(), options: options) { response in switch response { case .resource(let resource): guard resource.success else { completion?(nil) return } persistPublicSettings(settings: resource.authSettings, realm: realm, completion: completion) case .error(let error): switch error { case .version: websocketUpdatePublicSettings(realm, auth, completion: completion) default: completion?(nil) } } } } private static func websocketUpdatePublicSettings(_ realm: Realm?, _ auth: Auth?, completion: (MessageCompletionObject<AuthSettings>)? = nil) { let object = [ "msg": "method", "method": "public-settings/get" ] as [String: Any] SocketManager.send(object) { (response) in guard !response.isError() else { completion?(nil) return } let settings = AuthSettings() settings.map(response.result["result"], realm: realm) persistPublicSettings(settings: settings, realm: realm, completion: completion) } } }
b6cbcbbb48da9d77278646ee6b1687d6
32.16
154
0.586248
false
false
false
false
AlexeyGolovenkov/DocGenerator
refs/heads/master
GRMustache.swift/Sources/CoreFunctions.swift
mit
1
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // ============================================================================= // MARK: - KeyedSubscriptFunction /** `KeyedSubscriptFunction` is used by the Mustache rendering engine whenever it has to resolve identifiers in expressions such as `{{ name }}` or `{{ user.name }}`. Subscript functions turn those identifiers into `MustacheBox`, the type that wraps rendered values. All types that expose keys to Mustache templates provide such a subscript function by conforming to the `MustacheBoxable` protocol. This is the case of built-in types such as NSObject, that uses `valueForKey:` in order to expose its properties; String, which exposes its "length"; collections, which expose keys like "count", "first", etc. etc. var box = Box("string") box = box["length"] // Evaluates the KeyedSubscriptFunction box.value // 6 box = Box(["a", "b", "c"]) box = box["first"] // Evaluates the KeyedSubscriptFunction box.value // "a" Your can build boxes that hold a custom subscript function. This is a rather advanced usage, only supported with the low-level function `func Box(boolValue:value:keyedSubscript:filter:render:willRender:didRender:) -> MustacheBox`. // A KeyedSubscriptFunction that turns "key" into "KEY": let keyedSubscript: KeyedSubscriptFunction = { (key: String) -> MustacheBox in return Box(key.uppercaseString) } // Render "FOO & BAR" let template = try! Template(string: "{{foo}} & {{bar}}") let box = Box(keyedSubscript: keyedSubscript) try! template.render(box) ### Missing keys vs. missing values. `KeyedSubscriptFunction` returns a non-optional `MustacheBox`. In order to express "missing key", and have Mustache rendering engine dig deeper in the context stack in order to resolve a key, return the empty box `Box()`. In order to express "missing value", and prevent the rendering engine from digging deeper, return `Box(NSNull())`. */ public typealias KeyedSubscriptFunction = (key: String) -> MustacheBox // ============================================================================= // MARK: - FilterFunction /** `FilterFunction` is the core type that lets GRMustache evaluate filtered expressions such as `{{ uppercase(string) }}`. To build a filter, you use the `Filter()` function. It takes a function as an argument. For example: let increment = Filter { (x: Int?) in return Box(x! + 1) } To let a template use a filter, register it: let template = try! Template(string: "{{increment(x)}}") template.registerInBaseContext("increment", Box(increment)) // "2" try! template.render(Box(["x": 1])) `Filter()` can take several types of functions, depending on the type of filter you want to build. The example above processes `Int` values. There are three types of filters: - Values filters: - `(MustacheBox) throws -> MustacheBox` - `(T?) throws -> MustacheBox` (Generic) - `([MustacheBox]) throws -> MustacheBox` (Multiple arguments) - Pre-rendering filters: - `(Rendering) throws -> Rendering` - Custom rendering filters: - `(MustacheBox, RenderingInfo) throws -> Rendering` - `(T?, RenderingInfo) throws -> Rendering` (Generic) See the documentation of the `Filter()` functions. */ public typealias FilterFunction = (box: MustacheBox, partialApplication: Bool) throws -> MustacheBox // ----------------------------------------------------------------------------- // MARK: - Values Filters /** Builds a filter that takes a single argument. For example, here is the trivial `identity` filter: let identity = Filter { (box: MustacheBox) in return box } let template = try! Template(string: "{{identity(a)}}, {{identity(b)}}") template.registerInBaseContext("identity", Box(identity)) // "foo, 1" try! template.render(Box(["a": "foo", "b": 1])) If the template provides more than one argument, the filter returns a MustacheError of type RenderError. - parameter filter: A function `(MustacheBox) throws -> MustacheBox`. - returns: A FilterFunction. */ public func Filter(filter: (MustacheBox) throws -> MustacheBox) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError(kind: .RenderError, message: "Too many arguments") } return try filter(box) } } /** Builds a filter that takes a single argument of type `T?`. For example: let increment = Filter { (x: Int?) in return Box(x! + 1) } let template = try! Template(string: "{{increment(x)}}") template.registerInBaseContext("increment", Box(increment)) // "2" try! template.render(Box(["x": 1])) The argument is converted to `T` using the built-in `as?` operator before being given to the filter. If the template provides more than one argument, the filter returns a MustacheError of type RenderError. - parameter filter: A function `(T?) throws -> MustacheBox`. - returns: A FilterFunction. */ public func Filter<T>(filter: (T?) throws -> MustacheBox) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError(kind: .RenderError, message: "Too many arguments") } return try filter(box.value as? T) } } /** Returns a filter than accepts any number of arguments. For example: // `sum(x, ...)` evaluates to the sum of provided integers let sum = VariadicFilter { (boxes: [MustacheBox]) in // Extract integers out of input boxes, assuming zero for non numeric values let integers = boxes.map { (box) in (box.value as? Int) ?? 0 } let sum = integers.reduce(0, combine: +) return Box(sum) } let template = try! Template(string: "{{ sum(a,b,c) }}") template.registerInBaseContext("sum", Box(sum)) // Renders "6" try! template.render(Box(["a": 1, "b": 2, "c": 3])) - parameter filter: A function `([MustacheBox]) throws -> MustacheBox`. - returns: A FilterFunction. */ public func VariadicFilter(filter: ([MustacheBox]) throws -> MustacheBox) -> FilterFunction { // f(a,b,c) is implemented as f(a)(b)(c). // // f(a) returns another filter, which returns another filter, which // eventually computes the final result. // // It is the partialApplication flag the tells when it's time to return the // final result. func partialFilter(filter: ([MustacheBox]) throws -> MustacheBox, arguments: [MustacheBox]) -> FilterFunction { return { (nextArgument: MustacheBox, partialApplication: Bool) in let arguments = arguments + [nextArgument] if partialApplication { // Wait for another argument return Box(partialFilter(filter, arguments: arguments)) } else { // No more argument: compute final value return try filter(arguments) } } } return partialFilter(filter, arguments: []) } // ----------------------------------------------------------------------------- // MARK: - Pre-Rendering Filters /** Builds a filter that performs post rendering. `Rendering` is a type that wraps a rendered String, and its content type (HTML or Text). This filter turns a rendering in another one: // twice filter renders its argument twice: let twice = Filter { (rendering: Rendering) in return Rendering(rendering.string + rendering.string, rendering.contentType) } let template = try! Template(string: "{{ twice(x) }}") template.registerInBaseContext("twice", Box(twice)) // Renders "foofoo", "123123" try! template.render(Box(["x": "foo"])) try! template.render(Box(["x": 123])) When this filter is executed, eventual HTML-escaping performed by the rendering engine has not happened yet: the rendering argument may contain raw text. This allows you to chain pre-rendering filters without mangling HTML entities. - parameter filter: A function `(Rendering) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter(filter: (Rendering) throws -> Rendering) -> FilterFunction { return { (box: MustacheBox, partialApplication: Bool) in guard !partialApplication else { // This is a single-argument filter: we do not wait for another one. throw MustacheError(kind: .RenderError, message: "Too many arguments") } // Box a RenderFunction return Box { (info: RenderingInfo) in let rendering = try box.render(info: info) return try filter(rendering) } } } // ----------------------------------------------------------------------------- // MARK: - Custom Rendering Filters /** Builds a filter that takes a single argument and performs custom rendering. See the documentation of the `RenderFunction` type for a detailed discussion of the `RenderingInfo` and `Rendering` types. For an example of such a filter, see the documentation of `func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction`. This example processes `T?` instead of `MustacheBox`, but the idea is the same. - parameter filter: A function `(MustacheBox, RenderingInfo) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter(filter: (MustacheBox, RenderingInfo) throws -> Rendering) -> FilterFunction { return Filter { (box: MustacheBox) in // Box a RenderFunction return Box { (info: RenderingInfo) in return try filter(box, info) } } } /** Builds a filter that takes a single argument of type `T?` and performs custom rendering. For example: // {{# pluralize(count) }}...{{/ }} renders the plural form of the section // content if the `count` argument is greater than 1. let pluralize = Filter { (count: Int?, info: RenderingInfo) in // Pluralize the inner content of the section tag: var string = info.tag.innerTemplateString if count > 1 { string += "s" // naive pluralization } return Rendering(string) } let template = try! Template(string: "I have {{ cats.count }} {{# pluralize(cats.count) }}cat{{/ }}.") template.registerInBaseContext("pluralize", Box(pluralize)) // Renders "I have 3 cats." let data = ["cats": ["Kitty", "Pussy", "Melba"]] try! template.render(Box(data)) The argument is converted to `T` using the built-in `as?` operator before being given to the filter. If the template provides more than one argument, the filter returns a MustacheError of type RenderError. See the documentation of the `RenderFunction` type for a detailed discussion of the `RenderingInfo` and `Rendering` types. - parameter filter: A function `(T?, RenderingInfo) throws -> Rendering`. - returns: A FilterFunction. */ public func Filter<T>(filter: (T?, RenderingInfo) throws -> Rendering) -> FilterFunction { return Filter { (t: T?) in // Box a RenderFunction return Box { (info: RenderingInfo) in return try filter(t, info) } } } // ============================================================================= // MARK: - RenderFunction /** `RenderFunction` is used by the Mustache rendering engine when it renders a variable tag (`{{name}}` or `{{{body}}}`) or a section tag (`{{#name}}...{{/name}}`). ### Output: `Rendering` The return type of `RenderFunction` is `Rendering`, a type that wraps a rendered String, and its ContentType (HTML or Text). Text renderings are HTML-escaped, except for `{{{triple}}}` mustache tags, and Text templates (see `Configuration.contentType` for a full discussion of the content type of templates). For example: let HTML: RenderFunction = { (_) in return Rendering("<HTML>", .HTML) } let text: RenderFunction = { (_) in return Rendering("<text>") // default content type is text } // Renders "<HTML>, &lt;text&gt;" let template = try! Template(string: "{{HTML}}, {{text}}") let data = ["HTML": Box(HTML), "text": Box(text)] let rendering = try! template.render(Box(data)) ### Input: `RenderingInfo` The `info` argument contains a `RenderingInfo` which provides information about the requested rendering: - `info.context: Context` is the context stack which contains the rendered data. - `info.tag: Tag` is the tag to render. - `info.tag.type: TagType` is the type of the tag (variable or section). You can use this type to have a different rendering for variable and section tags. - `info.tag.innerTemplateString: String` is the inner content of the tag, unrendered. For the section tag `{{# person }}Hello {{ name }}!{{/ person }}`, it is `Hello {{ name }}!`. - `info.tag.render: (Context) throws -> Rendering` is a function that renders the inner content of the tag, given a context stack. For example, the section tag `{{# person }}Hello {{ name }}!{{/ person }}` would render `Hello Arthur!`, assuming the provided context stack provides "Arthur" for the key "name". ### Example As an example, let's write a `RenderFunction` which performs the default rendering of a value: - `{{ value }}` and `{{{ value }}}` renders the built-in Swift String Interpolation of the value: our render function will return a `Rendering` with content type Text when the rendered tag is a variable tag. The Text content type makes sure that the returned string will be HTML-escaped if needed. - `{{# value }}...{{/ value }}` pushes the value on the top of the context stack, and renders the inner content of section tags. The default rendering thus reads: let value = ... // Some value let renderValue: RenderFunction = { (info: RenderingInfo) throws in // Default rendering depends on the tag type: switch info.tag.type { case .Variable: // {{ value }} and {{{ value }}} // Return the built-in Swift String Interpolation of the value: return Rendering("\(value)", .Text) case .Section: // {{# value }}...{{/ value }} // Push the value on the top of the context stack: let context = info.context.extendedContext(Box(value)) // Renders the inner content of the section tag: return try info.tag.render(context) } } let template = try! Template(string: "{{value}}") let rendering = try! template.render(Box(["value": Box(renderValue)])) - parameter info: A RenderingInfo. - parameter error: If there is a problem in the rendering, throws an error that describes the problem. - returns: A Rendering. */ public typealias RenderFunction = (info: RenderingInfo) throws -> Rendering // ----------------------------------------------------------------------------- // MARK: - Mustache lambdas /** Builds a `RenderFunction` which conforms to the "lambda" defined by the Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml). The `lambda` parameter is a function which takes the unrendered context of a section, and returns a String. The returned `RenderFunction` renders this string against the current delimiters. For example: let template = try! Template(string: "{{#bold}}{{name}} has a Mustache!{{/bold}}") let bold = Lambda { (string) in "<b>\(string)</b>" } let data = [ "name": Box("Clark Gable"), "bold": Box(bold)] // Renders "<b>Clark Gable has a Mustache.</b>" let rendering = try! template.render(Box(data)) **Warning**: the returned String is *parsed* each time the lambda is executed. In the example above, this is inefficient because the inner content of the bolded section has already been parsed with its template. You may prefer the raw `RenderFunction` type, capable of an equivalent and faster implementation: let bold: RenderFunction = { (info: RenderingInfo) in let rendering = try info.tag.render(info.context) return Rendering("<b>\(rendering.string)</b>", rendering.contentType) } let data = [ "name": Box("Clark Gable"), "bold": Box(bold)] // Renders "<b>Lionel Richie has a Mustache.</b>" let rendering = try! template.render(Box(data)) - parameter lambda: A `String -> String` function. - returns: A RenderFunction. */ public func Lambda(lambda: String -> String) -> RenderFunction { return { (info: RenderingInfo) in switch info.tag.type { case .Variable: // {{ lambda }} return Rendering("(Lambda)") case .Section: // {{# lambda }}...{{/ lambda }} // // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L117 // > Lambdas used for sections should parse with the current delimiters let templateRepository = TemplateRepository() templateRepository.configuration.tagDelimiterPair = info.tag.tagDelimiterPair let templateString = lambda(info.tag.innerTemplateString) let template = try templateRepository.template(string: templateString) return try template.render(info.context) // IMPLEMENTATION NOTE // // This lambda implementation is unable of two things: // // - process partial tags correctly, because it uses a // TemplateRepository that does not know how to load partials. // - honor the current content type. // // This partial problem is a tricky one to solve. A `{{>partial}}` // tag loads the "partial" template which is sibling of the // currently rendered template. // // Imagine the following template hierarchy: // // - /a.mustache: {{#lambda}}...{{/lambda}}...{{>dir/b}} // - /x.mustache: ... // - /dir/b.mustache: {{#lambda}}...{{/lambda}} // - /dir/x.mustache: ... // // If the lambda returns `{{>x}}` then rendering the `a.mustache` // template should trigger the inclusion of both `/x.mustache` and // `/dir/x.mustache`. // // Given the current state of GRMustache types, achieving proper // lambda would require: // // - a template repository // - a TemplateID // - a property `Tag.contentType` // - a method `TemplateRepository.template(string:contentType:tagDelimiterPair:baseTemplateID:)` // // Code would read something like: // // let templateString = lambda(info.tag.innerTemplateString) // let templateRepository = info.tag.templateRepository // let templateID = info.tag.templateID // let contentType = info.tag.contentType // let template = try templateRepository.template( // string: templateString, // contentType: contentType // tagDelimiterPair: info.tag.tagDelimiterPair, // baseTemplateID: templateID) // return try template.render(info.context) // // Should we ever implement this, beware the retain cycle between // tags and template repositories (which own tags through their // cached templateASTs). // // -------- // // Lambda spec requires Lambda { ">" } to render "&gt". // // What should Lambda { "<{{>partial}}>" } render when partial // contains "<>"? "&lt;<>&gt;" ???? } } } /** Builds a `RenderFunction` which conforms to the "lambda" defined by the Mustache specification (see https://github.com/mustache/spec/blob/v1.1.2/specs/%7Elambdas.yml). The `lambda` parameter is a function without any argument that returns a String. The returned `RenderFunction` renders this string against the default `{{` and `}}` delimiters. For example: let template = try! Template(string: "{{fullName}} has a Mustache.") let fullName = Lambda { "{{firstName}} {{lastName}}" } let data = [ "firstName": Box("Lionel"), "lastName": Box("Richie"), "fullName": Box(fullName)] // Renders "Lionel Richie has a Mustache." let rendering = try! template.render(Box(data)) **Warning**: the returned String is *parsed* each time the lambda is executed. In the example above, this is inefficient because the same `"{{firstName}} {{lastName}}"` would be parsed several times. You may prefer using a Template instead of a lambda (see the documentation of `Template.mustacheBox` for more information): let fullName = try! Template(string:"{{firstName}} {{lastName}}") let data = [ "firstName": Box("Lionel"), "lastName": Box("Richie"), "fullName": Box(fullName)] // Renders "Lionel Richie has a Mustache." let rendering = try! template.render(Box(data)) - parameter lambda: A `() -> String` function. - returns: A RenderFunction. */ public func Lambda(lambda: () -> String) -> RenderFunction { return { (info: RenderingInfo) in switch info.tag.type { case .Variable: // {{ lambda }} // // https://github.com/mustache/spec/blob/83b0721610a4e11832e83df19c73ace3289972b9/specs/%7Elambdas.yml#L73 // > Lambda results should be appropriately escaped // // Let's render a text template: let templateRepository = TemplateRepository() templateRepository.configuration.contentType = .Text let templateString = lambda() let template = try templateRepository.template(string: templateString) return try template.render(info.context) // IMPLEMENTATION NOTE // // This lambda implementation is unable to process partial tags // correctly: it uses a TemplateRepository that does not know how // to load partials. // // This problem is a tricky one to solve. The `{{>partial}}` tag // loads the "partial" template which is sibling of the currently // rendered template. // // Imagine the following template hierarchy: // // - /a.mustache: {{lambda}}...{{>dir/b}} // - /x.mustache: ... // - /dir/b.mustache: {{lambda}} // - /dir/x.mustache: ... // // If the lambda returns `{{>x}}` then rendering the `a.mustache` // template should trigger the inclusion of both `/x.mustache` and // `/dir/x.mustache`. // // Given the current state of GRMustache types, achieving this // feature would require: // // - a template repository // - a TemplateID // - a method `TemplateRepository.template(string:contentType:tagDelimiterPair:baseTemplateID:)` // // Code would read something like: // // let templateString = lambda(info.tag.innerTemplateString) // let templateRepository = info.tag.templateRepository // let templateID = info.tag.templateID // let template = try templateRepository.template( // string: templateString, // contentType: .Text, // tagDelimiterPair: ("{{", "}}), // baseTemplateID: templateID) // return try template.render(info.context) // // Should we ever implement this, beware the retain cycle between // tags and template repositories (which own tags through their // cached templateASTs). // // -------- // // Lambda spec requires Lambda { ">" } to render "&gt". // // What should Lambda { "<{{>partial}}>" } render when partial // contains "<>"? "&lt;<>&gt;" ???? case .Section: // {{# lambda }}...{{/ lambda }} // // Behave as a true object, and render the section. let context = info.context.extendedContext(Box(Lambda(lambda))) return try info.tag.render(context) } } } /** `Rendering` is a type that wraps a rendered String, and its content type (HTML or Text). See `RenderFunction` and `FilterFunction` for more information. */ public struct Rendering { /// The rendered string public let string: String /// The content type of the rendering public let contentType: ContentType /** Builds a Rendering with a String and a ContentType. Rendering("foo") // Defaults to Text Rendering("foo", .Text) Rendering("foo", .HTML) - parameter string: A string. - parameter contentType: A content type. - returns: A Rendering. */ public init(_ string: String, _ contentType: ContentType = .Text) { self.string = string self.contentType = contentType } } extension Rendering : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { var contentTypeString: String switch contentType { case .HTML: contentTypeString = "HTML" case .Text: contentTypeString = "Text" } return "Rendering(\(contentTypeString):\(string.debugDescription))" } } /** `RenderingInfo` provides information about a rendering. See `RenderFunction` for more information. */ public struct RenderingInfo { /// The currently rendered tag. public let tag: Tag /// The current context stack. public var context: Context // If true, the rendering is part of an enumeration. Some values don't // render the same whenever they render as an enumeration item, or alone: // {{# values }}...{{/ values }} vs. {{# value }}...{{/ value }}. // // This is the case of Int, UInt, Double, Bool: they enter the context // stack when used in an iteration, and do not enter the context stack when // used as a boolean (see https://github.com/groue/GRMustache/issues/83). // // This is also the case of collections: they enter the context stack when // used as an item of a collection, and enumerate their items when used as // a collection. var enumerationItem: Bool } // ============================================================================= // MARK: - WillRenderFunction /** Once a `WillRenderFunction` has entered the context stack, it is called just before tags are about to render, and has the opportunity to replace the value they are about to render. let logTags: WillRenderFunction = { (tag: Tag, box: MustacheBox) in print("\(tag) will render \(box.value!)") return box } // By entering the base context of the template, the logTags function // will be notified of all tags. let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}") template.extendBaseContext(Box(logTags)) // Prints: // {{# user }} at line 1 will render { firstName = Errol; lastName = Flynn; } // {{ firstName }} at line 1 will render Errol // {{ lastName }} at line 1 will render Flynn let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]] try! template.render(Box(data)) `WillRenderFunction` don't have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section. let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}") // Prints: // {{ lastName }} at line 1 will render Flynn let data = [ "user": Box(["firstName": "Errol", "lastName": "Flynn"]), "spy": Box(logTags) ] try! template.render(Box(data)) */ public typealias WillRenderFunction = (tag: Tag, box: MustacheBox) -> MustacheBox // ============================================================================= // MARK: - DidRenderFunction /** Once a DidRenderFunction has entered the context stack, it is called just after tags have been rendered. let logRenderings: DidRenderFunction = { (tag: Tag, box: MustacheBox, string: String?) in println("\(tag) did render \(box.value!) as `\(string!)`") } // By entering the base context of the template, the logRenderings function // will be notified of all tags. let template = try! Template(string: "{{# user }}{{ firstName }} {{ lastName }}{{/ user }}") template.extendBaseContext(Box(logRenderings)) // Renders "Errol Flynn" // // Prints: // {{ firstName }} at line 1 did render Errol as `Errol` // {{ lastName }} at line 1 did render Flynn as `Flynn` // {{# user }} at line 1 did render { firstName = Errol; lastName = Flynn; } as `Errol Flynn` let data = ["user": ["firstName": "Errol", "lastName": "Flynn"]] try! template.render(Box(data)) DidRender functions don't have to enter the base context of a template to perform: they can enter the context stack just like any other value, by being attached to a section. In this case, they are only notified of tags inside that section. let template = try! Template(string: "{{# user }}{{ firstName }} {{# spy }}{{ lastName }}{{/ spy }}{{/ user }}") // Renders "Errol Flynn" // // Prints: // {{ lastName }} at line 1 did render Flynn as `Flynn` let data = [ "user": Box(["firstName": "Errol", "lastName": "Flynn"]), "spy": Box(logRenderings) ] try! template.render(Box(data)) The string argument of DidRenderFunction is optional: it is nil if and only if the tag could not render because of a rendering error. See also: - WillRenderFunction */ public typealias DidRenderFunction = (tag: Tag, box: MustacheBox, string: String?) -> Void
e480170e64de7af9d8f3346caa5529e2
35.662442
119
0.62172
false
false
false
false
jonbrown21/Seafood-Guide-iOS
refs/heads/master
Seafood Guide/Lingo/ViewControllers/LingoTableViewController.swift
mit
1
// Converted to Swift 5.1 by Swiftify v5.1.26565 - https://objectivec2swift.com/ // // LingoTableViewController.swift // Seafood Guide // // Created by Jon Brown on 9/1/14. // Copyright (c) 2014 Jon Brown Designs. All rights reserved. // import UIKit import CoreData class LingoTableViewController: UITableViewController, UINavigationBarDelegate, UINavigationControllerDelegate { var uppercaseFirstLetterOfName = "" var predicateKey = "" var window: UIWindow? var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? lazy var managedObjectContext: NSManagedObjectContext? = { return (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext }() var sectionIndexTitles: [AnyHashable] = [] init(lingoSize size: String?) { super.init(style: .plain) } func setupFetchedResultsController() { let entityName = "Lingo" // Put your entity name here let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) request.sortDescriptors = [NSSortDescriptor.init(key: "titlenews", ascending: true)] if let managedObjectContext = managedObjectContext { fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "uppercaseFirstLetterOfName", cacheName: nil) } do { try fetchedResultsController?.performFetch() } catch { } } override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { weak var sectionInfo = fetchedResultsController?.sections?[section] return sectionInfo?.name } override func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int { weak var sectionInfo = fetchedResultsController?.sections?[section] return sectionInfo?.numberOfObjects ?? 0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupFetchedResultsController() } static let tableViewCellIdentifier = "lingocells" override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: LingoTableViewController.tableViewCellIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: LingoTableViewController.tableViewCellIdentifier) } cell?.accessoryType = .disclosureIndicator let lingo = fetchedResultsController?.object(at: indexPath) as? Lingo cell?.textLabel?.text = lingo?.titlenews return cell! } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return UILocalizedIndexedCollation.current().sectionIndexTitles } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return UILocalizedIndexedCollation.current().section(forSectionIndexTitle: index) } convenience override init(style: UITableView.Style) { self.init(lingoSize: nil) } override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem?.title = "Back" } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Table view sends data to detail view override func tableView(_ aTableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailViewController = DetailLingoViewController.init(style: .plain) var sumSections = 0 for i in 0..<indexPath.section { let rowsInSection = tableView.numberOfRows(inSection: i) sumSections += rowsInSection } let currentRow = sumSections + indexPath.row let allLingo = fetchedResultsController?.fetchedObjects?[currentRow] as? Lingo detailViewController.item = allLingo navigationController?.pushViewController(detailViewController, animated: true) navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationItem.hidesBackButton = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
838ae68ad44628b978b0eeb0bc19e5f7
32.708029
198
0.701386
false
false
false
false
iamyuiwong/swift-common
refs/heads/master
util/StringUtil.swift
lgpl-3.0
1
/* * NAME StringUtil - string util * * DESC * - Current for iOS 9 * - See diffs: (2015-10-04 17:43:24 +0800) * https://developer.apple.com/library/prerelease/ios/releasenotes/General/iOS90APIDiffs/Swift/Swift.html * * V. See below */ import Foundation /* * NAME NSObjectString - class NSObjectString * * V * - 1.0.0.0_2015100800 */ public class NSObjectString: NSObject { public var s: String? } /* * NAME StringUtil - class StringUtil * * V * - 1.0.0.3_20151009175522800 */ public class StringUtil { public static func toString () -> String { return "StringUtilv1.0.0.3_20151009175522800" } /* * NAME toString - from String Array * * ARGS * - struct Array<T> * - struct String * * DESC * - E.X. ["1", "2", "3"] -> "123" */ public static func toString (let fromStringArray sa: [String]) -> String { var ret = "" for s in sa { ret += s } return ret } /* * NAME toString - from String Array and insert separator * * ARGS * - struct Array<T> * - struct String * - ht if true always append sep to last */ public static func toString (let fromStringArray sa: [String], insSeparator sep: String, hasTail ht: Bool) -> String { var ret = "" let c = sa.count for i in 0..<c { ret += sa[i] + sep } if let l = sa.last { ret += l } if (ht) { ret += sep } return ret } public static func toString (let byFormat fmt: String, args: [CVarArgType]) -> String { let ret = String(format: fmt, arguments: args) return ret /* success */ } public static func toString (fromCstring s: UnsafeMutablePointer<Int8>, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { if (nil == s) { return nil } return String(CString: s, encoding: encoding) } public static func toString (fromCstring2 s: [Int8], encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { return String(CString: s, encoding: encoding) } public static func toString (fromCstring3 s: UnsafePointer<Int8>, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { if (nil == s) { return nil } return String(CString: s, encoding: encoding) } public static func toString (fromErrno en: Int32) -> String { let _ret = strerror(en) let reto = StringUtil.toString(fromCstring: _ret, encoding: NSUTF8StringEncoding) if let ret = reto { return ret } else { return "errno: \(en)" } } /* * NAME tocstring - from String * * DESC * - String to "char *" use "encoding" */ public static func tocstringArray (let fromString s: String, let encoding enc: NSStringEncoding = NSUTF8StringEncoding) -> array<Int8>? { let ret = array<Int8>() ret.data = s.cStringUsingEncoding(enc) return ret } public static func toCString (let fromString s: String, let encoding enc: NSStringEncoding = NSUTF8StringEncoding) -> [Int8]? { return s.cStringUsingEncoding(enc) } public static func toCString_2 (let fromString s: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> [Int8]? { /* e.x. NSUTF8StringEncoding */ let data = s.dataUsingEncoding(encoding, allowLossyConversion: false) if (nil == data) { return nil } let l = data!.length var buf: [Int8] = [Int8](count: l, repeatedValue: 0x0) Log.v(tag: TAG, items: "len: \(l)") data!.getBytes(&buf, length: l) return buf } public static func toHexDataStr (let fromCString arr: [Int8], start: Int = 0, count: size_t? = nil, uppercase: Bool = false) -> String? { let cc = ArrayChecker.check(array: arr, start: start, count: count) if (cc < 0) { return nil } var ret = "" var f: String? if (uppercase) { f = "%.2X" } else { f = "%.2x" } for i in 0..<cc { let b = arr[i + start] ret += String(format: f!, b) } return ret } /** * NAME toHexDataStr - fromData<br> * E.x. { '0', '9', 0xa } => { 30, 39, 10 }<br> * => { '3', '0', '3', '9', '1', '0' }<br> * => final result "303910"<br> * * NOTE * All lower case */ public static func toHexDataStr (let fromData arr: [UInt8], start: Int = 0, count: size_t? = nil, uppercase: Bool = false) -> String? { let cc = ArrayChecker.check(array: arr, start: start, count: count) if (cc < 0) { return nil } var ret = "" var f: String? if (uppercase) { f = "%.2X" } else { f = "%.2x" } for i in 0..<cc { let b = arr[i + start] ret += String(format: f!, b) } return ret } public static func toInt (fromBinString s: String) -> Int64 { if let ret = Int64(s, radix: 2) { return ret } else { return 0 } } public static func toInt (fromOctString s: String) -> Int64 { if let ret = Int64(s, radix: 8) { return ret } else { return 0 } } public static func toInt (fromDecString s: String) -> Int64 { if let ret = Int64(s, radix: 10) { return ret } else { return 0 } } public static func toInt (fromHexString s: String) -> Int64 { if let ret = Int64(s, radix: 16) { return ret } else { return 0 } } public static func toInt (fromString s: String, radix r: Int) -> Int64 { if let ret = Int64(s, radix: r) { return ret } else { return 0 } } public static func toData (let fromString s: String, let encoding enc: NSStringEncoding = NSUTF8StringEncoding) -> [UInt8]? { /* check */ if (s.isEmpty) { return [0x0] } let nsdata = s.dataUsingEncoding(enc, allowLossyConversion: false) if (nil == nsdata) { return nil } else { } let l = nsdata!.length var buf: [UInt8] = [UInt8](count: l, repeatedValue: 0x0) nsdata!.getBytes(&buf, length: l) return buf } /* * NAME split - split string by ONE Character to strings */ public static func split (string s: String, byCharacter separator: Character) -> [String] { return s.componentsSeparatedByString(String(separator)) } /* * NAME split - split string by characters to strings */ public static func split (let string s: String, let byString separator: String) -> [String] { return s.componentsSeparatedByString(separator) } /* * NAME charsCount - string characters count */ public static func charsCount (let ofString s: String) -> Int { return s.characters.count } /* * NAME cstringCount - c string count whenEncoding is encoding */ public static func cstringCount (let ofString s: String, whenEncoding encoding: NSStringEncoding = NSUTF8StringEncoding) -> Int { if let cs = StringUtil.toCString(fromString: s, encoding: encoding) { return cs.count } else { return -1 } } /* * NAME dataCount - c string count whenEncoding is encoding */ public static func dataCount (let ofString s: String, whenEncoding encoding: NSStringEncoding = NSUTF8StringEncoding) -> Int { return StringUtil.cstringCount(ofString: s, whenEncoding: encoding) } /* * NAME substring - sub string of string (by character) * * DESC * - from start Char index to end(no end) */ public static func substring (let ofString s: String, fromCharIndex ib: Int, to ie: Int) -> String? { let c = s.characters.count if ((ib < 0) || (ie > c) || (ie < (ib + 1))) { return nil } else { let start = s.startIndex.advancedBy(ib) let end = s.startIndex.advancedBy(ie - 1) return s[start...end] } } /* * NAME substring - sub string of string (by character) * * DESC * - from start Char index and count Chars */ public static func substring (let ofString s: String, fromCharIndex ib: Int, count c: Int) -> String? { let ec = s.characters.count if ((ib < 0) || (c <= 0) || ((c + ib) > ec)) { return nil } else { let start = s.startIndex.advancedBy(ib) let end = s.startIndex.advancedBy(ib + c - 1) return s[start...end] } } /* * NAME reverse - reverse string to reversed string */ public static func reverse (let tostring ori: String) -> String { return String(ori.characters.reverse()) } /* * NAME reverse - reverse string to reversed CS */ public static func reverse (let tocs ori: String) -> [Character] { return ori.characters.reverse() } /* * NAME remove - remove:inString:fromCharIndex:to * * DESC * - String copy .. -- but if not !! * - And acceptable: to get a new string and keep origin!! * - indclude "to" index (remove) */ public static func remove (let inString _s: String, fromCharIndex f: Int, to t: Int) -> String { let c = _s.characters.count if ((f < 0) || (t < 0) || (c <= 0) || (f > t) || (t >= c)) { return _s } let start = _s.startIndex.advancedBy(f) let end = _s.startIndex.advancedBy(t) var s = _s s.removeRange(start...end) return s } /* * NAME remove - remove:inString:fromCharIndex:count */ public static func remove (let inString _s: String, fromCharIndex f: Int, count c: Int) -> String { let ec = _s.characters.count if ((f < 0) || (c <= 0) || ((c + f) > ec)) { return _s } let start = _s.startIndex.advancedBy(f) let end = _s.startIndex.advancedBy(f + c - 1) var s = _s s.removeRange(start...end) return s } private static let TAG: String = StringUtil.toString() } func string2double (s: String) -> Double { return NSNumberFormatter().numberFromString(s)!.doubleValue } func string2uint8 (s: String) -> UInt8 { return UInt8(NSNumberFormatter().numberFromString(s)!.unsignedShortValue) } /* * NAME numeric2string - to string */ func numeric2string (d: Double) -> String { /* Double to String no .0 suffix */ let s: String = "\(d)" if (s.hasSuffix(".0")) { let n = s.characters.count return String(s.characters.prefix(n - 2)) } else { return s } } func numeric2string (i: Int) -> String { /* Int to String */ let s: String = "\(i)" return s } func numeric2string (i: Int32) -> String { /* Int32 to String */ let s: String = "\(i)" return s } func numeric2string (u: UInt32) -> String { /* UInt32 to String */ let s: String = "\(u)" return s } /* * NAME append2string - this is for <Integer>.<Frac> * * DESCRIPTION * E.x. "1.1", 3, 1 => "1.13" * "1.012", 3, 5 => "1.012003" */ func append2string (final s: String, frac: UInt8, n: UInt32) -> String { var res = s print(s, frac, n) if (res.characters.contains(".")) { let ss = res.characters.split(".") let l = ss[1].count let le = n - UInt32(l) for (var i: UInt32 = 0; i < le; ++i) { res += "0" } res += numeric2string(UInt32(frac)) } else { res += "." for (var i: UInt32 = 0; i < n; ++i) { res += "0" } res += numeric2string(UInt32(frac)) } return res }
2520ef4950967bc815948f797836d7d5
17.353448
106
0.617097
false
false
false
false
ivanbruel/SwipeIt
refs/heads/master
Pods/Localizable/Pod/Network.swift
mit
1
// // Network.swift // Localizable // // Created by Ivan Bruel on 23/02/16. // Copyright © 2016 Localizable. All rights reserved. // import Foundation class Network: NSObject { private static let defaultApiURL = "https://localizable-api.herokuapp.com/api/v1/" private static let timeout = 60.0 private static let jsonHeader = "application/json" var mockData: Bool = false var apiURL = Network.defaultApiURL static var sharedInstance = Network() private let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) func performRequest(api: API, token: String, completion: (([String: AnyObject]?, NSError?) -> Void)? = nil) { let url = urlFromPath(api.path) performRequest(api.method, url: url, token: token, sampleData: api.sampleData, json: api.json, completion: completion) } } private extension Network { private func urlFromPath(path: String) -> String { return "\(apiURL)\(path)" } private func performRequest(method: Method = .GET, url: String, token: String, sampleData: [String: AnyObject]?, json: [String: AnyObject]? = nil, completion: (([String: AnyObject]?, NSError?) -> Void)? = nil) { var url = url if let json = json where method == .GET { let queryString = json.map { "\($0.0)=\($0.1.description)"}.joinWithSeparator("&") if queryString.characters.count > 0 { url = "\(url)?\(queryString)" } } guard let requestURL = NSURL(string: url) else { Logger.logHttp("Invalid url \(url)") return } let request = NSMutableURLRequest(URL: requestURL, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: Network.timeout) request.addValue(Network.jsonHeader, forHTTPHeaderField: "Content-Type") request.addValue(Network.jsonHeader, forHTTPHeaderField: "Accept") request.addValue(token, forHTTPHeaderField: "X-LOCALIZABLE-TOKEN") request.HTTPMethod = method.rawValue Logger.logHttp("\(method.rawValue) to \(url) with token \(token)") if let json = json where method != .GET { do { let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) request.HTTPBody = jsonData if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) { Logger.logHttp(jsonString) } } catch { Logger.logHttp("Could not serialize \(json.description) into JSON") } } if let sampleData = sampleData where self.mockData { completion?(sampleData, nil) return } let task = session.dataTaskWithRequest(request) { (data, response, error) in self.handleNetworkResponse(data, response: response, error: error, completion: completion) } task.resume() } private func handleNetworkResponse(data: NSData?, response: NSURLResponse?, error: NSError?, completion: (([String: AnyObject]?, NSError?) -> Void)?) { if let error = error { completion?(nil, error) } else if let data = data where data.length > 0 { let jsonString = String(data: data, encoding: NSUTF8StringEncoding) do { if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject] { completion?(json, nil) } else { Logger.logHttp("Could not cast \(jsonString) into [String: AnyObject]") completion?([:], nil) } } catch { Logger.logHttp("Could not deserialize \(jsonString) into [String: AnyObject]") completion?([:], nil) } } else { completion?([:], nil) } } }
c705eb294f30626bb196c4e850ab3110
32.517857
100
0.63772
false
false
false
false
pawan007/SmartZip
refs/heads/master
SmartZip/Library/Managers/Location Manager/LocationManager.swift
mit
1
// // LocationManager.swift // // // Created by Jimmy Jose on 14/08/14. // // // 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 CoreLocation import MapKit typealias LMReverseGeocodeCompletionHandler = ((reverseGecodeInfo:NSDictionary?,placemark:CLPlacemark?, error:String?)->Void)? typealias LMGeocodeCompletionHandler = ((gecodeInfo:NSDictionary?,placemark:CLPlacemark?, error:String?)->Void)? typealias LMLocationCompletionHandler = ((latitude:Double, longitude:Double, status:String, verboseMessage:String, error:String?)->())? // Todo: Keep completion handler differerent for all services, otherwise only one will work enum GeoCodingType{ case Geocoding case ReverseGeocoding } @available(iOS 8.0, *) class LocationManager: NSObject,CLLocationManagerDelegate { /* Private variables */ private var completionHandler:LMLocationCompletionHandler private var reverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler private var geocodingCompletionHandler:LMGeocodeCompletionHandler private var locationStatus : NSString = "Calibrating"// to pass in handler private var locationManager: CLLocationManager! private var verboseMessage = "Calibrating" private let verboseMessageDictionary = [CLAuthorizationStatus.NotDetermined:"You have not yet made a choice with regards to this application.", CLAuthorizationStatus.Restricted:"This application is not authorized to use location services. Due to active restrictions on location services, the user cannot change this status, and may not have personally denied authorization.", CLAuthorizationStatus.Denied:"You have explicitly denied authorization for this application, or location services are disabled in Settings.", CLAuthorizationStatus.AuthorizedAlways:"App is Authorized to use location services.", CLAuthorizationStatus.AuthorizedWhenInUse:"You have granted authorization to use your location only when the app is visible to you."] var delegate:LocationManagerDelegate? = nil var latitude:Double = 0.0 var longitude:Double = 0.0 var latitudeAsString:String = "" var longitudeAsString:String = "" var lastKnownLatitude:Double = 0.0 var lastKnownLongitude:Double = 0.0 var lastKnownLatitudeAsString:String = "" var lastKnownLongitudeAsString:String = "" var keepLastKnownLocation:Bool = true var hasLastKnownLocation:Bool = true var autoUpdate:Bool = false var showVerboseMessage = false var isRunning = false class var sharedInstance : LocationManager { struct Static { static let instance : LocationManager = LocationManager() } return Static.instance } private override init(){ super.init() if(!autoUpdate){ autoUpdate = !CLLocationManager.significantLocationChangeMonitoringAvailable() } } private func resetLatLon(){ latitude = 0.0 longitude = 0.0 latitudeAsString = "" longitudeAsString = "" } private func resetLastKnownLatLon(){ hasLastKnownLocation = false lastKnownLatitude = 0.0 lastKnownLongitude = 0.0 lastKnownLatitudeAsString = "" lastKnownLongitudeAsString = "" } func startUpdatingLocationWithCompletionHandler(completionHandler:((latitude:Double, longitude:Double, status:String, verboseMessage:String, error:String?)->())? = nil){ self.completionHandler = completionHandler initLocationManager() } func startUpdatingLocation(){ initLocationManager() } func stopUpdatingLocation(){ if(autoUpdate){ locationManager.stopUpdatingLocation() }else{ locationManager.stopMonitoringSignificantLocationChanges() } resetLatLon() if(!keepLastKnownLocation){ resetLastKnownLatLon() } } private func initLocationManager() { // App might be unreliable if someone changes autoupdate status in between and stops it locationManager = CLLocationManager() locationManager.delegate = self // locationManager.locationServicesEnabled locationManager.desiredAccuracy = kCLLocationAccuracyBest let Device = UIDevice.currentDevice() let iosVersion = NSString(string: Device.systemVersion).doubleValue let iOS8 = iosVersion >= 8 if iOS8{ //locationManager.requestAlwaysAuthorization() // add in plist NSLocationAlwaysUsageDescription locationManager.requestWhenInUseAuthorization() // add in plist NSLocationWhenInUseUsageDescription } startLocationManger() } private func startLocationManger(){ if(autoUpdate){ locationManager.startUpdatingLocation() }else{ locationManager.startMonitoringSignificantLocationChanges() } isRunning = true } private func stopLocationManger(){ if(autoUpdate){ locationManager.stopUpdatingLocation() }else{ locationManager.stopMonitoringSignificantLocationChanges() } isRunning = false } internal func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { stopLocationManger() resetLatLon() if(!keepLastKnownLocation){ resetLastKnownLatLon() } var verbose = "" if showVerboseMessage {verbose = verboseMessage} completionHandler?(latitude: 0.0, longitude: 0.0, status: locationStatus as String, verboseMessage:verbose,error: error.localizedDescription) if ((delegate != nil) && (delegate?.respondsToSelector(#selector(LocationManagerDelegate.locationManagerReceivedError(_:))))!){ delegate?.locationManagerReceivedError!(error.localizedDescription) } } internal func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let arrayOfLocation = locations as NSArray let location = arrayOfLocation.lastObject as! CLLocation let coordLatLon = location.coordinate latitude = coordLatLon.latitude longitude = coordLatLon.longitude latitudeAsString = coordLatLon.latitude.description longitudeAsString = coordLatLon.longitude.description var verbose = "" if showVerboseMessage {verbose = verboseMessage} if(completionHandler != nil){ completionHandler?(latitude: latitude, longitude: longitude, status: locationStatus as String,verboseMessage:verbose, error: nil) } lastKnownLatitude = coordLatLon.latitude lastKnownLongitude = coordLatLon.longitude lastKnownLatitudeAsString = coordLatLon.latitude.description lastKnownLongitudeAsString = coordLatLon.longitude.description hasLastKnownLocation = true if (delegate != nil){ if((delegate?.respondsToSelector(#selector(LocationManagerDelegate.locationFoundGetAsString(_:longitude:))))!){ delegate?.locationFoundGetAsString!(latitudeAsString,longitude:longitudeAsString) } if((delegate?.respondsToSelector(#selector(LocationManagerDelegate.locationFound(_:longitude:))))!){ delegate?.locationFound(latitude,longitude:longitude) } } } internal func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var hasAuthorised = false let verboseKey = status switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access" case CLAuthorizationStatus.Denied: locationStatus = "Denied access" case CLAuthorizationStatus.NotDetermined: locationStatus = "Not determined" default: locationStatus = "Allowed access" hasAuthorised = true } verboseMessage = verboseMessageDictionary[verboseKey]! if (hasAuthorised == true) { startLocationManger() }else{ resetLatLon() if (!locationStatus.isEqualToString("Denied access")){ var verbose = "" if showVerboseMessage { verbose = verboseMessage if ((delegate != nil) && (delegate?.respondsToSelector(#selector(LocationManagerDelegate.locationManagerVerboseMessage(_:))))!){ delegate?.locationManagerVerboseMessage!(verbose) } } if(completionHandler != nil){ completionHandler?(latitude: latitude, longitude: longitude, status: locationStatus as String, verboseMessage:verbose,error: nil) } } if ((delegate != nil) && (delegate?.respondsToSelector(#selector(LocationManagerDelegate.locationManagerStatus(_:))))!){ delegate?.locationManagerStatus!(locationStatus) } } } func reverseGeocodeLocationWithLatLon(latitude latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ let location:CLLocation = CLLocation(latitude:latitude, longitude: longitude) reverseGeocodeLocationWithCoordinates(location,onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler) } func reverseGeocodeLocationWithCoordinates(coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler reverseGocode(coord) } private func reverseGocode(location:CLLocation){ let geocoder: CLGeocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in if (error != nil) { self.reverseGeocodingCompletionHandler!(reverseGecodeInfo:nil,placemark:nil, error: error!.localizedDescription) } else{ if let placemark = placemarks?.first { let address = AddressParser() address.parseAppleLocationData(placemark) let addressDict = address.getAddressDictionary() self.reverseGeocodingCompletionHandler!(reverseGecodeInfo: addressDict,placemark:placemark,error: nil) } else { self.reverseGeocodingCompletionHandler!(reverseGecodeInfo: nil,placemark:nil,error: "No Placemarks Found!") return } } }) } func geocodeAddressString(address address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){ self.geocodingCompletionHandler = onGeocodingCompletionHandler geoCodeAddress(address) } private func geoCodeAddress(address:NSString){ let geocoder = CLGeocoder() geocoder.geocodeAddressString(address as String, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in if (error != nil) { self.geocodingCompletionHandler!(gecodeInfo:nil,placemark:nil,error: error!.localizedDescription) } else{ if let placemark = placemarks?.first { let address = AddressParser() address.parseAppleLocationData(placemark) let addressDict = address.getAddressDictionary() self.geocodingCompletionHandler!(gecodeInfo: addressDict,placemark:placemark,error: nil) } else { self.geocodingCompletionHandler!(gecodeInfo: nil,placemark:nil,error: "invalid address: \(address)") } } }) } func geocodeUsingGoogleAddressString(address address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){ self.geocodingCompletionHandler = onGeocodingCompletionHandler geoCodeUsignGoogleAddress(address) } private func geoCodeUsignGoogleAddress(address:NSString){ var urlString = "http://maps.googleapis.com/maps/api/geocode/json?address=\(address)&sensor=true" as NSString urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())! performOperationForURL(urlString, type: GeoCodingType.Geocoding) } func reverseGeocodeLocationUsingGoogleWithLatLon(latitude latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler reverseGocodeUsingGoogle(latitude: latitude, longitude: longitude) } func reverseGeocodeLocationUsingGoogleWithCoordinates(coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ reverseGeocodeLocationUsingGoogleWithLatLon(latitude: coord.coordinate.latitude, longitude: coord.coordinate.longitude, onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler) } private func reverseGocodeUsingGoogle(latitude latitude:Double, longitude: Double){ var urlString = "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&sensor=true" as NSString urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())! performOperationForURL(urlString, type: GeoCodingType.ReverseGeocoding) } private func performOperationForURL(urlString:NSString,type:GeoCodingType){ let url:NSURL? = NSURL(string:urlString as String) let request:NSURLRequest = NSURLRequest(URL:url!) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in if(error != nil){ self.setCompletionHandler(responseInfo:nil, placemark:nil, error:error!.localizedDescription, type:type) }else{ let kStatus = "status" let kOK = "ok" let kZeroResults = "ZERO_RESULTS" let kAPILimit = "OVER_QUERY_LIMIT" let kRequestDenied = "REQUEST_DENIED" let kInvalidRequest = "INVALID_REQUEST" let kInvalidInput = "Invalid Input" //let dataAsString: NSString? = NSString(data: data!, encoding: NSUTF8StringEncoding) let jsonResult: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary var status = jsonResult.valueForKey(kStatus) as! NSString status = status.lowercaseString if(status.isEqualToString(kOK)){ let address = AddressParser() address.parseGoogleLocationData(jsonResult) let addressDict = address.getAddressDictionary() let placemark:CLPlacemark = address.getPlacemark() self.setCompletionHandler(responseInfo:addressDict, placemark:placemark, error: nil, type:type) }else if(!status.isEqualToString(kZeroResults) && !status.isEqualToString(kAPILimit) && !status.isEqualToString(kRequestDenied) && !status.isEqualToString(kInvalidRequest)){ self.setCompletionHandler(responseInfo:nil, placemark:nil, error:kInvalidInput, type:type) } else{ //status = (status.componentsSeparatedByString("_") as NSArray).componentsJoinedByString(" ").capitalizedString self.setCompletionHandler(responseInfo:nil, placemark:nil, error:status as String, type:type) } } } task.resume() } private func setCompletionHandler(responseInfo responseInfo:NSDictionary?,placemark:CLPlacemark?, error:String?,type:GeoCodingType){ if(type == GeoCodingType.Geocoding){ self.geocodingCompletionHandler!(gecodeInfo:responseInfo,placemark:placemark,error:error) }else{ self.reverseGeocodingCompletionHandler!(reverseGecodeInfo:responseInfo,placemark:placemark,error:error) } } } @objc protocol LocationManagerDelegate : NSObjectProtocol { func locationFound(latitude:Double, longitude:Double) optional func locationFoundGetAsString(latitude:NSString, longitude:NSString) optional func locationManagerStatus(status:NSString) optional func locationManagerReceivedError(error:NSString) optional func locationManagerVerboseMessage(message:NSString) } private class AddressParser: NSObject{ private var latitude = NSString() private var longitude = NSString() private var streetNumber = NSString() private var route = NSString() private var locality = NSString() private var subLocality = NSString() private var formattedAddress = NSString() private var administrativeArea = NSString() private var administrativeAreaCode = NSString() private var subAdministrativeArea = NSString() private var postalCode = NSString() private var country = NSString() private var subThoroughfare = NSString() private var thoroughfare = NSString() private var ISOcountryCode = NSString() private var state = NSString() override init(){ super.init() } private func getAddressDictionary()-> NSDictionary{ let addressDict = NSMutableDictionary() addressDict.setValue(latitude, forKey: "latitude") addressDict.setValue(longitude, forKey: "longitude") addressDict.setValue(streetNumber, forKey: "streetNumber") addressDict.setValue(locality, forKey: "locality") addressDict.setValue(subLocality, forKey: "subLocality") addressDict.setValue(administrativeArea, forKey: "administrativeArea") addressDict.setValue(postalCode, forKey: "postalCode") addressDict.setValue(country, forKey: "country") addressDict.setValue(formattedAddress, forKey: "formattedAddress") return addressDict } private func parseAppleLocationData(placemark:CLPlacemark){ let addressLines = placemark.addressDictionary!["FormattedAddressLines"] as! NSArray //self.streetNumber = placemark.subThoroughfare ? placemark.subThoroughfare : "" self.streetNumber = (placemark.thoroughfare != nil ? placemark.thoroughfare : "")! self.locality = (placemark.locality != nil ? placemark.locality : "")! self.postalCode = (placemark.postalCode != nil ? placemark.postalCode : "")! self.subLocality = (placemark.subLocality != nil ? placemark.subLocality : "")! self.administrativeArea = (placemark.administrativeArea != nil ? placemark.administrativeArea : "")! self.country = (placemark.country != nil ? placemark.country : "")! self.longitude = placemark.location!.coordinate.longitude.description; self.latitude = placemark.location!.coordinate.latitude.description if(addressLines.count>0){ self.formattedAddress = addressLines.componentsJoinedByString(", ")} else{ self.formattedAddress = "" } } private func parseGoogleLocationData(resultDict:NSDictionary){ let locationDict = (resultDict.valueForKey("results") as! NSArray).firstObject as! NSDictionary let formattedAddrs = locationDict.objectForKey("formatted_address") as! NSString let geometry = locationDict.objectForKey("geometry") as! NSDictionary let location = geometry.objectForKey("location") as! NSDictionary let lat = location.objectForKey("lat") as! Double let lng = location.objectForKey("lng") as! Double self.latitude = lat.description self.longitude = lng.description let addressComponents = locationDict.objectForKey("address_components") as! NSArray self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name") self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name") self.streetNumber = self.subThoroughfare self.locality = component("locality", inArray: addressComponents, ofType: "long_name") self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name") self.route = component("route", inArray: addressComponents, ofType: "long_name") self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name") self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name") self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name") self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name") self.country = component("country", inArray: addressComponents, ofType: "long_name") self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name") self.formattedAddress = formattedAddrs; } private func component(component:NSString,inArray:NSArray,ofType:NSString) -> NSString{ let index:NSInteger = inArray.indexOfObjectPassingTest { (obj, idx, stop) -> Bool in let objDict:NSDictionary = obj as! NSDictionary let types:NSArray = objDict.objectForKey("types") as! NSArray let type = types.firstObject as! NSString return type.isEqualToString(component as String) } if (index == NSNotFound){ return "" } if (index >= inArray.count){ return "" } let type = ((inArray.objectAtIndex(index) as! NSDictionary).valueForKey(ofType as String)!) as! NSString if (type.length > 0){ return type } return "" } private func getPlacemark() -> CLPlacemark{ var addressDict = [String : AnyObject]() let formattedAddressArray = self.formattedAddress.componentsSeparatedByString(", ") as Array let kSubAdministrativeArea = "SubAdministrativeArea" let kSubLocality = "SubLocality" let kState = "State" let kStreet = "Street" let kThoroughfare = "Thoroughfare" let kFormattedAddressLines = "FormattedAddressLines" let kSubThoroughfare = "SubThoroughfare" let kPostCodeExtension = "PostCodeExtension" let kCity = "City" let kZIP = "ZIP" let kCountry = "Country" let kCountryCode = "CountryCode" addressDict[kSubAdministrativeArea] = self.subAdministrativeArea addressDict[kSubLocality] = self.subLocality as NSString addressDict[kState] = self.administrativeAreaCode addressDict[kStreet] = formattedAddressArray.first! as NSString addressDict[kThoroughfare] = self.thoroughfare addressDict[kFormattedAddressLines] = formattedAddressArray addressDict[kSubThoroughfare] = self.subThoroughfare addressDict[kPostCodeExtension] = "" addressDict[kCity] = self.locality addressDict[kZIP] = self.postalCode addressDict[kCountry] = self.country addressDict[kCountryCode] = self.ISOcountryCode let lat = self.latitude.doubleValue let lng = self.longitude.doubleValue let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng) let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict as [String : AnyObject]?) return (placemark as CLPlacemark) } }
a7dfbb51ba29fee2552c72b248c46ab9
37.504923
239
0.627826
false
false
false
false
karwa/swift
refs/heads/master
test/Constraints/members.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -swift-version 5 //// // Members of structs //// struct X { func f0(_ i: Int) -> X { } func f1(_ i: Int) { } mutating func f1(_ f: Float) { } func f2<T>(_ x: T) -> T { } } struct Y<T> { func f0(_: T) -> T {} func f1<U>(_ x: U, y: T) -> (T, U) {} } var i : Int var x : X var yf : Y<Float> func g0(_: (inout X) -> (Float) -> ()) {} _ = x.f0(i) x.f0(i).f1(i) g0(X.f1) // expected-error{{partial application of 'mutating' method}} _ = x.f0(x.f2(1)) _ = x.f0(1).f2(i) _ = yf.f0(1) _ = yf.f1(i, y: 1) // Members referenced from inside the struct struct Z { var i : Int func getI() -> Int { return i } mutating func incI() {} func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } } subscript (k : Int) -> Int { get { return i + k } mutating set { i -= k } } } struct GZ<T> { var i : T func getI() -> T { return i } func f1<U>(_ a: T, b: U) -> (T, U) { return (a, b) } func f2() { var f : Float var t = f1(i, b: f) f = t.1 var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}} var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}} } } var z = Z(i: 0) var getI = z.getI var incI = z.incI // expected-error{{partial application of 'mutating'}} var zi = z.getI() var zcurried1 = z.curried var zcurried2 = z.curried(0) var zcurriedFull = z.curried(0)(1) //// // Members of modules //// // Module Swift.print(3, terminator: "") //// // Unqualified references //// //// // Members of literals //// // FIXME: Crappy diagnostic "foo".lower() // expected-error{{value of type 'String' has no member 'lower'}} var tmp = "foo".debugDescription //// // Members of enums //// enum W { case Omega func foo(_ x: Int) {} func curried(_ x: Int) -> (Int) -> () {} } var w = W.Omega var foo = w.foo var fooFull : () = w.foo(0) var wcurried1 = w.curried var wcurried2 = w.curried(0) var wcurriedFull : () = w.curried(0)(1) // Member of enum type func enumMetatypeMember(_ opt: Int?) { opt.none // expected-error{{enum case 'none' cannot be used as an instance member}} } //// // Nested types //// // Reference a Type member. <rdar://problem/15034920> class G<T> { class In { class func foo() {} } } func goo() { G<Int>.In.foo() } //// // Misc ambiguities //// // <rdar://problem/15537772> struct DefaultArgs { static func f(_ a: Int = 0) -> DefaultArgs { return DefaultArgs() } init() { self = .f() } } class InstanceOrClassMethod { func method() -> Bool { return true } class func method(_ other: InstanceOrClassMethod) -> Bool { return false } } func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) { let result = InstanceOrClassMethod.method(obj) let _: Bool = result // no-warning let _: () -> Bool = InstanceOrClassMethod.method(obj) } protocol Numeric { static func +(x: Self, y: Self) -> Self } func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { } func testNumeric<T : Numeric>(_ x: T) { acceptBinaryFunc(x, +) } /* FIXME: We can't check this directly, but it can happen with multiple modules. class PropertyOrMethod { func member() -> Int { return 0 } let member = false class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 } let methodOnClass = false } func testPreferPropertyToMethod(_ obj: PropertyOrMethod) { let result = obj.member let resultChecked: Bool = result let called = obj.member() let calledChecked: Int = called let curried = obj.member as () -> Int let methodOnClass = PropertyOrMethod.methodOnClass let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass } */ struct Foo { var foo: Int } protocol ExtendedWithMutatingMethods { } extension ExtendedWithMutatingMethods { mutating func mutatingMethod() {} var mutableProperty: Foo { get { } set { } } var nonmutatingProperty: Foo { get { } nonmutating set { } } var mutatingGetProperty: Foo { mutating get { } set { } } } class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {} class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {} func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}} sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}} c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}} c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} c.nonmutatingProperty = Foo(foo: 0) c.nonmutatingProperty.foo = 0 c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = c.mutableProperty _ = c.mutableProperty.foo _ = c.nonmutatingProperty _ = c.nonmutatingProperty.foo // FIXME: diagnostic nondeterministically says "member" or "getter" _ = c.mutatingGetProperty // expected-error{{cannot use mutating}} _ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}} sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}} sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} sub.nonmutatingProperty = Foo(foo: 0) sub.nonmutatingProperty.foo = 0 sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = sub.mutableProperty _ = sub.mutableProperty.foo _ = sub.nonmutatingProperty _ = sub.nonmutatingProperty.foo _ = sub.mutatingGetProperty // expected-error{{cannot use mutating}} _ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}} var mutableC = c mutableC.mutatingMethod() mutableC.mutableProperty = Foo(foo: 0) mutableC.mutableProperty.foo = 0 mutableC.nonmutatingProperty = Foo(foo: 0) mutableC.nonmutatingProperty.foo = 0 mutableC.mutatingGetProperty = Foo(foo: 0) mutableC.mutatingGetProperty.foo = 0 _ = mutableC.mutableProperty _ = mutableC.mutableProperty.foo _ = mutableC.nonmutatingProperty _ = mutableC.nonmutatingProperty.foo _ = mutableC.mutatingGetProperty _ = mutableC.mutatingGetProperty.foo var mutableSub = sub mutableSub.mutatingMethod() mutableSub.mutableProperty = Foo(foo: 0) mutableSub.mutableProperty.foo = 0 mutableSub.nonmutatingProperty = Foo(foo: 0) mutableSub.nonmutatingProperty.foo = 0 _ = mutableSub.mutableProperty _ = mutableSub.mutableProperty.foo _ = mutableSub.nonmutatingProperty _ = mutableSub.nonmutatingProperty.foo _ = mutableSub.mutatingGetProperty _ = mutableSub.mutatingGetProperty.foo } // <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad. enum LedModules: Int { case WS2811_1x_5V } extension LedModules { static var watts: Double { return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}} } } // <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic class r15117741S { static func g() {} } func test15117741(_ s: r15117741S) { s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}} } // <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous struct UnavailMember { @available(*, unavailable) static var XYZ : UnavailMember { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}} } let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}} let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}} // <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias struct S22490787 { typealias Iterator = AnyIterator<Int> } func f22490787() { var path: S22490787 = S22490787() for p in path { // expected-error {{for-in loop requires 'S22490787' to conform to 'Sequence'}} } } // <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor enum r23942743 { case Tomato(cloud: String) } let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}} // expected-error@-1 {{cannot infer contextual base in reference to member 'none'}} // SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions enum SomeErrorType { case StandaloneError case UnderlyingError(String) static func someErrorFromString(_ str: String) -> SomeErrorType? { if str == "standalone" { return .StandaloneError } if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}} return nil } } // SR-2193: QoI: better diagnostic when a decl exists, but is not a type enum SR_2193_Error: Error { case Boom } do { throw SR_2193_Error.Boom } catch let e as SR_2193_Error.Boom { // expected-error {{enum case 'Boom' is not a member type of 'SR_2193_Error'}} } // rdar://problem/25341015 extension Sequence { func r25341015_1() -> Int { return max(1, 2) // expected-error {{use of 'max' refers to instance method 'max(by:)' rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} } } class C_25341015 { static func baz(_ x: Int, _ y: Int) {} func baz() {} func qux() { baz(1, 2) // expected-error {{static member 'baz' cannot be used on instance of type 'C_25341015'}} {{5-5=C_25341015.}} } } struct S_25341015 { static func foo(_ x: Int, y: Int) {} func foo(z: Int) {} func bar() { foo(1, y: 2) // expected-error {{static member 'foo' cannot be used on instance of type 'S_25341015'}} {{5-5=S_25341015.}} } } func r25341015() { func baz(_ x: Int, _ y: Int) {} class Bar { func baz() {} func qux() { baz(1, 2) // expected-error {{argument passed to call that takes no arguments}} } } } func r25341015_local(x: Int, y: Int) {} func r25341015_inner() { func r25341015_local() {} r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}} } // rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely func foo_32854314() -> Double { return 42 } func bar_32854314() -> Int { return 0 } extension Array where Element == Int { func foo() { let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } func foo(_ x: Int, _ y: Double) { let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } func bar() { let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}} } } // Crash in diagnoseImplicitSelfErrors() struct Aardvark { var snout: Int mutating func burrow() { dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}} } func dig(_: inout Int, _: Int) {} } func rdar33914444() { struct A { enum R<E: Error> { case e(E) // expected-note {{'e' declared here}} } struct S { enum E: Error { case e1 } let e: R<E> } } _ = A.S(e: .e1) // expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}} } // SR-5324: Better diagnostic when instance member of outer type is referenced from nested type struct Outer { var outer: Int struct Inner { var inner: Int func sum() -> Int { return inner + outer // expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}} } } } // rdar://problem/39514009 - don't crash when trying to diagnose members with special names print("hello")[0] // expected-error {{value of type '()' has no subscripts}} func rdar40537782() { class A {} class B : A { override init() {} func foo() -> A { return A() } } struct S<T> { init(_ a: T...) {} } func bar<T>(_ t: T) { _ = S(B(), .foo(), A()) // expected-error {{type 'A' has no member 'foo'}} } } func rdar36989788() { struct A<T> { func foo() -> A<T> { return self } } func bar<T>(_ x: A<T>) -> (A<T>, A<T>) { return (x.foo(), x.undefined()) // expected-error {{value of type 'A<T>' has no member 'undefined'}} } } func rdar46211109() { struct MyIntSequenceStruct: Sequence { struct Iterator: IteratorProtocol { var current = 0 mutating func next() -> Int? { return current + 1 } } func makeIterator() -> Iterator { return Iterator() } } func foo<E, S: Sequence>(_ type: E.Type) -> S? where S.Element == E { return nil } let _: MyIntSequenceStruct? = foo(Int.Self) // expected-error@-1 {{type 'Int' has no member 'Self'}} } class A {} enum B { static func foo() { bar(A()) // expected-error {{instance member 'bar' cannot be used on type 'B'}} } func bar(_: A) {} } class C { static func foo() { bar(0) // expected-error {{instance member 'bar' cannot be used on type 'C'}} } func bar(_: Int) {} } class D { static func foo() {} func bar() { foo() // expected-error {{static member 'foo' cannot be used on instance of type 'D'}} } } func rdar_48114578() { struct S<T> { var value: T static func valueOf<T>(_ v: T) -> S<T> { return S<T>(value: v) } } typealias A = (a: [String]?, b: Int) func foo(_ a: [String], _ b: Int) -> S<A> { let v = (a, b) return .valueOf(v) } func bar(_ a: [String], _ b: Int) -> S<A> { return .valueOf((a, b)) // Ok } } struct S_Min { var xmin: Int = 42 } func xmin(_: Int, _: Float) -> Int { return 0 } func xmin(_: Float, _: Int) -> Int { return 0 } extension S_Min : CustomStringConvertible { public var description: String { return "\(xmin)" // Ok } } // rdar://problem/50679161 func rdar50679161() { struct Point {} struct S { var w, h: Point } struct Q { init(a: Int, b: Int) {} init(a: Point, b: Point) {} } func foo() { _ = { () -> Void in var foo = S // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} if let v = Int?(1) { var _ = Q( a: v + foo.w, // expected-error@-1 {{instance member 'w' cannot be used on type 'S'}} // expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}} b: v + foo.h // expected-error@-1 {{instance member 'h' cannot be used on type 'S'}} // expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}} ) } } } } func rdar_50467583_and_50909555() { // rdar://problem/50467583 let _: Set = [Int][] // expected-error@-1 {{instance member 'subscript' cannot be used on type '[Int]'}} // rdar://problem/50909555 struct S { static subscript(x: Int, y: Int) -> Int { // expected-note {{'subscript(_:_:)' declared here}} return 1 } } func test(_ s: S) { s[1] // expected-error {{static member 'subscript' cannot be used on instance of type 'S'}} {{5-6=S}} // expected-error@-1 {{missing argument for parameter #2 in call}} {{8-8=, <#Int#>}} } } // SR-9396 (rdar://problem/46427500) - Nonsensical error message related to constrained extensions struct SR_9396<A, B> {} extension SR_9396 where A == Bool { // expected-note {{where 'A' = 'Int'}} func foo() {} } func test_sr_9396(_ s: SR_9396<Int, Double>) { s.foo() // expected-error {{referencing instance method 'foo()' on 'SR_9396' requires the types 'Int' and 'Bool' be equivalent}} } // rdar://problem/34770265 - Better diagnostic needed for constrained extension method call extension Dictionary where Key == String { // expected-note {{where 'Key' = 'Int'}} func rdar_34770265_key() {} } extension Dictionary where Value == String { // expected-note {{where 'Value' = 'Int'}} func rdar_34770265_val() {} } func test_34770265(_ dict: [Int: Int]) { dict.rdar_34770265_key() // expected-error@-1 {{referencing instance method 'rdar_34770265_key()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}} dict.rdar_34770265_val() // expected-error@-1 {{referencing instance method 'rdar_34770265_val()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}} }
4d8c1a3b840408f42ec44899d879b269
25.610606
226
0.640153
false
false
false
false
yakirlee/Extersion
refs/heads/master
Helpers/UIImage+Orientation.swift
mit
1
// // UIImage+Orientation.swift // TSWeChat // // Created by Hilen on 2/17/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation //https://github.com/cosnovae/fixUIImageOrientation/blob/master/fixImageOrientation.swift public extension UIImage { class func fixImageOrientation(src:UIImage) -> UIImage { if src.imageOrientation == UIImageOrientation.Up { return src } var transform: CGAffineTransform = CGAffineTransformIdentity switch src.imageOrientation { case UIImageOrientation.Down, UIImageOrientation.DownMirrored: transform = CGAffineTransformTranslate(transform, src.size.width, src.size.height) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)) break case UIImageOrientation.Left, UIImageOrientation.LeftMirrored: transform = CGAffineTransformTranslate(transform, src.size.width, 0) transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)) break case UIImageOrientation.Right, UIImageOrientation.RightMirrored: transform = CGAffineTransformTranslate(transform, 0, src.size.height) transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2)) break case UIImageOrientation.Up, UIImageOrientation.UpMirrored: break } switch src.imageOrientation { case UIImageOrientation.UpMirrored, UIImageOrientation.DownMirrored: CGAffineTransformTranslate(transform, src.size.width, 0) CGAffineTransformScale(transform, -1, 1) break case UIImageOrientation.LeftMirrored, UIImageOrientation.RightMirrored: CGAffineTransformTranslate(transform, src.size.height, 0) CGAffineTransformScale(transform, -1, 1) case UIImageOrientation.Up, UIImageOrientation.Down, UIImageOrientation.Left, UIImageOrientation.Right: break } let ctx:CGContextRef = CGBitmapContextCreate(nil, Int(src.size.width), Int(src.size.height), CGImageGetBitsPerComponent(src.CGImage), 0, CGImageGetColorSpace(src.CGImage), CGImageAlphaInfo.PremultipliedLast.rawValue)! CGContextConcatCTM(ctx, transform) switch src.imageOrientation { case UIImageOrientation.Left, UIImageOrientation.LeftMirrored, UIImageOrientation.Right, UIImageOrientation.RightMirrored: CGContextDrawImage(ctx, CGRectMake(0, 0, src.size.height, src.size.width), src.CGImage) break default: CGContextDrawImage(ctx, CGRectMake(0, 0, src.size.width, src.size.height), src.CGImage) break } let cgimage:CGImageRef = CGBitmapContextCreateImage(ctx)! let image:UIImage = UIImage(CGImage: cgimage) return image } }
ec9e1f6e93c2f92278fde4356ba71266
38.391892
225
0.675129
false
false
false
false
infinitedg/SwiftDDP
refs/heads/master
Examples/CoreData/Pods/SwiftDDP/SwiftDDP/DDPClient.swift
mit
1
// // // A DDP Client written in Swift // // Copyright (c) 2016 Peter Siegesmund <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // This software uses CryptoSwift: https://github.com/krzyzanowskim/CryptoSwift/ // import Foundation import SwiftWebSocket import XCGLogger let log = XCGLogger(identifier: "DDP") public typealias DDPMethodCallback = (result:AnyObject?, error:DDPError?) -> () public typealias DDPConnectedCallback = (session:String) -> () public typealias DDPCallback = () -> () /** DDPDelegate provides an interface to react to user events */ public protocol SwiftDDPDelegate { func ddpUserDidLogin(user:String) func ddpUserDidLogout(user:String) } /** DDPClient is the base class for communicating with a server using the DDP protocol */ public class DDPClient: NSObject { // included for storing login id and token internal let userData = NSUserDefaults.standardUserDefaults() let background: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "DDP Background Data Queue" queue.qualityOfService = .Background return queue }() // Callbacks execute in the order they're received internal let callbackQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "DDP Callback Queue" queue.maxConcurrentOperationCount = 1 queue.qualityOfService = .UserInitiated return queue }() // Document messages are processed in the order that they are received, // separately from callbacks internal let documentQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "DDP Background Queue" queue.maxConcurrentOperationCount = 1 queue.qualityOfService = .Background return queue }() // Hearbeats get a special queue so that they're not blocked by // other operations, causing the connection to close internal let heartbeat: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "DDP Heartbeat Queue" queue.qualityOfService = .Utility return queue }() let userBackground: NSOperationQueue = { let queue = NSOperationQueue() queue.name = "DDP High Priority Background Queue" queue.qualityOfService = .UserInitiated return queue }() let userMainQueue: NSOperationQueue = { let queue = NSOperationQueue.mainQueue() queue.name = "DDP High Priorty Main Queue" queue.qualityOfService = .UserInitiated return queue }() private var socket:WebSocket!{ didSet{ socket.allowSelfSignedSSL = self.allowSelfSignedSSL } } private var server:(ping:NSDate?, pong:NSDate?) = (nil, nil) internal var resultCallbacks:[String:Completion] = [:] internal var subCallbacks:[String:Completion] = [:] internal var unsubCallbacks:[String:Completion] = [:] public var url:String! private var subscriptions = [String:(id:String, name:String, ready:Bool)]() internal var events = DDPEvents() internal var connection:(ddp:Bool, session:String?) = (false, nil) public var delegate:SwiftDDPDelegate? // MARK: Settings /** Boolean value that determines whether the */ public var allowSelfSignedSSL:Bool = false { didSet{ guard let currentSocket = socket else { return } currentSocket.allowSelfSignedSSL = allowSelfSignedSSL } } /** Sets the log level. The default value is .None. Possible values: .Verbose, .Debug, .Info, .Warning, .Error, .Severe, .None */ public var logLevel = XCGLogger.LogLevel.None { didSet { log.setup(logLevel, showLogIdentifier: true, showFunctionName: true, showThreadName: true, showLogLevel: true, showFileNames: false, showLineNumbers: true, showDate: false, writeToFile: nil, fileLogLevel: .None) } } internal override init() { super.init() } /** Creates a random String id */ public func getId() -> String { let numbers = Set<Character>(["0","1","2","3","4","5","6","7","8","9"]) let uuid = NSUUID().UUIDString.stringByReplacingOccurrencesOfString("-", withString: "") var id = "" for character in uuid.characters { if (!numbers.contains(character) && (round(Float(arc4random()) / Float(UINT32_MAX)) == 1)) { id += String(character).lowercaseString } else { id += String(character) } } return id } /** Makes a DDP connection to the server - parameter url: The String url to connect to, ex. "wss://todos.meteor.com/websocket" - parameter callback: A closure that takes a String argument with the value of the websocket session token */ public func connect(url:String, callback:DDPConnectedCallback?) { self.url = url // capture the thread context in which the function is called let executionQueue = NSOperationQueue.currentQueue() socket = WebSocket(url) //Create backoff let backOff:DDPExponentialBackoff = DDPExponentialBackoff() socket.event.close = {code, reason, clean in //Use backoff to slow reconnection retries backOff.createBackoff({ log.info("Web socket connection closed with code \(code). Clean: \(clean). \(reason)") let event = self.socket.event self.socket = WebSocket(url) self.socket.event = event self.ping() }) } socket.event.error = events.onWebsocketError socket.event.open = { self.heartbeat.addOperationWithBlock() { // Add a subscription to loginServices to each connection event let callbackWithServiceConfiguration = { (session:String) in // let loginServicesSubscriptionCollection = "meteor_accounts_loginServiceConfiguration" let loginServiceConfiguration = "meteor.loginServiceConfiguration" self.sub(loginServiceConfiguration, params: nil) // /tools/meteor-services/auth.js line 922 // Resubscribe to existing subs on connection to ensure continuity self.subscriptions.forEach({ (subscription: (String, (id: String, name: String, ready: Bool))) -> () in if subscription.1.name != loginServiceConfiguration { self.sub(subscription.1.id, name: subscription.1.name, params: nil, callback: nil) } }) callback?(session: session) } var completion = Completion(callback: callbackWithServiceConfiguration) //Reset the backoff to original values backOff.reset() completion.executionQueue = executionQueue self.events.onConnected = completion self.sendMessage(["msg":"connect", "version":"1", "support":["1"]]) } } socket.event.message = { message in self.background.addOperationWithBlock() { if let text = message as? String { do { try self.ddpMessageHandler(DDPMessage(message: text)) } catch { log.debug("Message handling error. Raw message: \(text)")} } } } } private func ping() { heartbeat.addOperationWithBlock() { self.sendMessage(["msg":"ping", "id":self.getId()]) } } // Respond to a server ping private func pong(ping: DDPMessage) { heartbeat.addOperationWithBlock() { self.server.ping = NSDate() var response = ["msg":"pong"] if let id = ping.id { response["id"] = id } self.sendMessage(response) } } // Parse DDP messages and dispatch to the appropriate function internal func ddpMessageHandler(message: DDPMessage) throws { log.debug("Received message: \(message.json)") switch message.type { case .Connected: self.connection = (true, message.session!) self.events.onConnected.execute(message.session!) case .Result: callbackQueue.addOperationWithBlock() { if let id = message.id, // Message has id let completion = self.resultCallbacks[id], // There is a callback registered for the message let result = message.result { completion.execute(result, error: message.error) self.resultCallbacks[id] = nil } else if let id = message.id, let completion = self.resultCallbacks[id] { completion.execute(nil, error:message.error) self.resultCallbacks[id] = nil } } // Principal callbacks for managing data // Document was added case .Added: documentQueue.addOperationWithBlock() { if let collection = message.collection, let id = message.id { self.documentWasAdded(collection, id: id, fields: message.fields) } } // Document was changed case .Changed: documentQueue.addOperationWithBlock() { if let collection = message.collection, let id = message.id { self.documentWasChanged(collection, id: id, fields: message.fields, cleared: message.cleared) } } // Document was removed case .Removed: documentQueue.addOperationWithBlock() { if let collection = message.collection, let id = message.id { self.documentWasRemoved(collection, id: id) } } // Notifies you when the result of a method changes case .Updated: documentQueue.addOperationWithBlock() { if let methods = message.methods { self.methodWasUpdated(methods) } } // Callbacks for managing subscriptions case .Ready: documentQueue.addOperationWithBlock() { if let subs = message.subs { self.ready(subs) } } // Callback that fires when subscription has been completely removed // case .Nosub: documentQueue.addOperationWithBlock() { if let id = message.id { self.nosub(id, error: message.error) } } case .Ping: heartbeat.addOperationWithBlock() { self.pong(message) } case .Pong: heartbeat.addOperationWithBlock() { self.server.pong = NSDate() } case .Error: background.addOperationWithBlock() { self.didReceiveErrorMessage(DDPError(json: message.json)) } default: log.error("Unhandled message: \(message.json)") } } private func sendMessage(message:NSDictionary) { if let m = message.stringValue() { self.socket.send(m) } } /** Executes a method on the server. If a callback is passed, the callback is asynchronously executed when the method has completed. The callback takes two arguments: result and error. It the method call is successful, result contains the return value of the method, if any. If the method fails, error contains information about the error. - parameter name: The name of the method - parameter params: An object containing method arguments, if any - parameter callback: The closure to be executed when the method has been executed */ public func method(name: String, params: AnyObject?, callback: DDPMethodCallback?) -> String { let id = getId() let message = ["msg":"method", "method":name, "id":id] as NSMutableDictionary if let p = params { message["params"] = p } if let completionCallback = callback { let completion = Completion(callback: completionCallback) self.resultCallbacks[id] = completion } userBackground.addOperationWithBlock() { self.sendMessage(message) } return id } // // Subscribe // internal func sub(id: String, name: String, params: [AnyObject]?, callback: DDPCallback?) -> String { if let completionCallback = callback { let completion = Completion(callback: completionCallback) self.subCallbacks[id] = completion } self.subscriptions[id] = (id, name, false) let message = ["msg":"sub", "name":name, "id":id] as NSMutableDictionary if let p = params { message["params"] = p } userBackground.addOperationWithBlock() { self.sendMessage(message) } return id } /** Sends a subscription request to the server. - parameter name: The name of the subscription - parameter params: An object containing method arguments, if any */ public func sub(name: String, params: [AnyObject]?) -> String { let id = String(name.hashValue) return sub(id, name: name, params: params, callback:nil) } /** Sends a subscription request to the server. If a callback is passed, the callback asynchronously runs when the client receives a 'ready' message indicating that the initial subset of documents contained in the subscription has been sent by the server. - parameter name: The name of the subscription - parameter params: An object containing method arguments, if any - parameter callback: The closure to be executed when the server sends a 'ready' message */ public func sub(name:String, params: [AnyObject]?, callback: DDPCallback?) -> String { let id = String(name.hashValue) if let subData = findSubscription(name) { log.info("You are already subscribed to \(name)") return subData.id } return sub(id, name: name, params: params, callback: callback) } // Iterates over the Dictionary of subscriptions to find a subscription by name internal func findSubscription(name:String) -> (id:String, name:String, ready:Bool)? { for subscription in subscriptions.values { if (name == subscription.name) { return subscription } } return nil } // // Unsubscribe // /** Sends an unsubscribe request to the server. - parameter name: The name of the subscription */ public func unsub(name: String) -> String? { return unsub(name, callback: nil) } /** Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously runs when the client receives a 'ready' message indicating that the subset of documents contained in the subscription have been removed. - parameter name: The name of the subscription - parameter callback: The closure to be executed when the server sends a 'ready' message */ public func unsub(name: String, callback: DDPCallback?) -> String? { if let sub = findSubscription(name) { unsub(withId: sub.id, callback: callback) background.addOperationWithBlock() { self.sendMessage(["msg":"unsub", "id":sub.id]) } return sub.id } return nil } internal func unsub(withId id: String, callback: DDPCallback?) { if let completionCallback = callback { let completion = Completion(callback: completionCallback) unsubCallbacks[id] = completion } background.addOperationWithBlock() { self.sendMessage(["msg":"unsub", "id":id]) } } // // Responding to server subscription messages // private func ready(subs: [String]) { for id in subs { if let completion = subCallbacks[id] { completion.execute() // Run the callback subCallbacks[id] = nil // Delete the callback after running } else { // If there is no callback, execute the method if var sub = subscriptions[id] { sub.ready = true subscriptions[id] = sub subscriptionIsReady(sub.id, subscriptionName: sub.name) } } } } private func nosub(id: String, error: DDPError?) { if let e = error where (e.isValid == true) { log.error("\(e)") } else { if let completion = unsubCallbacks[id], let _ = subscriptions[id] { completion.execute() unsubCallbacks[id] = nil subscriptions[id] = nil } else { if let subscription = subscriptions[id] { subscriptions[id] = nil subscriptionWasRemoved(subscription.id, subscriptionName: subscription.name) } } } } // // public callbacks: should be overridden // /** Executes when a subscription is ready. - parameter subscriptionId: A String representation of the hash of the subscription name - parameter subscriptionName: The name of the subscription */ public func subscriptionIsReady(subscriptionId: String, subscriptionName:String) {} /** Executes when a subscription is removed. - parameter subscriptionId: A String representation of the hash of the subscription name - parameter subscriptionName: The name of the subscription */ public func subscriptionWasRemoved(subscriptionId:String, subscriptionName:String) {} /** Executes when the server has sent a new document. - parameter collection: The name of the collection that the document belongs to - parameter id: The document's unique id - parameter fields: The documents properties */ public func documentWasAdded(collection:String, id:String, fields:NSDictionary?) { if let added = events.onAdded { added(collection: collection, id: id, fields: fields) } } /** Executes when the server sends a message to remove a document. - parameter collection: The name of the collection that the document belongs to - parameter id: The document's unique id */ public func documentWasRemoved(collection:String, id:String) { if let removed = events.onRemoved { removed(collection: collection, id: id) } } /** Executes when the server sends a message to update a document. - parameter collection: The name of the collection that the document belongs to - parameter id: The document's unique id - parameter fields: Optional object with EJSON values containing the fields to update - parameter cleared: Optional array of strings (field names to delete) */ public func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?) { if let changed = events.onChanged { changed(collection:collection, id:id, fields:fields, cleared:cleared) } } /** Executes when the server sends a message indicating that the result of a method has changed. - parameter methods: An array of strings (ids passed to 'method', all of whose writes have been reflected in data messages) */ public func methodWasUpdated(methods:[String]) { if let updated = events.onUpdated { updated(methods: methods) } } /** Executes when the client receives an error message from the server. Such a message is used to represent errors raised by the method or subscription, as well as an attempt to subscribe to an unknown subscription or call an unknown method. - parameter message: A DDPError object with information about the error */ public func didReceiveErrorMessage(message: DDPError) { if let error = events.onError { error(message: message) } } }
bca180be4d4b097e3fd8374844e5a531
36.832203
242
0.59509
false
false
false
false
tankco/TTImagePicker
refs/heads/master
TCImagePickerExample/TCImagePickerExample/ViewController.swift
mit
1
// // ViewController.swift // TCImagePickerExample // // Created by 谈超 on 2017/5/3. // Copyright © 2017年 谈超. All rights reserved. // import UIKit import TCImagePicker class ViewController: UIViewController { lazy private var imageView: UIImageView = { let object = UIImageView() object.backgroundColor = UIColor.red return object }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 80)) view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 80)) imageView.addOnClickListener(target: self, action: #selector(ViewController.imageViewClick(imageView:))); } func imageViewClick(imageView:UIImageView?) { TCImagePicker.showImagePickerFromViewController(viewController: self, allowsEditing: true, iconView: self.imageView) { [unowned self](icon) in self.imageView.image = icon! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension UIView{ func addOnClickListener(target: AnyObject, action: Selector) { let gr = UITapGestureRecognizer(target: target, action: action) gr.numberOfTapsRequired = 1 isUserInteractionEnabled = true; // userInteractionEnabled = true addGestureRecognizer(gr) } }
ad72323ed7f38c4423bef4516cf921b5
41.244898
166
0.698068
false
false
false
false
IngmarStein/swift
refs/heads/master
test/Sema/diag_optional_to_any.swift
apache-2.0
1
// RUN: %target-parse-verify-swift func takeAny(_ left: Any, _ right: Any) -> Int? { return left as? Int } func throwing() throws -> Int? {} func warnOptionalToAnyCoercion(value x: Int?) -> Any { let a: Any = x // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}}{{17-17= ?? <#default value#>}} // expected-note@-2 {{force-unwrap the value to avoid this warning}}{{17-17=!}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}{{17-17= as Any}} let b: Any = x as Any let c: Any = takeAny(a, b) // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} let _: Any = takeAny(c, c) as Any let _: Any = (x) // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} let f: Any = (x as Any) let g: Any = (x) as (Any) _ = takeAny(f as? Int, g) // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} let _: Any = takeAny(f as? Int, g) as Any // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}}{{33-33= ?? <#default value#>}} // expected-note@-2 {{force-unwrap the value to avoid this warning}}{{33-33=!}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}{{33-33= as Any}} let _: Any = takeAny(f as? Int as Any, g) as Any let _: Any = x! == x! ? 1 : x // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} do { let _: Any = try throwing() // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} } catch {} return x // expected-warning {{expression implicitly coerced from 'Int?' to Any}} // expected-note@-1 {{provide a default value to avoid this warning}} // expected-note@-2 {{force-unwrap the value to avoid this warning}} // expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}} }
82b96817f93a0d301c668d552793508e
51.666667
116
0.669937
false
false
false
false
cocoascientist/Passengr
refs/heads/master
Passengr/RefreshController.swift
mit
1
// // RefreshController.swift // Passengr // // Created by Andrew Shepard on 12/9/15. // Copyright © 2015 Andrew Shepard. All rights reserved. // import UIKit enum RefreshState { case idle case updating case error } final class RefreshController: NSObject { weak var refreshControl: UIRefreshControl? weak var dataSource: PassDataSource? init(refreshControl: UIRefreshControl, dataSource: PassDataSource) { self.refreshControl = refreshControl self.dataSource = dataSource super.init() // NotificationCenter.default.addObserver(self, selector: #selector(RefreshController.handleRefresh(_:)), name: NSNotification.Name.didBecomeActiveNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func setControlState(state: RefreshState) { guard let refreshControl = refreshControl else { fatalError("refreshControl should not be nil") } let string = title(for: state) refreshControl.attributedTitle = NSAttributedString(string: string) transition(to: state) } func setControlState(error: NSError) { guard let refreshControl = refreshControl else { fatalError("refreshControl should not be nil") } let string = title(for: error) refreshControl.attributedTitle = NSAttributedString(string: string) transition(to: .error) } @objc func handleRefresh(_ notification: NSNotification) { self.dataSource?.reloadData() } private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter }() } extension RefreshController { private func transition(to state: RefreshState) { if state == .updating { let delayTime = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { [weak self] in self?.dataSource?.reloadData() }) } else { self.refreshControl?.endRefreshing() } } private func title(for state: RefreshState) -> String { guard let dataSource = dataSource else { fatalError("dataSource should not be nil") } switch state { case .error: return NSLocalizedString("Error", comment: "Error") case .updating: return NSLocalizedString("Updating...", comment: "Updating") case .idle: let dateString = self.dateFormatter.string(from: dataSource.lastUpdated) let prefix = NSLocalizedString("Updated on", comment: "Updated on") return "\(prefix) \(dateString)" } } private func title(for error: NSError) -> String { var string = title(for: .error) if let message = error.userInfo[NSLocalizedDescriptionKey] as? String { string = "\(string): \(message)" } return string } }
194027d427cb9cfb168483c27608d168
28.867925
180
0.612445
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
refs/heads/master
solutions/9_Palindrome_Number.playground/Contents.swift
mit
1
// #9 Palindrome Number https://leetcode.com/problems/palindrome-number/ // 很简单的题,没给出的条件是负数不算回文数。有个 case 1000021 一开始做错了。另外一开始写了个递归,后来发现没必要…… // 时间复杂度:O(n) 空间复杂度:O(1) class Solution { func isPalindrome(_ x: Int) -> Bool { guard x >= 0 else { return false } var divider = 1 while divider * 10 <= x { divider *= 10 } var target = x while divider >= 10 { if target / divider != target % 10 { return false } target = (target % divider) / 10 divider = divider / 100 } return true } } Solution().isPalindrome(11)
7d11cb415a8b1db1158e8951f9d596b6
22.866667
72
0.486034
false
false
false
false
devinross/curry-fire
refs/heads/master
curryfire/TKBounceBehavior.swift
mit
1
// // TKBounceBehavior.swift // Created by Devin Ross on 9/15/16. // /* curryfire || https://github.com/devinross/curry-fire 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 public class TKBounceBehavior: UIDynamicBehavior { @objc public var gravityBehavior: UIGravityBehavior @objc public var pushBehavior: UIPushBehavior @objc public var itemBehavior: UIDynamicItemBehavior @objc public var collisionBehavior: UICollisionBehavior private var _bounceDirection: CGVector = CGVector(dx: 0, dy:2.0) public init(items: [UIDynamicItem] ) { gravityBehavior = UIGravityBehavior(items: items) collisionBehavior = UICollisionBehavior(items: items) collisionBehavior.translatesReferenceBoundsIntoBoundary = true pushBehavior = UIPushBehavior(items: items, mode: .instantaneous) pushBehavior.pushDirection = _bounceDirection pushBehavior.active = false itemBehavior = UIDynamicItemBehavior(items: items) itemBehavior.elasticity = 0.45 super.init() self.addChildBehavior(gravityBehavior) self.addChildBehavior(pushBehavior) self.addChildBehavior(itemBehavior) self.addChildBehavior(collisionBehavior) } @objc public var bounceDirection : CGVector { get { return _bounceDirection } set (vector) { _bounceDirection = vector self.pushBehavior.pushDirection = vector var dx: CGFloat = 0 var dy: CGFloat = 0 if vector.dx > 0 { dx = -1 } else if vector.dx < 0 { dx = 1 } if vector.dy > 0 { dy = -1 } else if vector.dy < 0 { dy = 1 } self.gravityBehavior.gravityDirection = CGVector(dx: dx, dy:dy) } } @objc public func bounce() { self.pushBehavior.active = true } }
e67e1be12840baa918a635fb85ad6048
26.408163
67
0.748325
false
false
false
false
yhx189/WildHacks
refs/heads/master
SwiftMaps/PlayViewController.swift
apache-2.0
1
// // PlayViewController.swift // SwiftMaps // // Created by Yang Hu on 11/21/15. // Copyright © 2015 Brett Morgan. All rights reserved. // import Foundation import UIKit import GoogleMaps import Parse import AVFoundation class PlayViewController: UIViewController , ESTBeaconManagerDelegate,AVAudioPlayerDelegate, AVAudioRecorderDelegate { var allRecords: [String] = [] var audioPlayer: AVAudioPlayer? var timer = NSTimer() var counter = 0 let beaconManager = ESTBeaconManager() let beaconRegion = CLBeaconRegion( proximityUUID: NSUUID(UUIDString: "CF1A5302-EEBB-5C4F-AA18-851A36494C3D")!, identifier: "blueberry") let placesByBeacons = [ "583:38376": [ "Heavenly Sandwiches": 50, "Green & Green Salads": 150, "Mini Panini": 325 ], "648:12": [ "Heavenly Sandwiches": 250, "Green & Green Salads": 100, "Mini Panini": 20 ], "17581:4351": [ "Heavenly Sandwiches": 350, "Green & Green Salads": 500, "Mini Panini": 170 ] ] func placesNearBeacon(beacon: CLBeacon) -> [String] { let beaconKey = "\(beacon.major):\(beacon.minor)" if let places = self.placesByBeacons[beaconKey] { let sortedPlaces = Array(places).sort( { $0.1 < $1.1 }).map { $0.0 } return sortedPlaces } return [] } func beaconManager(manager: AnyObject!, beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { print("ssss") if let nearestBeacon = beacons.first as? CLBeacon { let places = placesNearBeacon(nearestBeacon) // TODO: update the UI here print(places) // TODO: remove after implementing the UI } } override func viewDidLoad() { super.viewDidLoad() self.beaconManager.delegate = self // 4. We need to request this authorization for every beacon manager self.beaconManager.requestAlwaysAuthorization() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.beaconManager.startRangingBeaconsInRegion(self.beaconRegion) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.beaconManager.stopRangingBeaconsInRegion(self.beaconRegion) } }
c131783df24fd6b118e6077687a3778b
27.375
118
0.602965
false
false
false
false
rahuliyer95/iShowcase
refs/heads/master
Example/iShowcaseExample/ViewController.swift
mit
1
// // ViewController.swift // iShowcaseExample // // Created by Rahul Iyer on 14/10/15. // Copyright © 2015 rahuliyer. All rights reserved. // import UIKit import iShowcase class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, iShowcaseDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var backgroundColor: UITextField! @IBOutlet weak var titleColor: UITextField! @IBOutlet weak var detailsColor: UITextField! @IBOutlet weak var highlightColor: UITextField! let tableData = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"] var showcase: iShowcase! var custom: Bool = false var multiple: Bool = false override func viewDidLoad() { super.viewDidLoad() setupShowcase() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) { UIView.animate(withDuration: duration, animations: { if let showcase = self.showcase { showcase.setNeedsLayout() } }) } @IBAction func barButtonClick(_ sender: UIBarButtonItem) { showcase.titleLabel.text = "Bar Button Example" showcase.detailsLabel.text = "This example highlights the Bar Button Item" showcase.setupShowcaseForBarButtonItem(sender) showcase.show() } @IBAction func defaultShowcaseClick(_ sender: UIButton) { showcase.titleLabel.text = "Default" showcase.detailsLabel.text = "This is default iShowcase with long long long long long long long long text" showcase.setupShowcaseForView(sender) showcase.show() } @IBAction func multipleShowcaseClick(_ sender: UIButton) { multiple = true defaultShowcaseClick(sender) } @IBAction func tableViewShowcaseClick(_ sender: UIButton) { showcase.titleLabel.text = "UITableView" showcase.detailsLabel.text = "This is default position example" showcase.setupShowcaseForTableView(tableView) showcase.show() } @IBAction func customShowcaseClick(_ sender: UIButton) { if backgroundColor.text!.characters.count > 0 { showcase.coverColor = UIColor.colorFromHexString(backgroundColor.text!) } if titleColor.text!.characters.count > 0 { showcase.titleLabel.textColor = UIColor.colorFromHexString(titleColor.text!) } if detailsColor.text!.characters.count > 0 { showcase.detailsLabel.textColor = UIColor.colorFromHexString(detailsColor.text!) } if highlightColor.text!.characters.count > 0 { showcase.highlightColor = UIColor.colorFromHexString(highlightColor.text!) } custom = true showcase.type = .circle showcase.titleLabel.text = "Custom" showcase.detailsLabel.text = "This is custom iShowcase" showcase.setupShowcaseForView(sender) // Uncomment this to show the showcase only once after 1st run // showcase.singleShotId = 47 showcase.show() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) super.touchesBegan(touches, with: event) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } if let cell = cell { cell.textLabel!.text = tableData[(indexPath as NSIndexPath).row] } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { showcase.titleLabel.text = "UITableView" showcase.detailsLabel.text = "This is custom position example" showcase.setupShowcaseForTableView(tableView, withIndexPath: indexPath) showcase.show() tableView.deselectRow(at: indexPath, animated: true) } fileprivate func setupShowcase() { showcase = iShowcase() showcase.delegate = self } func iShowcaseDismissed(_ showcase: iShowcase) { if multiple { showcase.titleLabel.text = "Multiple" showcase.detailsLabel.text = "This is multiple iShowcase" showcase.setupShowcaseForView(titleColor) showcase.show() multiple = false } if custom { setupShowcase() custom = false } } }
2c6099fc2f3b8e8008d627a1ef1f5489
31.89404
124
0.658345
false
false
false
false
LamGiauKhongKhoTeam/LGKK
refs/heads/master
Modules/FlagKit/FlagKit.swift
mit
1
// // FlagKit.swift // MobileTrading // // Created by Nguyen Minh on 4/6/17. // Copyright © 2017 AHDEnglish. All rights reserved. // import UIKit import Foundation import CoreGraphics open class SpriteSheet { typealias GridSize = (cols: Int, rows: Int) typealias ImageSize = (width: CGFloat, height: CGFloat) typealias Margin = (top: CGFloat, left: CGFloat, right: CGFloat, bottom: CGFloat) struct SheetInfo { fileprivate(set) var gridSize: GridSize fileprivate(set) var spriteSize: ImageSize fileprivate(set) var spriteMargin: Margin fileprivate(set) var codes: [String] } fileprivate(set) var info: SheetInfo fileprivate(set) var image: UIImage fileprivate var imageCache = [String:UIImage]() init?(sheetImage: UIImage, info sInfo: SheetInfo) { image = sheetImage info = sInfo } func getImageFor(code: String) -> UIImage? { var cimg: UIImage? cimg = imageCache[code] if cimg == nil { let rect = getRectFor(code) cimg = image.cropped(to: rect) cimg = image.cropped(to: rect) imageCache[code] = cimg } return cimg } open func getRectFor(_ code: String) -> CGRect { let spriteW = info.spriteSize.width let spriteH = info.spriteSize.height let realSpriteW = spriteW - info.spriteMargin.left - info.spriteMargin.right let realSpriteH = spriteH - info.spriteMargin.top - info.spriteMargin.bottom let idx = info.codes.index(of: code.lowercased()) ?? 0 let dx = idx % info.gridSize.cols let dy = idx/info.gridSize.cols let x = CGFloat(dx) * spriteW + info.spriteMargin.top let y = CGFloat(dy) * spriteH + info.spriteMargin.left return CGRect(x: x, y: y, width: realSpriteW, height: realSpriteH) } deinit { imageCache.removeAll() } } open class FlagKit: NSObject { static let shared = FlagKit() var spriteSheet: SpriteSheet? override init() { super.init() spriteSheet = FlagKit.loadDefault() } open class func loadDefault() -> SpriteSheet? { guard let assetsBundle = assetsBundle() else { return nil } if let infoFile = assetsBundle.path(forResource: "flags_v1", ofType: "json") { return self.loadSheetFrom(infoFile) } return nil } open class func loadSheetFrom(_ file: String) -> SpriteSheet? { guard let assetsBundle = assetsBundle() else { return nil } if let infoData = try? Data(contentsOf: URL(fileURLWithPath: file)) { do { if let infoObj = try JSONSerialization.jsonObject(with: infoData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String:Any] { if let gridSizeObj = infoObj["gridSize"] as? [String:Int], let spriteSizeObj = infoObj["spriteSize"] as? [String:CGFloat], let spriteMarginObj = infoObj["margin"] as? [String:CGFloat] { let gridSize = (gridSizeObj["cols"]!, gridSizeObj["rows"]!) let spriteSize = (spriteSizeObj["width"]!, spriteSizeObj["height"]!) let spriteMargin = (spriteMarginObj["top"]!, spriteMarginObj["left"]!, spriteMarginObj["right"]!, spriteMarginObj["bottom"]!) if let codes = (infoObj["codes"] as? String)?.components(separatedBy: ",") { if let sheetFileName = infoObj["sheetFile"] as? String, let resourceUrl = assetsBundle.resourceURL { let sheetFileUrl = resourceUrl.appendingPathComponent(sheetFileName) if let image = UIImage(contentsOfFile: sheetFileUrl.path) { let info = SpriteSheet.SheetInfo(gridSize: gridSize, spriteSize: spriteSize, spriteMargin: spriteMargin, codes: codes) return SpriteSheet(sheetImage: image, info: info) } } } } } } catch { } } return nil } fileprivate class func assetsBundle() -> Bundle? { let bundle = Bundle(for: self) guard let assetsBundlePath = bundle.path(forResource: "flag-assets", ofType: "bundle") else { return nil } return Bundle(path: assetsBundlePath); } } extension UIImage { enum JPEGQuality: CGFloat { case lowest = 0 case low = 0.25 case medium = 0.5 case high = 0.75 case highest = 1 } /// Returns the data for the specified image in PNG format /// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory. /// - returns: A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format. var png: Data? { return UIImagePNGRepresentation(self) } /// Returns the data for the specified image in JPEG format. /// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory. /// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format. func jpeg(_ quality: JPEGQuality) -> Data? { return UIImageJPEGRepresentation(self, quality.rawValue) } /// UIImage Cropped to CGRect. /// /// - Parameter rect: CGRect to crop UIImage to. /// - Returns: cropped UIImage public func cropped(to rect: CGRect) -> UIImage { guard rect.size.height < size.height && rect.size.width < size.width else { return self } guard let image: CGImage = cgImage?.cropping(to: rect) else { return self } return UIImage(cgImage: image) } }
941188dc8552b1233d807572d3bdde7c
38.913043
242
0.59197
false
false
false
false
adamnemecek/AudioKit
refs/heads/main
Tests/AudioKitTests/Node Tests/Effects Tests/ExpanderTests.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit import XCTest class ExpanderTests: XCTestCase { func testDefault() throws { try XCTSkipIf(true, "TODO This test gives different results on local machines from what CI does") let engine = AudioEngine() let url = Bundle.module.url(forResource: "12345", withExtension: "wav", subdirectory: "TestResources")! let input = AudioPlayer(url: url)! engine.output = Expander(input) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } }
1f0612e860ae81efce205fa584ee4544
33.9
111
0.679083
false
true
false
false
cloudinary/cloudinary_ios
refs/heads/master
Cloudinary/Classes/Core/BaseNetwork/CLDNValidation.swift
mit
1
// // CLDNValidation.swift // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension CLDNRequest { // MARK: Helper Types fileprivate typealias ErrorReason = CLDNError.ResponseValidationFailureReason /// Used to represent whether validation was successful or encountered an error resulting in a failure. /// /// - success: The validation was successful. /// - failure: The validation failed encountering the provided error. internal enum ValidationResult { case success case failure(Error) } fileprivate struct MIMEType { let type: String let subtype: String var isWildcard: Bool { return type == "*" && subtype == "*" } init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) #if swift(>=3.2) let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] #else let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) #endif return split.components(separatedBy: "/") }() if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false } } } // MARK: Properties internal var acceptableStatusCodes: [Int] { return Array(200..<300) } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { return accept.components(separatedBy: ",") } return ["*/*"] } // MARK: Status Code fileprivate func validate<S: Sequence>( statusCode acceptableStatusCodes: S, response: HTTPURLResponse) -> ValidationResult where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { return .success } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(CLDNError.responseValidationFailed(reason: reason)) } } // MARK: Content Type fileprivate func validate<S: Sequence>( contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, data.count > 0 else { return .success } guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .success } } let error: CLDNError = { let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) return CLDNError.responseValidationFailed(reason: reason) }() return .failure(error) } for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { return .success } } let error: CLDNError = { let reason: ErrorReason = .unacceptableContentType( acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType ) return CLDNError.responseValidationFailed(reason: reason) }() return .failure(error) } } // MARK: - extension CLDNDataRequest { /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the /// request was valid. internal typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult internal func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(self.request, response, self.delegate.data) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult internal func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult internal func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in return self.validate(contentType: acceptableContentTypes, response: response, data: data) } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult internal func validate() -> Self { let contentTypes = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } }
a1092ba16b54f238879c897f94749336
35.24
123
0.629507
false
false
false
false
jayesh15111988/JKLoginMVVMDemoSwift
refs/heads/master
JKLoginMVVMDemoSwift/TableDemoViewModel.swift
mit
1
// // TableDemoViewModel.swift // JKLoginMVVMDemoSwift // // Created by Jayesh Kawli on 10/24/16. // Copyright © 2016 Jayesh Kawli. All rights reserved. // import Foundation import ReactiveCocoa class TableDemoViewModel: NSObject { var addItemButtonActionCommand: RACCommand? dynamic var items: [String] dynamic var addItemButtonIndicator: Bool override init() { addItemButtonIndicator = false items = [] super.init() addItemButtonActionCommand = RACCommand(signal: { (signal) -> RACSignal? in return RACSignal.return(true) }) _ = addItemButtonActionCommand?.executionSignals.flatten(1).subscribeNext({ [weak self] (value) in if let value = value as? Bool { self?.addItemButtonIndicator = value } }) } func addItem() { items.append("\(items.count)") } func removeItem(at index: Int) { items.remove(at: index) } }
0faa8b99d9de90c28a24473fccc9a28f
23.804878
106
0.60472
false
false
false
false
Ethenyl/JAMFKit
refs/heads/master
JamfKit/Sources/Models/Partition.swift
mit
1
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // /// Represents a logical partition for an hard drive installed inside an hardware element managed by Jamf. @objc(JMFKPartition) public final class Partition: NSObject, Requestable { // MARK: - Constants static let NameKey = "name" static let SizeGigabytesKey = "size_gb" static let MaximumPercentageKey = "maximum_percentage" static let FormatKey = "format" static let IsRestorePartitionKey = "is_restore_partition" static let ComputerConfigurationKey = "computer_configuration" static let ReimageKey = "reimage" static let AppendToNameKey = "append_to_name" // MARK: - Properties @objc public var name = "" @objc public var sizeInGigabytes: UInt = 0 @objc public var maximumPercentage: UInt = 0 @objc public var format = "" @objc public var isRestorePartition = false @objc public var computerConfiguration = "" @objc public var reimage = false @objc public var appendToName = "" @objc public override var description: String { return "[\(String(describing: type(of: self)))][\(name)]" } // MARK: - Initialization public init?(json: [String: Any], node: String = "") { name = json[Partition.NameKey] as? String ?? "" sizeInGigabytes = json[Partition.SizeGigabytesKey] as? UInt ?? 0 maximumPercentage = json[Partition.MaximumPercentageKey] as? UInt ?? 0 format = json[Partition.FormatKey] as? String ?? "" isRestorePartition = json[Partition.IsRestorePartitionKey] as? Bool ?? false computerConfiguration = json[Partition.ComputerConfigurationKey] as? String ?? "" reimage = json[Partition.ReimageKey] as? Bool ?? false appendToName = json[Partition.AppendToNameKey] as? String ?? "" } public init?(name: String) { guard !name.isEmpty else { return nil } self.name = name super.init() } // MARK: - Functions public func toJSON() -> [String: Any] { var json = [String: Any]() json[Partition.NameKey] = name json[Partition.SizeGigabytesKey] = sizeInGigabytes json[Partition.MaximumPercentageKey] = maximumPercentage json[Partition.FormatKey] = format json[Partition.IsRestorePartitionKey] = isRestorePartition json[Partition.ComputerConfigurationKey] = computerConfiguration json[Partition.ReimageKey] = reimage json[Partition.AppendToNameKey] = appendToName return json } }
cea4d52bc7a6939853a994d52bace281
28.747253
106
0.66014
false
true
false
false
kallahir/AlbumTrackr-iOS
refs/heads/master
AlbumTracker/Artist.swift
agpl-3.0
1
// // Artist.swift // AlbumTracker // // Created by Itallo Rossi Lucas on 5/2/16. // Copyright © 2016 AlbumTrackr. All rights reserved. // import CoreData class Artist: NSManagedObject { @NSManaged var id: NSNumber @NSManaged var name: String? @NSManaged var style: String? @NSManaged var lastAlbum: String? @NSManaged var imagePath: String? // var artistAlbums: [Album] = [] struct Keys { static let id = "id" static let name = "name" static let style = "style" static let lastAlbum = "lastAlbum" static let imagePath = "imagePath" static let albums = "albums" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Artist", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) // id = dictionary[Keys.id] as! Int name = dictionary[Keys.name] as? String // style = dictionary[Keys.style] as? String lastAlbum = dictionary[Keys.lastAlbum] as? String imagePath = dictionary[Keys.imagePath] as? String } }
45da759e6c52f5bb9f7e924e39a324af
31.511628
113
0.65927
false
false
false
false
e78l/swift-corelibs-foundation
refs/heads/master
Foundation/URLProtectionSpace.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif /*! @const NSURLProtectionSpaceHTTP @abstract The protocol for HTTP */ public let NSURLProtectionSpaceHTTP: String = "NSURLProtectionSpaceHTTP" /*! @const NSURLProtectionSpaceHTTPS @abstract The protocol for HTTPS */ public let NSURLProtectionSpaceHTTPS: String = "NSURLProtectionSpaceHTTPS" /*! @const NSURLProtectionSpaceFTP @abstract The protocol for FTP */ public let NSURLProtectionSpaceFTP: String = "NSURLProtectionSpaceFTP" /*! @const NSURLProtectionSpaceHTTPProxy @abstract The proxy type for http proxies */ public let NSURLProtectionSpaceHTTPProxy: String = "NSURLProtectionSpaceHTTPProxy" /*! @const NSURLProtectionSpaceHTTPSProxy @abstract The proxy type for https proxies */ public let NSURLProtectionSpaceHTTPSProxy: String = "NSURLProtectionSpaceHTTPSProxy" /*! @const NSURLProtectionSpaceFTPProxy @abstract The proxy type for ftp proxies */ public let NSURLProtectionSpaceFTPProxy: String = "NSURLProtectionSpaceFTPProxy" /*! @const NSURLProtectionSpaceSOCKSProxy @abstract The proxy type for SOCKS proxies */ public let NSURLProtectionSpaceSOCKSProxy: String = "NSURLProtectionSpaceSOCKSProxy" /*! @const NSURLAuthenticationMethodDefault @abstract The default authentication method for a protocol */ public let NSURLAuthenticationMethodDefault: String = "NSURLAuthenticationMethodDefault" /*! @const NSURLAuthenticationMethodHTTPBasic @abstract HTTP basic authentication. Equivalent to NSURLAuthenticationMethodDefault for http. */ public let NSURLAuthenticationMethodHTTPBasic: String = "NSURLAuthenticationMethodHTTPBasic" /*! @const NSURLAuthenticationMethodHTTPDigest @abstract HTTP digest authentication. */ public let NSURLAuthenticationMethodHTTPDigest: String = "NSURLAuthenticationMethodHTTPDigest" /*! @const NSURLAuthenticationMethodHTMLForm @abstract HTML form authentication. Applies to any protocol. */ public let NSURLAuthenticationMethodHTMLForm: String = "NSURLAuthenticationMethodHTMLForm" /*! @const NSURLAuthenticationMethodNTLM @abstract NTLM authentication. */ public let NSURLAuthenticationMethodNTLM: String = "NSURLAuthenticationMethodNTLM" /*! @const NSURLAuthenticationMethodNegotiate @abstract Negotiate authentication. */ public let NSURLAuthenticationMethodNegotiate: String = "NSURLAuthenticationMethodNegotiate" /*! @const NSURLAuthenticationMethodClientCertificate @abstract SSL Client certificate. Applies to any protocol. */ public let NSURLAuthenticationMethodClientCertificate: String = "NSURLAuthenticationMethodClientCertificate" /*! @const NSURLAuthenticationMethodServerTrust @abstract SecTrustRef validation required. Applies to any protocol. */ public let NSURLAuthenticationMethodServerTrust: String = "NSURLAuthenticationMethodServerTrust" /*! @class URLProtectionSpace @discussion This class represents a protection space requiring authentication. */ open class URLProtectionSpace : NSObject, NSSecureCoding, NSCopying { private let _host: String private let _isProxy: Bool private let _proxyType: String? private let _port: Int private let _protocol: String? private let _realm: String? private let _authenticationMethod: String open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { NSUnimplemented() } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { NSUnimplemented() } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } /*! @method initWithHost:port:protocol:realm:authenticationMethod: @abstract Initialize a protection space representing an origin server, or a realm on one @param host The hostname of the server @param port The port for the server @param protocol The sprotocol for this server - e.g. "http", "ftp", "https" @param realm A string indicating a protocol-specific subdivision of a single host. For http and https, this maps to the realm string in http authentication challenges. For many other protocols it is unused. @param authenticationMethod The authentication method to use to access this protection space - valid values include nil (default method), @"digest" and @"form". @result The initialized object. */ public init(host: String, port: Int, protocol: String?, realm: String?, authenticationMethod: String?) { _host = host _port = port _protocol = `protocol` _realm = realm _authenticationMethod = authenticationMethod ?? NSURLAuthenticationMethodDefault _proxyType = nil _isProxy = false } /*! @method initWithProxyHost:port:type:realm:authenticationMethod: @abstract Initialize a protection space representing a proxy server, or a realm on one @param host The hostname of the proxy server @param port The port for the proxy server @param type The type of proxy - e.g. "http", "ftp", "SOCKS" @param realm A string indicating a protocol-specific subdivision of a single host. For http and https, this maps to the realm string in http authentication challenges. For many other protocols it is unused. @param authenticationMethod The authentication method to use to access this protection space - valid values include nil (default method) and @"digest" @result The initialized object. */ public init(proxyHost host: String, port: Int, type: String?, realm: String?, authenticationMethod: String?) { _host = host _port = port _proxyType = type _realm = realm _authenticationMethod = authenticationMethod ?? NSURLAuthenticationMethodDefault _isProxy = true _protocol = nil } /*! @method realm @abstract Get the authentication realm for which the protection space that needs authentication @discussion This is generally only available for http authentication, and may be nil otherwise. @result The realm string */ open var realm: String? { return _realm } /*! @method receivesCredentialSecurely @abstract Determine if the password for this protection space can be sent securely @result YES if a secure authentication method or protocol will be used, NO otherwise */ open var receivesCredentialSecurely: Bool { NSUnimplemented() } /*! @method host @abstract Get the proxy host if this is a proxy authentication, or the host from the URL. @result The host for this protection space. */ open var host: String { return _host } /*! @method port @abstract Get the proxy port if this is a proxy authentication, or the port from the URL. @result The port for this protection space, or 0 if not set. */ open var port: Int { return _port } /*! @method proxyType @abstract Get the type of this protection space, if a proxy @result The type string, or nil if not a proxy. */ open var proxyType: String? { return _proxyType } /*! @method protocol @abstract Get the protocol of this protection space, if not a proxy @result The type string, or nil if a proxy. */ open var `protocol`: String? { return _protocol } /*! @method authenticationMethod @abstract Get the authentication method to be used for this protection space @result The authentication method */ open var authenticationMethod: String { return _authenticationMethod } /*! @method isProxy @abstract Determine if this authenticating protection space is a proxy server @result YES if a proxy, NO otherwise */ open override func isProxy() -> Bool { return _isProxy } /*! A string that represents the contents of the URLProtectionSpace Object. This property is intended to produce readable output. */ open override var description: String { let authMethods: Set<String> = [ NSURLAuthenticationMethodDefault, NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodHTMLForm, NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate, NSURLAuthenticationMethodServerTrust ] var result = "<\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque())>: " result += "Host:\(host), " if let prot = self.protocol { result += "Server:\(prot), " } else { result += "Server:(null), " } if authMethods.contains(self.authenticationMethod) { result += "Auth-Scheme:\(self.authenticationMethod), " } else { result += "Auth-Scheme:NSURLAuthenticationMethodDefault, " } if let realm = self.realm { result += "Realm:\(realm), " } else { result += "Realm:(null), " } result += "Port:\(self.port), " if _isProxy { result += "Proxy:YES, " } else { result += "Proxy:NO, " } if let proxyType = self.proxyType { result += "Proxy-Type:\(proxyType), " } else { result += "Proxy-Type:(null)" } return result } } extension URLProtectionSpace { //an internal helper to create a URLProtectionSpace from a HTTPURLResponse static func create(using response: HTTPURLResponse) -> URLProtectionSpace { let host = response.url?.host ?? "" let port = response.url?.port ?? 80 //HTTP let _protocol = response.url?.scheme guard let wwwAuthHeader = response.allHeaderFields["Www-Authenticate"] as? String else { fatalError("Authentication failed but no Www-Authenticate header in response") } //The format of the authentication header is `<auth-scheme> realm="<realm value>"` //Example: `Basic realm="Fake Realm"` let authMethod = wwwAuthHeader.components(separatedBy: " ")[0] let realm = String(String(wwwAuthHeader.components(separatedBy: "realm=")[1].dropFirst()).dropLast()) return URLProtectionSpace(host: host, port: port, protocol: _protocol, realm: realm, authenticationMethod: authMethod) } } extension URLProtectionSpace { /*! @method distinguishedNames @abstract Returns an array of acceptable certificate issuing authorities for client certification authentication. Issuers are identified by their distinguished name and returned as a DER encoded data. @result An array of NSData objects. (Nil if the authenticationMethod is not NSURLAuthenticationMethodClientCertificate) */ public var distinguishedNames: [Data]? { NSUnimplemented() } } // TODO: Currently no implementation of Security.framework /* extension URLProtectionSpace { /*! @method serverTrust @abstract Returns a SecTrustRef which represents the state of the servers SSL transaction state @result A SecTrustRef from Security.framework. (Nil if the authenticationMethod is not NSURLAuthenticationMethodServerTrust) */ public var serverTrust: SecTrust? { NSUnimplemented() } } */
760ce28c6cb71655cfa2bdbf846bb3bc
33.762857
208
0.682748
false
false
false
false
qiscus/qiscus-sdk-ios
refs/heads/master
Qiscus/Qiscus/Extension/String+Localization.swift
mit
1
// // String+Localization.swift // Qiscus // // Created by Rahardyan Bisma on 03/05/18. // import Foundation extension String { func getLocalize(value: Int) -> String { var bundle = Qiscus.bundle if Qiscus.disableLocalization { let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj") bundle = Bundle(path: path!)! } return String(format: NSLocalizedString(self, bundle: bundle, comment: ""), value) } func getLocalize(value: String) -> String { var bundle = Qiscus.bundle if Qiscus.disableLocalization { let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj") bundle = Bundle(path: path!)! } return String(format: NSLocalizedString(self, bundle: bundle, comment: ""), value) } func getLocalize() -> String { var bundle = Qiscus.bundle if Qiscus.disableLocalization { let path = Qiscus.bundle.path(forResource: "en", ofType: "lproj") bundle = Bundle(path: path!)! } return NSLocalizedString(self, bundle: bundle, comment: "") } }
c5b30e91e934e88256cbdd0c3436e010
27.139535
90
0.570248
false
false
false
false
mmiroslav/LinEqua
refs/heads/master
Example/LinEqua/Data/Data.swift
mit
1
// // Data.swift // LinEqua // // Created by Miroslav Milivojevic on 7/5/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import LinEqua class Data: NSObject { static let shared = Data() var matrix: Matrix? { if insertedMatrix != nil { return insertedMatrix } return generatedMatrix } var generatedMatrix: Matrix? var insertedMatrix: Matrix? var resultsGauss: [Double]? = [] var resultsGaussJordan: [Double]? = [] private override init() {} func calculateGausError() -> Double { guard let resultsGauss = resultsGauss else { return 0.0 } let gaussResultsVector = Vector(withArray: resultsGauss) guard let matrix = generatedMatrix else {return 0.0} var sumGausErrors = 0.0 for row in matrix.elements { let rowVector = Vector(withArray: row) let result = rowVector.popLast() sumGausErrors += result! - (rowVector * gaussResultsVector).sum() } let rv = sumGausErrors / Double(gaussResultsVector.count) print("Gauss error: \(rv)") return abs(rv) } func calculateGausJordanError() -> Double { guard let resultsGauss = resultsGaussJordan else { return 0.0 } let gaussJordanResultsVector = Vector(withArray: resultsGauss) guard let matrix = generatedMatrix else {return 0.0} var sumGausJordanErrors = 0.0 for row in matrix.elements { let rowVector = Vector(withArray: row) let result = rowVector.popLast() sumGausJordanErrors += result! - (rowVector * gaussJordanResultsVector).sum() } let rv = sumGausJordanErrors / Double(gaussJordanResultsVector.count) print("Gauss Jordan error: \(rv)") return abs(rv) } }
7464f939c5f83f95d0004b6c9b9711cf
27.850746
89
0.595965
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Controllers/Editorials/Cells/EditorialJoinCell.swift
mit
1
//// /// EditorialJoinCell.swift // class EditorialJoinCell: EditorialCellContent { private let joinLabel = StyledLabel(style: .editorialHeader) private let joinCaption = StyledLabel(style: .editorialCaption) private let emailField = ElloTextField() private let usernameField = ElloTextField() private let passwordField = ElloTextField() private let submitButton = StyledButton(style: .editorialJoin) var onJoinChange: ((Editorial.JoinInfo) -> Void)? private var isValid: Bool { guard let email = emailField.text, let username = usernameField.text, let password = passwordField.text else { return false } return Validator.hasValidSignUpCredentials( email: email, username: username, password: password, isTermsChecked: true ) } @objc func submitTapped() { guard let email = emailField.text, let username = usernameField.text, let password = passwordField.text else { return } let info: Editorial.JoinInfo = ( email: emailField.text, username: usernameField.text, password: passwordField.text, submitted: true ) onJoinChange?(info) emailField.isEnabled = false usernameField.isEnabled = false passwordField.isEnabled = false submitButton.isEnabled = false let responder: EditorialToolsResponder? = findResponder() responder?.submitJoin( cell: self.editorialCell, email: email, username: username, password: password ) } override func style() { super.style() joinLabel.text = InterfaceString.Editorials.Join joinLabel.isMultiline = true joinCaption.text = InterfaceString.Editorials.JoinCaption joinCaption.isMultiline = true ElloTextFieldView.styleAsEmailField(emailField) ElloTextFieldView.styleAsUsernameField(usernameField) ElloTextFieldView.styleAsPasswordField(passwordField) emailField.backgroundColor = .white emailField.placeholder = InterfaceString.Editorials.EmailPlaceholder usernameField.backgroundColor = .white usernameField.placeholder = InterfaceString.Editorials.UsernamePlaceholder passwordField.backgroundColor = .white passwordField.placeholder = InterfaceString.Editorials.PasswordPlaceholder submitButton.isEnabled = false submitButton.title = InterfaceString.Editorials.SubmitJoin } override func updateConfig() { super.updateConfig() emailField.text = config.join?.email usernameField.text = config.join?.username passwordField.text = config.join?.password let enabled = !(config.join?.submitted ?? false) emailField.isEnabled = enabled usernameField.isEnabled = enabled passwordField.isEnabled = enabled submitButton.isEnabled = enabled } override func bindActions() { super.bindActions() submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside) emailField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) usernameField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) passwordField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } override func arrange() { super.arrange() editorialContentView.addSubview(joinLabel) editorialContentView.addSubview(joinCaption) editorialContentView.addSubview(emailField) editorialContentView.addSubview(usernameField) editorialContentView.addSubview(passwordField) editorialContentView.addSubview(submitButton) joinLabel.snp.makeConstraints { make in make.top.equalTo(editorialContentView).inset(Size.smallTopMargin) make.leading.equalTo(editorialContentView).inset(Size.defaultMargin) make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin) .priority(Priority.required) } joinCaption.snp.makeConstraints { make in make.top.equalTo(joinLabel.snp.bottom).offset(Size.textFieldMargin) make.leading.equalTo(editorialContentView).inset(Size.defaultMargin) make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin) .priority(Priority.required) } let fields = [emailField, usernameField, passwordField] fields.forEach { field in field.snp.makeConstraints { make in make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) } } submitButton.snp.makeConstraints { make in make.height.equalTo(Size.buttonHeight).priority(Priority.required) make.bottom.equalTo(editorialContentView).offset(-Size.defaultMargin.bottom) make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) } } override func layoutSubviews() { super.layoutSubviews() layoutIfNeeded() // why-t-f is this necessary!? // doing this simple height calculation in auto layout was a total waste of time let fields = [emailField, usernameField, passwordField] let textFieldsBottom = frame.height - Size.defaultMargin.bottom - Size.buttonHeight - Size.textFieldMargin var remainingHeight = textFieldsBottom - joinCaption.frame.maxY - Size.textFieldMargin - CGFloat(fields.count) * Size.joinMargin if remainingHeight < Size.minFieldHeight * 3 { joinCaption.isHidden = true remainingHeight += joinCaption.frame.height + Size.textFieldMargin } else { joinCaption.isVisible = true } let fieldHeight: CGFloat = min( max(ceil(remainingHeight / 3), Size.minFieldHeight), Size.maxFieldHeight ) var y: CGFloat = textFieldsBottom for field in fields.reversed() { y -= fieldHeight field.frame.origin.y = y field.frame.size.height = fieldHeight y -= Size.joinMargin } } override func prepareForReuse() { super.prepareForReuse() onJoinChange = nil } } extension EditorialJoinCell { @objc func textFieldDidChange() { let info: Editorial.JoinInfo = ( email: emailField.text, username: usernameField.text, password: passwordField.text, submitted: false ) onJoinChange?(info) submitButton.isEnabled = isValid } }
d76b045c63b379ed4eeaa6063dff1e34
35.918919
98
0.659883
false
false
false
false
peferron/algo
refs/heads/master
EPI/Linked Lists/Merge two sorted lists/swift/test.swift
mit
1
import Darwin let tests = [ ( a: [0], b: [0], merged: [0, 0] ), ( a: [0], b: [1], merged: [0, 1] ), ( a: [0, 1, 3, 4, 5, 12], b: [2, 4, 4, 6, 20], merged: [0, 1, 2, 3, 4, 4, 4, 5, 6, 12, 20] ), ] func toList(_ values: [Int]) -> Node { let first = Node(value: values.first!) var previous = first for value in values.dropFirst(1) { let current = Node(value: value) previous.next = current previous = current } return first } func toArray(_ head: Node) -> [Int] { var values = [Int]() var current: Node? = head while let c = current { values.append(c.value) current = c.next } return values } for test in tests { let actual = toArray(toList(test.a).merge(toList(test.b))) guard actual == test.merged else { print("For a \(test.a) and b \(test.b), expected merged to be \(test.merged), " + "but was \(actual)") exit(1) } }
6dd435bdc144f065177690bba6d8f6db
18.679245
89
0.479386
false
true
false
false
customerly/Customerly-iOS-SDK
refs/heads/master
CustomerlySDK/Library/CyConfig.swift
apache-2.0
1
// // CyConfig.swift // Customerly // // Created by Paolo Musolino on 09/10/16. // // import Foundation let API_BASE_URL = "https://tracking.customerly.io" + API_VERSION let API_VERSION = "/v" + cy_api_version let CUSTOMERLY_URL = "https://www.customerly.io" // The domain used for creating all Customerly errors. let cy_domain = "io.customerly.CustomerlySDK" // Extra device and app info let cy_app_version = "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "")" let cy_app_build : String = Bundle.main.object(forInfoDictionaryKey:kCFBundleVersionKey as String) as! String let cy_device = UIDevice.current.model let cy_os = UIDevice.current.systemName let cy_os_version = UIDevice.current.systemVersion let cy_app_name : String = Bundle.main.object(forInfoDictionaryKey:kCFBundleNameKey as String) as! String let cy_sdk_version = "3.1.1" let cy_api_version = "1" let cy_socket_version = "0.0.1" let cy_preferred_language = NSLocale.preferredLanguages.count > 0 ? NSLocale.preferredLanguages[0] : nil //Default parameters let base_color_template = UIColor(hexString: "#65A9E7") var user_color_template: UIColor? //Images func adminImageURL(id: Int?, pxSize: Int) -> URL{ if let admin_id = id{ return URL(string: "https://pictures.customerly.io/accounts/\(admin_id)/\(pxSize)")! } return URL(string: "https://pictures.customerly.io/accounts/-/\(pxSize)")! } func userImageURL(id: Int?, pxSize: Int) -> URL{ if let user_id = id{ return URL(string: "https://pictures.customerly.io/users/\(user_id)/\(pxSize)")! } return URL(string: "https://pictures.customerly.io/users/-/\(pxSize)")! } enum CyUserType: Int { case anonymous = 1 case lead = 2 case user = 4 }
63239187c93a9b880dfd29c2d4a49d8b
32.037736
109
0.70474
false
false
false
false
4dot/MatchMatch
refs/heads/master
MatchMatch/Controller/MatchCollectionViewDataSource.swift
mit
1
// // MatchCollectionViewDataSource.swift // MatchMatch // // Created by Park, Chanick on 5/23/17. // Copyright © 2017 Chanick Park. All rights reserved. // import Foundation import UIKit import Alamofire import AlamofireImage import SwiftyJSON // game card type typealias gameCardType = (opend: Bool, matched: Bool, card: MatchCard) // // MatchCollectionViewDataSource Class // class MatchCollectionViewDataSource : NSObject, UICollectionViewDataSource { // game cards var cards: [gameCardType] = [] // place hoder image var placeHoder: MatchCard! // total = rows * cols var rowsCnt: Int = 0 var colsCnt: Int = 0 /** @desc Request random images @param count request count */ func requestCards(rows: Int, cols: Int, complete: @escaping (Bool, [gameCardType])->Void) { let params: [String : Any] = ["tags" : "kitten", "per_page" : (rows * cols) / 2] // request count/2 // save rows, cols count for devide sections rowsCnt = rows colsCnt = cols cards.removeAll() flickrSearch(with: params) { [weak self] (success, cards) in guard let strongSelf = self else { complete(success, []) return } var imageURLs: [String] = [] // save 2 times and shuffle for card in cards { strongSelf.cards.append((false, false, card)) strongSelf.cards.append((false, false, card)) imageURLs.append(card.frontImageURL) } // shuffle strongSelf.cards = strongSelf.cards.shuffled() // request images strongSelf.requestImages(from: imageURLs, complete: { (result, images) in complete(result, strongSelf.cards) }) } } /** @desc Request random placeholder images */ func requestPlaceHoder(complete: @escaping (Bool, MatchCard)->Void) { let params: [String : Any] = ["tags" : "card deck", "per_page" : 5] // request 5 images information flickrSearch(with: params) { (success, cards) in // select one of 5 let placeHolder = cards[Int(arc4random_uniform(UInt32(cards.count)))] complete(success, placeHolder) } } // MARK: - private functions /** @desc Request random images @param count request count */ private func flickrSearch(with params: [String : Any], complete: @escaping (Bool, [MatchCard])->Void) { var parameters = params // add deault params parameters["method"] = FlickrSearchMethod parameters["api_key"] = APIKey parameters["format"] = "json" parameters["extras"] = "url_n" // URL of small, 320 on longest side size image parameters["nojsoncallback"] = 1 // request Alamofire.request(FlickrRestSeerviceURL, method: .get, parameters: parameters) .validate() .responseJSON { [weak self] (response) in var searchedCards: [MatchCard] = [] // request fail guard let _ = self else { complete(false, searchedCards) return } switch response.result { case .failure(let error): print(error) case .success: if let values = response.result.value { let json = JSON(values) print("JSON: \(json)") // get photo list let photos = json["photos"]["photo"] for (_, photoJson):(String, JSON) in photos { // add card data let card = MatchCard(with: photoJson) searchedCards.append(card) } } } // callback complete(true, searchedCards) } } /** @desc request images with URL, waiting until download all images using dispatch_group */ private func requestImages(from URLs: [String], complete: @escaping (Bool, [Image])->Void) { // create dispatch group let downloadGroup = DispatchGroup() var images: [Image] = [] let _ = DispatchQueue.global(qos: .userInitiated) DispatchQueue.concurrentPerform(iterations: URLs.count) { idx in let address = URLs[Int(idx)] downloadGroup.enter() // store to cache _ = CardImageManager.sharedInstance.retrieveImage(for: address, completion: { (image) in guard let img = image else { //?.cgImage?.copy() complete(false, images) return } // copy image //let newImage = UIImage(cgImage: img) // save images.append(img) downloadGroup.leave() }) } // notifiy when finished download all downloadGroup.notify(queue: DispatchQueue.main) { complete(true, images) } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if rowsCnt <= 0 { return 0 } return cards.count / rowsCnt } func numberOfSections(in collectionView: UICollectionView) -> Int { if colsCnt <= 0 { return 0 } return cards.count / colsCnt } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MATCH_COLLECTIONVIEW_CELL_ID, for: indexPath) as! MatchCollectionViewCell cell.clear() // save card index cell.tag = indexPath.row + (indexPath.section * colsCnt) let card = cards[cell.tag] // default placeholder(back view) cell.imageView[CardViewType.Back.rawValue].image = UIImage(named: "placeHolder")?.af_imageRounded(withCornerRadius: 4.0) let imgURL = card.card.frontImageURL if imgURL.isEmpty { return cell } // Request image from cache (already stored cache) _ = CardImageManager.sharedInstance.retrieveImage(for: imgURL) { image in if image != nil { DispatchQueue.main.async { // set front image cell.imageView[CardViewType.Front.rawValue].image = image?.af_imageRounded(withCornerRadius: 4.0) } } } return cell } }
28a7fad44f7a871742a40e59379b7ad1
31.231441
148
0.511177
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
iOS/ViewControllers/Login/PasswordLoginViewController.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import SafariServices import UIKit import WebKit class PasswordLoginViewController: UIViewController, LoginViewController, WKUIDelegate { @IBOutlet private weak var emailField: UITextField! @IBOutlet private weak var passwordField: UITextField! @IBOutlet private weak var loginButton: LoadingButton! @IBOutlet private weak var registerButton: UIButton! @IBOutlet private weak var singleSignOnView: UIView! @IBOutlet private weak var singleSignOnLabel: UILabel! @IBOutlet private weak var singleSignOnButton: UIButton! @IBOutlet private weak var centerInputFieldsConstraints: NSLayoutConstraint! @IBOutlet private var textFieldBackgroundViews: [UIView]! weak var loginDelegate: LoginDelegate? override func viewDidLoad() { super.viewDidLoad() self.loginButton.backgroundColor = Brand.default.colors.primary self.registerButton.backgroundColor = Brand.default.colors.primaryLight self.registerButton.tintColor = ColorCompatibility.secondaryLabel self.textFieldBackgroundViews.forEach { $0.layer.roundCorners(for: .default) } self.loginButton.layer.roundCorners(for: .default) self.registerButton.layer.roundCorners(for: .default) self.singleSignOnButton.layer.roundCorners(for: .default) self.loginButton.layer.roundCorners(for: .default) self.registerButton.layer.roundCorners(for: .default) self.singleSignOnButton.layer.roundCorners(for: .default) NotificationCenter.default.addObserver(self, selector: #selector(adjustViewForKeyboardShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(adjustViewForKeyboardHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) if let singleSignOnConfig = Brand.default.singleSignOn { self.singleSignOnView.isHidden = false self.singleSignOnButton.backgroundColor = Brand.default.colors.primary self.singleSignOnButton.setTitle(singleSignOnConfig.buttonTitle, for: .normal) // Disable native registration self.registerButton.isHidden = singleSignOnConfig.disabledRegistration if singleSignOnConfig.disabledRegistration { self.singleSignOnLabel.text = NSLocalizedString("login.sso.label.login or sign up with", comment: "Label for SSO login and signup") } else { self.singleSignOnLabel.text = NSLocalizedString("login.sso.label.login with", comment: "Label for SSO login") } } else { self.singleSignOnView.isHidden = true } } @IBAction private func dismiss() { self.presentingViewController?.dismiss(animated: trueUnlessReduceMotionEnabled) } @IBAction private func login() { guard let email = emailField.text, let password = passwordField.text else { self.emailField.shake() self.passwordField.shake() return } self.loginButton.startAnimation() let dispatchTime = 500.milliseconds.fromNow UserProfileHelper.shared.login(email, password: password).earliest(at: dispatchTime).onComplete { [weak self] _ in self?.loginButton.stopAnimation() }.onSuccess { [weak self] _ in self?.loginDelegate?.didSuccessfullyLogin() self?.presentingViewController?.dismiss(animated: trueUnlessReduceMotionEnabled) }.onFailure { [weak self] _ in self?.emailField.shake() self?.passwordField.shake() } } @IBAction private func register() { let safariVC = SFSafariViewController(url: Routes.register) safariVC.preferredControlTintColor = Brand.default.colors.window self.present(safariVC, animated: trueUnlessReduceMotionEnabled) } @IBAction private func forgotPassword() { let safariVC = SFSafariViewController(url: Routes.localizedForgotPasswordURL) safariVC.preferredControlTintColor = Brand.default.colors.window self.present(safariVC, animated: true) } @IBAction private func singleSignOn() { self.performSegue(withIdentifier: R.segue.passwordLoginViewController.showSSOWebView, sender: self) } @IBAction private func dismissKeyboard() { self.emailField.resignFirstResponder() self.passwordField.resignFirstResponder() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let typedInfo = R.segue.passwordLoginViewController.showSSOWebView(segue: segue) { typedInfo.destination.loginDelegate = self.loginDelegate typedInfo.destination.url = Routes.singleSignOn } } @objc func adjustViewForKeyboardShow(_ notification: Notification) { // On some devices, the keyboard can overlap with some UI elements. To prevent this, we move // the `inputContainer` upwards. The other views will reposition accordingly. let keyboardFrameValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue let keyboardHeight = keyboardFrameValue?.cgRectValue.size.height ?? 0.0 let contentInset = self.view.safeAreaInsets.top + self.view.safeAreaInsets.bottom let viewHeight = self.view.frame.size.height - contentInset let overlappingOffset = 0.5 * viewHeight - keyboardHeight - self.emailField.frame.size.height - 8.0 self.centerInputFieldsConstraints.constant = min(overlappingOffset, 0) // we only want to move the container upwards UIView.animate(withDuration: defaultAnimationDuration) { self.view.layoutIfNeeded() } } @objc func adjustViewForKeyboardHide(_ notification: Notification) { self.centerInputFieldsConstraints.constant = 0 UIView.animate(withDuration: defaultAnimationDuration) { self.view.layoutIfNeeded() } } } extension PasswordLoginViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { self.emailField.layoutIfNeeded() self.passwordField.layoutIfNeeded() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if textField == self.emailField { self.passwordField.becomeFirstResponder() } else if textField === self.passwordField { self.login() } return true } } protocol LoginViewController: AnyObject { var loginDelegate: LoginDelegate? { get set } } protocol LoginDelegate: AnyObject { func didSuccessfullyLogin() }
90535b47127493364d5c6dc8406b601a
39.090395
147
0.678269
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/InputBar/InputBar.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import Down import WireDataModel import WireCommonComponents extension Settings { var returnKeyType: UIReturnKeyType { let disableSendButton: Bool? = self[.sendButtonDisabled] return disableSendButton == true ? .send : .default } } enum EphemeralState: Equatable { case conversation case message case none var isEphemeral: Bool { return [.message, .conversation].contains(self) } } enum InputBarState: Equatable { case writing(ephemeral: EphemeralState) case editing(originalText: String, mentions: [Mention]) case markingDown(ephemeral: EphemeralState) var isWriting: Bool { switch self { case .writing: return true default: return false } } var isEditing: Bool { switch self { case .editing: return true default: return false } } var isMarkingDown: Bool { switch self { case .markingDown: return true default: return false } } var isEphemeral: Bool { switch self { case .markingDown(let ephemeral): return ephemeral.isEphemeral case .writing(let ephemeral): return ephemeral.isEphemeral default: return false } } var isEphemeralEnabled: Bool { switch self { case .markingDown(let ephemeral): return ephemeral == .message case .writing(let ephemeral): return ephemeral == .message default: return false } } mutating func changeEphemeralState(to newState: EphemeralState) { switch self { case .markingDown: self = .markingDown(ephemeral: newState) case .writing: self = .writing(ephemeral: newState) default: return } } } private struct InputBarConstants { let buttonsBarHeight: CGFloat = 56 } final class InputBar: UIView { typealias ConversationInputBar = L10n.Localizable.Conversation.InputBar private let inputBarVerticalInset: CGFloat = 34 static let rightIconSize: CGFloat = 32 private let textViewFont = FontSpec.normalRegularFont.font! let textView = MarkdownTextView(with: DownStyle.compact) let leftAccessoryView = UIView() let rightAccessoryStackView: UIStackView = { let stackView = UIStackView() let rightInset = (stackView.conversationHorizontalMargins.left - rightIconSize) / 2 stackView.spacing = 16 stackView.axis = .horizontal stackView.alignment = .center stackView.distribution = .fill stackView.isLayoutMarginsRelativeArrangement = true return stackView }() // Contains and clips the buttonInnerContainer let buttonContainer = UIView() // Contains editingView and mardownView let secondaryButtonsView: InputBarSecondaryButtonsView let buttonsView: InputBarButtonsView let editingView = InputBarEditView() let markdownView = MarkdownBarView() var editingBackgroundColor = SemanticColors.LegacyColors.brightYellow var barBackgroundColor: UIColor? = SemanticColors.SearchBar.backgroundInputView var writingSeparatorColor: UIColor? = SemanticColors.View.backgroundSeparatorCell var ephemeralColor: UIColor { return .accent() } var placeholderColor: UIColor = SemanticColors.SearchBar.textInputViewPlaceholder var textColor: UIColor? = SemanticColors.SearchBar.textInputView private lazy var rowTopInsetConstraint: NSLayoutConstraint = buttonInnerContainer.topAnchor.constraint(equalTo: buttonContainer.topAnchor, constant: -constants.buttonsBarHeight) // Contains the secondaryButtonsView and buttonsView private let buttonInnerContainer = UIView() fileprivate let buttonRowSeparator = UIView() fileprivate let constants = InputBarConstants() private lazy var leftAccessoryViewWidthConstraint: NSLayoutConstraint = leftAccessoryView.widthAnchor.constraint(equalToConstant: conversationHorizontalMargins.left) var isEditing: Bool { return inputBarState.isEditing } var isMarkingDown: Bool { return inputBarState.isMarkingDown } private var inputBarState: InputBarState = .writing(ephemeral: .none) { didSet { updatePlaceholder() updatePlaceholderColors() } } func changeEphemeralState(to newState: EphemeralState) { inputBarState.changeEphemeralState(to: newState) } var invisibleInputAccessoryView: InvisibleInputAccessoryView? { didSet { textView.inputAccessoryView = invisibleInputAccessoryView } } var availabilityPlaceholder: NSAttributedString? { didSet { updatePlaceholder() } } override var bounds: CGRect { didSet { invisibleInputAccessoryView?.overriddenIntrinsicContentSize = CGSize(width: UIView.noIntrinsicMetric, height: bounds.height) } } override func didMoveToWindow() { super.didMoveToWindow() // This is a workaround for UITextView truncating long contents. // However, this breaks the text view on iOS 8 ¯\_(ツ)_/¯. textView.isScrollEnabled = false textView.isScrollEnabled = true } required init(buttons: [UIButton]) { buttonsView = InputBarButtonsView(buttons: buttons) secondaryButtonsView = InputBarSecondaryButtonsView(editBarView: editingView, markdownBarView: markdownView) super.init(frame: CGRect.zero) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapBackground)) addGestureRecognizer(tapGestureRecognizer) buttonsView.clipsToBounds = true buttonContainer.clipsToBounds = true [leftAccessoryView, textView, rightAccessoryStackView, buttonContainer, buttonRowSeparator].forEach(addSubview) buttonContainer.addSubview(buttonInnerContainer) [buttonsView, secondaryButtonsView].forEach(buttonInnerContainer.addSubview) setupViews() updateRightAccessoryStackViewLayoutMargins() createConstraints() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(markdownView, selector: #selector(markdownView.textViewDidChangeActiveMarkdown), name: Notification.Name.MarkdownTextViewDidChangeActiveMarkdown, object: textView) notificationCenter.addObserver(self, selector: #selector(textViewTextDidChange), name: UITextView.textDidChangeNotification, object: textView) notificationCenter.addObserver(self, selector: #selector(textViewDidBeginEditing), name: UITextView.textDidBeginEditingNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(textViewDidEndEditing), name: UITextView.textDidEndEditingNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(sendButtonEnablingDidApplyChanges), name: NSNotification.Name.disableSendButtonChanged, object: nil) } /// Update return key type when receiving a notification (from setting->toggle send key option) @objc private func sendButtonEnablingDidApplyChanges() { updateReturnKey() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupViews() { textView.accessibilityIdentifier = "inputField" updatePlaceholder() textView.lineFragmentPadding = 0 textView.textAlignment = .natural textView.textContainerInset = UIEdgeInsets(top: inputBarVerticalInset / 2, left: 0, bottom: inputBarVerticalInset / 2, right: 4) textView.placeholderTextContainerInset = UIEdgeInsets(top: 21, left: 10, bottom: 21, right: 0) textView.keyboardType = .default textView.keyboardAppearance = .default textView.placeholderTextTransform = .none textView.tintAdjustmentMode = .automatic textView.font = textViewFont textView.placeholderFont = textViewFont textView.backgroundColor = .clear markdownView.delegate = textView self.addBorder(for: .top) updateReturnKey() updateInputBar(withState: inputBarState, animated: false) updateColors() } fileprivate func createConstraints() { [buttonContainer, textView, buttonRowSeparator, leftAccessoryView, rightAccessoryStackView, secondaryButtonsView, buttonsView, buttonInnerContainer].prepareForLayout() let rightAccessoryViewWidthConstraint = rightAccessoryStackView.widthAnchor.constraint(equalToConstant: 0) rightAccessoryViewWidthConstraint.priority = .defaultHigh NSLayoutConstraint.activate([ leftAccessoryView.leadingAnchor.constraint(equalTo: leftAccessoryView.superview!.leadingAnchor), leftAccessoryView.topAnchor.constraint(equalTo: leftAccessoryView.superview!.topAnchor), leftAccessoryView.bottomAnchor.constraint(equalTo: buttonContainer.topAnchor), leftAccessoryViewWidthConstraint, rightAccessoryStackView.trailingAnchor.constraint(equalTo: rightAccessoryStackView.superview!.trailingAnchor), rightAccessoryStackView.topAnchor.constraint(equalTo: rightAccessoryStackView.superview!.topAnchor), rightAccessoryViewWidthConstraint, rightAccessoryStackView.bottomAnchor.constraint(equalTo: buttonContainer.topAnchor), buttonContainer.topAnchor.constraint(equalTo: textView.bottomAnchor), textView.topAnchor.constraint(equalTo: textView.superview!.topAnchor), textView.leadingAnchor.constraint(equalTo: leftAccessoryView.trailingAnchor), textView.trailingAnchor.constraint(lessThanOrEqualTo: textView.superview!.trailingAnchor, constant: -16), textView.trailingAnchor.constraint(equalTo: rightAccessoryStackView.leadingAnchor), textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 56), textView.heightAnchor.constraint(lessThanOrEqualToConstant: 120), buttonRowSeparator.topAnchor.constraint(equalTo: buttonContainer.topAnchor), buttonRowSeparator.leadingAnchor.constraint(equalTo: buttonRowSeparator.superview!.leadingAnchor, constant: 16), buttonRowSeparator.trailingAnchor.constraint(equalTo: buttonRowSeparator.superview!.trailingAnchor, constant: -16), buttonRowSeparator.heightAnchor.constraint(equalToConstant: .hairline), secondaryButtonsView.topAnchor.constraint(equalTo: buttonInnerContainer.topAnchor), secondaryButtonsView.leadingAnchor.constraint(equalTo: buttonInnerContainer.leadingAnchor), secondaryButtonsView.trailingAnchor.constraint(equalTo: buttonInnerContainer.trailingAnchor), secondaryButtonsView.bottomAnchor.constraint(equalTo: buttonsView.topAnchor), secondaryButtonsView.heightAnchor.constraint(equalToConstant: constants.buttonsBarHeight), buttonsView.leadingAnchor.constraint(equalTo: buttonInnerContainer.leadingAnchor), buttonsView.trailingAnchor.constraint(lessThanOrEqualTo: buttonInnerContainer.trailingAnchor), buttonsView.bottomAnchor.constraint(equalTo: buttonInnerContainer.bottomAnchor), buttonContainer.bottomAnchor.constraint(equalTo: buttonContainer.superview!.bottomAnchor), buttonContainer.leadingAnchor.constraint(equalTo: buttonContainer.superview!.leadingAnchor), buttonContainer.trailingAnchor.constraint(equalTo: buttonContainer.superview!.trailingAnchor), buttonContainer.heightAnchor.constraint(equalToConstant: constants.buttonsBarHeight), buttonInnerContainer.leadingAnchor.constraint(equalTo: buttonContainer.leadingAnchor), buttonInnerContainer.trailingAnchor.constraint(equalTo: buttonContainer.trailingAnchor), rowTopInsetConstraint ]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass else { return } updateLeftAccessoryViewWidth() updateRightAccessoryStackViewLayoutMargins() } fileprivate func updateLeftAccessoryViewWidth() { leftAccessoryViewWidthConstraint.constant = conversationHorizontalMargins.left } fileprivate func updateRightAccessoryStackViewLayoutMargins() { let rightInset = (conversationHorizontalMargins.left - InputBar.rightIconSize) / 2 rightAccessoryStackView.layoutMargins = UIEdgeInsets(top: 0, left: rightInset, bottom: 0, right: rightInset) } @objc private func didTapBackground(_ gestureRecognizer: UITapGestureRecognizer!) { guard gestureRecognizer.state == .recognized else { return } buttonsView.showRow(0, animated: true) } func updateReturnKey() { textView.returnKeyType = isMarkingDown ? .default : Settings.shared.returnKeyType textView.reloadInputViews() } func updatePlaceholder() { textView.attributedPlaceholder = placeholderText(for: inputBarState) textView.setNeedsLayout() } func placeholderText(for state: InputBarState) -> NSAttributedString? { var placeholder = NSAttributedString(string: ConversationInputBar.placeholder) if let availabilityPlaceholder = availabilityPlaceholder { placeholder = availabilityPlaceholder } else if inputBarState.isEphemeral { placeholder = NSAttributedString(string: ConversationInputBar.placeholderEphemeral) && ephemeralColor } if state.isEditing { return nil } else { return placeholder } } // MARK: - Disable interactions on the lower part to not to interfere with the keyboard override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if self.textView.isFirstResponder { if super.point(inside: point, with: event) { let locationInButtonRow = buttonInnerContainer.convert(point, from: self) return locationInButtonRow.y < buttonInnerContainer.bounds.height / 1.3 } else { return false } } else { return super.point(inside: point, with: event) } } // MARK: - InputBarState func setInputBarState(_ state: InputBarState, animated: Bool) { let oldState = inputBarState inputBarState = state updateInputBar(withState: state, oldState: oldState, animated: animated) } private func updateInputBar(withState state: InputBarState, oldState: InputBarState? = nil, animated: Bool = true) { updateEditViewState() updatePlaceholder() updateReturnKey() rowTopInsetConstraint.constant = state.isWriting ? -constants.buttonsBarHeight : 0 let textViewChanges = { switch state { case .writing: if let oldState = oldState, oldState.isEditing { self.textView.text = nil } case .editing(let text, let mentions): self.setInputBarText(text, mentions: mentions) self.secondaryButtonsView.setEditBarView() case .markingDown: self.secondaryButtonsView.setMarkdownBarView() } } let completion: () -> Void = { self.updateColors() self.updatePlaceholderColors() if state.isEditing { self.textView.becomeFirstResponder() } } if animated && self.superview != nil { UIView.animate(easing: .easeInOutExpo, duration: 0.3, animations: layoutIfNeeded) UIView.transition(with: self.textView, duration: 0.1, options: [], animations: textViewChanges) { _ in self.updateColors() completion() } } else { layoutIfNeeded() textViewChanges() completion() } } func updateEphemeralState() { guard inputBarState.isWriting else { return } updateColors() updatePlaceholder() } fileprivate func backgroundColor(forInputBarState state: InputBarState) -> UIColor? { guard let writingColor = barBackgroundColor else { return nil } return state.isWriting || state.isMarkingDown ? writingColor : writingColor.mix(editingBackgroundColor, amount: 0.16) } fileprivate func updatePlaceholderColors() { if inputBarState.isEphemeral && inputBarState.isEphemeralEnabled && availabilityPlaceholder == nil { textView.placeholderTextColor = ephemeralColor } else { textView.placeholderTextColor = placeholderColor } } fileprivate func updateColors() { backgroundColor = backgroundColor(forInputBarState: inputBarState) buttonRowSeparator.backgroundColor = writingSeparatorColor updatePlaceholderColors() textView.tintColor = .accent() textView.updateTextColor(base: textColor) var buttons = self.buttonsView.buttons buttons.append(self.buttonsView.expandRowButton) buttons.forEach { button in guard let button = button as? IconButton else { return } button.layer.borderWidth = 1 button.setIconColor(SemanticColors.Button.textInputBarItemEnabled, for: .normal) button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemEnabled, for: .normal) button.setBorderColor(SemanticColors.Button.borderInputBarItemEnabled, for: .normal) button.setIconColor(SemanticColors.Button.textInputBarItemHighlighted, for: .highlighted) button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemHighlighted, for: .highlighted) button.setBorderColor(SemanticColors.Button.borderInputBarItemHighlighted, for: .highlighted) button.setIconColor(SemanticColors.Button.textInputBarItemHighlighted, for: .selected) button.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemHighlighted, for: .selected) button.setBorderColor(SemanticColors.Button.borderInputBarItemHighlighted, for: .selected) } } // MARK: – Editing View State func setInputBarText(_ text: String, mentions: [Mention]) { textView.setText(text, withMentions: mentions) textView.setContentOffset(.zero, animated: false) textView.undoManager?.removeAllActions() updateEditViewState() } func undo() { guard inputBarState.isEditing else { return } guard let undoManager = textView.undoManager, undoManager.canUndo else { return } undoManager.undo() updateEditViewState() } fileprivate func updateEditViewState() { if case .editing(let text, _) = inputBarState { let canUndo = textView.undoManager?.canUndo ?? false editingView.undoButton.isEnabled = canUndo // We do not want to enable the confirm button when // the text is the same as the original message let trimmedText = textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let hasChanges = text != trimmedText && canUndo editingView.confirmButton.isEnabled = hasChanges } } } extension InputBar { @objc func textViewTextDidChange(_ notification: Notification) { updateEditViewState() } @objc func textViewDidBeginEditing(_ notification: Notification) { updateEditViewState() } @objc func textViewDidEndEditing(_ notification: Notification) { updateEditViewState() } }
2d9324989f9174c29e7c7a723cfc7278
37.349265
202
0.697584
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/Unit/Simulation/View/NoteScoreTableViewSectionHeader.swift
mit
1
// // NoteScoreTableViewSectionHeader.swift // DereGuide // // Created by zzk on 2017/3/29. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit class NoteScoreTableViewSectionHeader: UITableViewHeaderFooterView { enum Title { case text(String) case icon(UIImage) } var labelTitles: [Title] = [ .text(NSLocalizedString("序号", comment: "")), .icon(#imageLiteral(resourceName: "score-bonus")), .icon(#imageLiteral(resourceName: "combo-bonus")), .icon(#imageLiteral(resourceName: "skill-boost")), .text(NSLocalizedString("得分", comment: "")), .text(NSLocalizedString("累计", comment: "")) ] var titleViews = [UIView]() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) for title in labelTitles { switch title { case .icon(let image): let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFit contentView.addSubview(imageView) titleViews.append(imageView) case .text(let text): let label = UILabel() label.adjustsFontSizeToFitWidth = true label.text = text label.textAlignment = .center label.baselineAdjustment = .alignCenters contentView.addSubview(label) titleViews.append(label) } } } override func layoutSubviews() { super.layoutSubviews() let space: CGFloat = 5 for i in 0..<titleViews.count { let view = titleViews[i] let width = (bounds.size.width - CGFloat(titleViews.count + 1) * space) / CGFloat(titleViews.count) let height = bounds.size.height view.frame = CGRect.init(x: CGFloat(i) * width + CGFloat(i + 1) * space, y: 0, width: width, height: height) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
330974a9164c195dbae39414de461249
31.646154
120
0.581527
false
false
false
false
Bijiabo/F-Client-iOS
refs/heads/master
F/Library/DeviceGuru.swift
gpl-2.0
1
// // DeviceGuru.swift // // Created by Inder Kumar Rathore on 06/02/15. // Copyright (c) 2015. All rights reserved. // import Foundation import UIKit /// Enum for different iPhone/iPad devices public enum Hardware: NSInteger { case NOT_AVAILABLE case IPHONE_2G case IPHONE_3G case IPHONE_3GS case IPHONE_4 case IPHONE_4_CDMA case IPHONE_4S case IPHONE_5 case IPHONE_5_CDMA_GSM case IPHONE_5C case IPHONE_5C_CDMA_GSM case IPHONE_5S case IPHONE_5S_CDMA_GSM case IPHONE_6 case IPHONE_6_PLUS case IPHONE_6S case IPHONE_6S_PLUS case IPOD_TOUCH_1G case IPOD_TOUCH_2G case IPOD_TOUCH_3G case IPOD_TOUCH_4G case IPOD_TOUCH_5G case IPAD case IPAD_2 case IPAD_2_WIFI case IPAD_2_CDMA case IPAD_3 case IPAD_3G case IPAD_3_WIFI case IPAD_3_WIFI_CDMA case IPAD_4 case IPAD_4_WIFI case IPAD_4_GSM_CDMA case IPAD_MINI case IPAD_MINI_WIFI case IPAD_MINI_WIFI_CDMA case IPAD_MINI_RETINA_WIFI case IPAD_MINI_RETINA_WIFI_CDMA case IPAD_MINI_3_WIFI case IPAD_MINI_3_WIFI_CELLULAR case IPAD_MINI_RETINA_WIFI_CELLULAR_CN case IPAD_AIR_WIFI case IPAD_AIR_WIFI_GSM case IPAD_AIR_WIFI_CDMA case IPAD_AIR_2_WIFI case IPAD_AIR_2_WIFI_CELLULAR case SIMULATOR } /// This method retruns the hardware type /// /// /// - returns: raw `String` of device type /// public func hardwareString() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var hw_machine = [CChar](count: Int(size), repeatedValue: 0) sysctl(&name, 2, &hw_machine, &size, &name, 0) let hardware: String = String.fromCString(hw_machine)! return hardware } /// This method returns the Hardware enum depending upon harware string /// /// /// - returns: `Hardware` type of the device /// public func hardware() -> Hardware { let hardware = hardwareString() if (hardware == "iPhone1,1") { return Hardware.IPHONE_2G } if (hardware == "iPhone1,2") { return Hardware.IPHONE_3G } if (hardware == "iPhone2,1") { return Hardware.IPHONE_3GS } if (hardware == "iPhone3,1") { return Hardware.IPHONE_4 } if (hardware == "iPhone3,2") { return Hardware.IPHONE_4 } if (hardware == "iPhone3,3") { return Hardware.IPHONE_4_CDMA } if (hardware == "iPhone4,1") { return Hardware.IPHONE_4S } if (hardware == "iPhone5,1") { return Hardware.IPHONE_5 } if (hardware == "iPhone5,2") { return Hardware.IPHONE_5_CDMA_GSM } if (hardware == "iPhone5,3") { return Hardware.IPHONE_5C } if (hardware == "iPhone5,4") { return Hardware.IPHONE_5C_CDMA_GSM } if (hardware == "iPhone6,1") { return Hardware.IPHONE_5S } if (hardware == "iPhone6,2") { return Hardware.IPHONE_5S_CDMA_GSM } if (hardware == "iPhone7,1") { return Hardware.IPHONE_6_PLUS } if (hardware == "iPhone7,2") { return Hardware.IPHONE_6 } if (hardware == "iPhone8,2") { return Hardware.IPHONE_6S_PLUS } if (hardware == "iPhone8,1") { return Hardware.IPHONE_6S } if (hardware == "iPod1,1") { return Hardware.IPOD_TOUCH_1G } if (hardware == "iPod2,1") { return Hardware.IPOD_TOUCH_2G } if (hardware == "iPod3,1") { return Hardware.IPOD_TOUCH_3G } if (hardware == "iPod4,1") { return Hardware.IPOD_TOUCH_4G } if (hardware == "iPod5,1") { return Hardware.IPOD_TOUCH_5G } if (hardware == "iPad1,1") { return Hardware.IPAD } if (hardware == "iPad1,2") { return Hardware.IPAD_3G } if (hardware == "iPad2,1") { return Hardware.IPAD_2_WIFI } if (hardware == "iPad2,2") { return Hardware.IPAD_2 } if (hardware == "iPad2,3") { return Hardware.IPAD_2_CDMA } if (hardware == "iPad2,4") { return Hardware.IPAD_2 } if (hardware == "iPad2,5") { return Hardware.IPAD_MINI_WIFI } if (hardware == "iPad2,6") { return Hardware.IPAD_MINI } if (hardware == "iPad2,7") { return Hardware.IPAD_MINI_WIFI_CDMA } if (hardware == "iPad3,1") { return Hardware.IPAD_3_WIFI } if (hardware == "iPad3,2") { return Hardware.IPAD_3_WIFI_CDMA } if (hardware == "iPad3,3") { return Hardware.IPAD_3 } if (hardware == "iPad3,4") { return Hardware.IPAD_4_WIFI } if (hardware == "iPad3,5") { return Hardware.IPAD_4 } if (hardware == "iPad3,6") { return Hardware.IPAD_4_GSM_CDMA } if (hardware == "iPad4,1") { return Hardware.IPAD_AIR_WIFI } if (hardware == "iPad4,2") { return Hardware.IPAD_AIR_WIFI_GSM } if (hardware == "iPad4,3") { return Hardware.IPAD_AIR_WIFI_CDMA } if (hardware == "iPad4,4") { return Hardware.IPAD_MINI_RETINA_WIFI } if (hardware == "iPad4,5") { return Hardware.IPAD_MINI_RETINA_WIFI_CDMA } if (hardware == "iPad4,6") { return Hardware.IPAD_MINI_RETINA_WIFI_CELLULAR_CN } if (hardware == "iPad4,7") { return Hardware.IPAD_MINI_3_WIFI } if (hardware == "iPad4,8") { return Hardware.IPAD_MINI_3_WIFI_CELLULAR } if (hardware == "iPad5,3") { return Hardware.IPAD_AIR_2_WIFI } if (hardware == "iPad5,4") { return Hardware.IPAD_AIR_2_WIFI_CELLULAR } if (hardware == "i386") { return Hardware.SIMULATOR } if (hardware == "x86_64") { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPhone")) { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPod")) { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPad")) { return Hardware.SIMULATOR } //log message that your device is not present in the list logMessage(hardware) return Hardware.NOT_AVAILABLE } /// This method returns the readable description of hardware string /// /// - returns: readable description `String` of the device /// public func hardwareDescription() -> String? { let hardware = hardwareString() if (hardware == "iPhone1,1") { return "iPhone 2G" } if (hardware == "iPhone1,2") { return "iPhone 3G" } if (hardware == "iPhone2,1") { return "iPhone 3GS" } if (hardware == "iPhone3,1") { return "iPhone 4 (GSM)" } if (hardware == "iPhone3,2") { return "iPhone 4 (GSM Rev. A)" } if (hardware == "iPhone3,3") { return "iPhone 4 (CDMA)" } if (hardware == "iPhone4,1") { return "iPhone 4S" } if (hardware == "iPhone5,1") { return "iPhone 5 (GSM)" } if (hardware == "iPhone5,2") { return "iPhone 5 (Global)" } if (hardware == "iPhone5,3") { return "iPhone 5c (GSM)" } if (hardware == "iPhone5,4") { return "iPhone 5c (Global)" } if (hardware == "iPhone6,1") { return "iPhone 5s (GSM)" } if (hardware == "iPhone6,2") { return "iPhone 5s (Global)" } if (hardware == "iPhone7,1") { return "iPhone 6 Plus" } if (hardware == "iPhone7,2") { return "iPhone 6" } if (hardware == "iPhone8,2") { return "iPhone 6s Plus" } if (hardware == "iPhone8,1") { return "iPhone 6s" } if (hardware == "iPod1,1") { return "iPod Touch (1 Gen)" } if (hardware == "iPod2,1") { return "iPod Touch (2 Gen)" } if (hardware == "iPod3,1") { return "iPod Touch (3 Gen)" } if (hardware == "iPod4,1") { return "iPod Touch (4 Gen)" } if (hardware == "iPod5,1") { return "iPod Touch (5 Gen)" } if (hardware == "iPad1,1") { return "iPad (WiFi)" } if (hardware == "iPad1,2") { return "iPad 3G" } if (hardware == "iPad2,1") { return "iPad 2 (WiFi)" } if (hardware == "iPad2,2") { return "iPad 2 (GSM)" } if (hardware == "iPad2,3") { return "iPad 2 (CDMA)" } if (hardware == "iPad2,4") { return "iPad 2 (WiFi Rev. A)" } if (hardware == "iPad2,5") { return "iPad Mini (WiFi)" } if (hardware == "iPad2,6") { return "iPad Mini (GSM)" } if (hardware == "iPad2,7") { return "iPad Mini (CDMA)" } if (hardware == "iPad3,1") { return "iPad 3 (WiFi)" } if (hardware == "iPad3,2") { return "iPad 3 (CDMA)" } if (hardware == "iPad3,3") { return "iPad 3 (Global)" } if (hardware == "iPad3,4") { return "iPad 4 (WiFi)" } if (hardware == "iPad3,5") { return "iPad 4 (CDMA)" } if (hardware == "iPad3,6") { return "iPad 4 (Global)" } if (hardware == "iPad4,1") { return "iPad Air (WiFi)" } if (hardware == "iPad4,2") { return "iPad Air (WiFi+GSM)" } if (hardware == "iPad4,3") { return "iPad Air (WiFi+CDMA)" } if (hardware == "iPad4,4") { return "iPad Mini Retina (WiFi)" } if (hardware == "iPad4,5") { return "iPad Mini Retina (WiFi+CDMA)" } if (hardware == "iPad4,6") { return "iPad Mini Retina (Wi-Fi + Cellular CN)" } if (hardware == "iPad4,7") { return "iPad Mini 3 (Wi-Fi)" } if (hardware == "iPad4,8") { return "iPad Mini 3 (Wi-Fi + Cellular)" } if (hardware == "iPad5,3") { return "iPad Air 2 (Wi-Fi)" } if (hardware == "iPad5,4") { return "iPad Air 2 (Wi-Fi + Cellular)" } if (hardware == "i386") { return "Simulator" } if (hardware == "x86_64") { return "Simulator" } if (hardware.hasPrefix("iPhone")) { return "iPhone" } if (hardware.hasPrefix("iPod")) { return "iPod" } if (hardware.hasPrefix("iPad")) { return "iPad" } //log message that your device is not present in the list logMessage(hardware) return nil } /// /// This method returns the hardware number not actual but logically. /// e.g. if the hardware string is 5,1 then hardware number would be 5.1 /// public func hardwareNumber(hardware: Hardware) -> CGFloat { switch (hardware) { case Hardware.IPHONE_2G: return 1.1 case Hardware.IPHONE_3G: return 1.2 case Hardware.IPHONE_3GS: return 2.1 case Hardware.IPHONE_4: return 3.1 case Hardware.IPHONE_4_CDMA: return 3.3 case Hardware.IPHONE_4S: return 4.1 case Hardware.IPHONE_5: return 5.1 case Hardware.IPHONE_5_CDMA_GSM: return 5.2 case Hardware.IPHONE_5C: return 5.3 case Hardware.IPHONE_5C_CDMA_GSM: return 5.4 case Hardware.IPHONE_5S: return 6.1 case Hardware.IPHONE_5S_CDMA_GSM: return 6.2 case Hardware.IPHONE_6_PLUS: return 7.1 case Hardware.IPHONE_6: return 7.2 case Hardware.IPHONE_6S_PLUS: return 8.2 case Hardware.IPHONE_6S: return 8.1 case Hardware.IPOD_TOUCH_1G: return 1.1 case Hardware.IPOD_TOUCH_2G: return 2.1 case Hardware.IPOD_TOUCH_3G: return 3.1 case Hardware.IPOD_TOUCH_4G: return 4.1 case Hardware.IPOD_TOUCH_5G: return 5.1 case Hardware.IPAD: return 1.1 case Hardware.IPAD_3G: return 1.2 case Hardware.IPAD_2_WIFI: return 2.1 case Hardware.IPAD_2: return 2.2 case Hardware.IPAD_2_CDMA: return 2.3 case Hardware.IPAD_MINI_WIFI: return 2.5 case Hardware.IPAD_MINI: return 2.6 case Hardware.IPAD_MINI_WIFI_CDMA: return 2.7 case Hardware.IPAD_3_WIFI: return 3.1 case Hardware.IPAD_3_WIFI_CDMA: return 3.2 case Hardware.IPAD_3: return 3.3 case Hardware.IPAD_4_WIFI: return 3.4 case Hardware.IPAD_4: return 3.5 case Hardware.IPAD_4_GSM_CDMA: return 3.6 case Hardware.IPAD_AIR_WIFI: return 4.1 case Hardware.IPAD_AIR_WIFI_GSM: return 4.2 case Hardware.IPAD_AIR_WIFI_CDMA: return 4.3 case Hardware.IPAD_AIR_2_WIFI: return 5.3 case Hardware.IPAD_AIR_2_WIFI_CELLULAR: return 5.4 case Hardware.IPAD_MINI_RETINA_WIFI: return 4.4 case Hardware.IPAD_MINI_RETINA_WIFI_CDMA: return 4.5 case Hardware.IPAD_MINI_3_WIFI: return 4.6 case Hardware.IPAD_MINI_3_WIFI_CELLULAR: return 4.7 case Hardware.IPAD_MINI_RETINA_WIFI_CELLULAR_CN: return 4.8 case Hardware.SIMULATOR: return 100.0 case Hardware.NOT_AVAILABLE: return 200.0 } } /// This method returns the resolution for still image that can be received /// from back camera of the current device. Resolution returned for image oriented landscape right. /// /// - parameters: /// - hardware: `Hardware` type of the device /// /// - returns: `CGSize` of the image captured by the device /// public func backCameraStillImageResolutionInPixels(hardware: Hardware) -> CGSize { switch (hardware) { case Hardware.IPHONE_2G, Hardware.IPHONE_3G: return CGSizeMake(1600, 1200) case Hardware.IPHONE_3GS: return CGSizeMake(2048, 1536) case Hardware.IPHONE_4, Hardware.IPHONE_4_CDMA, Hardware.IPAD_3_WIFI, Hardware.IPAD_3_WIFI_CDMA, Hardware.IPAD_3, Hardware.IPAD_4_WIFI, Hardware.IPAD_4, Hardware.IPAD_4_GSM_CDMA: return CGSizeMake(2592, 1936) case Hardware.IPHONE_4S, Hardware.IPHONE_5, Hardware.IPHONE_5_CDMA_GSM, Hardware.IPHONE_5C, Hardware.IPHONE_5C_CDMA_GSM, Hardware.IPHONE_6, Hardware.IPHONE_6_PLUS: return CGSizeMake(3264, 2448) case Hardware.IPOD_TOUCH_4G: return CGSizeMake(960, 720) case Hardware.IPOD_TOUCH_5G: return CGSizeMake(2440, 1605) case Hardware.IPAD_2_WIFI, Hardware.IPAD_2, Hardware.IPAD_2_CDMA: return CGSizeMake(872, 720) case Hardware.IPAD_MINI_WIFI, Hardware.IPAD_MINI, Hardware.IPAD_MINI_WIFI_CDMA: return CGSizeMake(1820, 1304) case Hardware.IPAD_AIR_2_WIFI, Hardware.IPAD_AIR_2_WIFI_CELLULAR: return CGSizeMake (1536, 2048) default: print("We have no resolution for your device's camera listed in this category. Please, make photo with back camera of your device, get its resolution in pixels (via Preview Cmd+I for example) and add a comment to this repository (https://github.com/InderKumarRathore/UIDeviceUtil) on GitHub.com in format Device = Hpx x Wpx.") } print("Your device is: \(hardwareDescription())") return CGSizeZero } /// Internal method for loggin, you don't need this method /// /// - parameters: /// - hardware: `String` hardware type of the device /// private func logMessage(hardware: String) { print("This is a device which is not listed in this category. Please visit https://github.com/InderKumarRathore/UIDeviceUtil and add a comment there."); print("Your device hardware string is: %@", hardware); }
c5a57872320d50bcb770ab31a6482ef5
44.561254
336
0.556028
false
false
false
false
frootloops/swift
refs/heads/master
test/Generics/requirement_inference.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck %s -verify // RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump protocol P1 { func p1() } protocol P2 : P1 { } struct X1<T : P1> { func getT() -> T { } } class X2<T : P1> { func getT() -> T { } } class X3 { } struct X4<T : X3> { func getT() -> T { } } struct X5<T : P2> { } // Infer protocol requirements from the parameter type of a generic function. func inferFromParameterType<T>(_ x: X1<T>) { x.getT().p1() } // Infer protocol requirements from the return type of a generic function. func inferFromReturnType<T>(_ x: T) -> X1<T> { x.p1() } // Infer protocol requirements from the superclass of a generic parameter. func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T { t.p1() } // Infer protocol requirements from the parameter type of a constructor. struct InferFromConstructor { init<T> (x : X1<T>) { x.getT().p1() } } // Don't infer requirements for outer generic parameters. class Fox : P1 { func p1() {} } class Box<T : Fox, U> { func unpack(_ x: X1<T>) {} func unpackFail(_ X: X1<U>) { } // expected-error{{type 'U' does not conform to protocol 'P1'}} } // ---------------------------------------------------------------------------- // Superclass requirements // ---------------------------------------------------------------------------- // Compute meet of two superclass requirements correctly. class Carnivora {} class Canidae : Carnivora {} struct U<T : Carnivora> {} struct V<T : Canidae> {} // CHECK-LABEL: .inferSuperclassRequirement1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement1<T : Carnivora>( _ v: V<T>) {} // CHECK-LABEL: .inferSuperclassRequirement2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {} // ---------------------------------------------------------------------------- // Same-type requirements // ---------------------------------------------------------------------------- protocol P3 { associatedtype P3Assoc : P2 // expected-note{{declared here}} } protocol P4 { associatedtype P4Assoc : P1 } protocol PCommonAssoc1 { associatedtype CommonAssoc } protocol PCommonAssoc2 { associatedtype CommonAssoc } protocol PAssoc { associatedtype Assoc } struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {} func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) { let u: U.P4Assoc? = nil let _: T.P3Assoc? = u! } func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {} // expected-warning@-1{{redundant conformance constraint 'T.P3Assoc': 'P2'}} // expected-note@-2{{conformance constraint 'T.P3Assoc': 'P2' implied here}} func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 { } protocol P5 { associatedtype Element } protocol P6 { associatedtype AssocP6 : P5 } protocol P7 : P6 { associatedtype AssocP7: P6 } // CHECK-LABEL: P7@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.AssocP6.Element : P6, τ_0_0.AssocP6.Element == τ_0_0.AssocP7.AssocP6.Element> extension P7 where AssocP6.Element : P6, // expected-note{{conformance constraint 'Self.AssocP6.Element': 'P6' written here}} AssocP7.AssocP6.Element : P6, // expected-warning{{redundant conformance constraint 'Self.AssocP6.Element': 'P6'}} AssocP6.Element == AssocP7.AssocP6.Element { func nestedSameType1() { } } protocol P8 { associatedtype A associatedtype B } protocol P9 : P8 { associatedtype A associatedtype B } protocol P10 { associatedtype A associatedtype C } // CHECK-LABEL: sameTypeConcrete1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.A == X3, τ_0_0.A == X3, τ_0_0.B == Int, τ_0_0.C == Int> func sameTypeConcrete1<T : P9 & P10>(_: T) where T.A == X3, T.C == T.B, T.C == Int { } // CHECK-LABEL: sameTypeConcrete2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.B == X3, τ_0_0.C == X3> // FIXME: Should have τ_0_0.A == τ_0_0.A func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { } // expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}} // expected-note@-2{{same-type constraint 'T.C' == 'X3' written here}} // Note: a standard-library-based stress test to make sure we don't inject // any additional requirements. // CHECK-LABEL: RangeReplaceableCollection // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : MutableCollection, τ_0_0 : RangeReplaceableCollection, τ_0_0.SubSequence == Slice<τ_0_0>> extension RangeReplaceableCollection where Self: MutableCollection, Self.SubSequence == Slice<Self> { func f() { } } // CHECK-LABEL: X14.recursiveConcreteSameType // CHECK: Generic signature: <T, V where T == CountableRange<Int>> // CHECK-NEXT: Canonical generic signature: <τ_0_0, τ_1_0 where τ_0_0 == CountableRange<Int>> struct X14<T> where T.Iterator == IndexingIterator<T> { func recursiveConcreteSameType<V>(_: V) where T == CountableRange<Int> { } } // rdar://problem/30478915 protocol P11 { associatedtype A } protocol P12 { associatedtype B: P11 } struct X6 { } struct X7 : P11 { typealias A = X6 } struct X8 : P12 { typealias B = X7 } struct X9<T: P12, U: P12> where T.B == U.B { // CHECK-LABEL: X9.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T == X8, U : P12, U.B == X8.B> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 == X8, τ_0_1 : P12, τ_0_1.B == X7> func upperSameTypeConstraint<V>(_: V) where T == X8 { } } protocol P13 { associatedtype C: P11 } struct X10: P11, P12 { typealias A = X10 typealias B = X10 } struct X11<T: P12, U: P12> where T.B == U.B.A { // CHECK-LABEL: X11.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T : P12, U == X10, T.B == X10.A> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P12, τ_0_1 == X10, τ_0_0.B == X10> func upperSameTypeConstraint<V>(_: V) where U == X10 { } } #if _runtime(_ObjC) // rdar://problem/30610428 @objc protocol P14 { } class X12<S: AnyObject> { func bar<V>(v: V) where S == P14 { } } @objc protocol P15: P14 { } class X13<S: P14> { func bar<V>(v: V) where S == P15 { } } #endif protocol P16 { associatedtype A } struct X15 { } struct X16<X, Y> : P16 { typealias A = (X, Y) } // CHECK-LABEL: .X17.bar@ // CHECK: Generic signature: <S, T, U, V where S == X16<X3, X15>, T == X3, U == X15> struct X17<S: P16, T, U> where S.A == (T, U) { func bar<V>(_: V) where S == X16<X3, X15> { } } // Same-type constraints that are self-derived via a parent need to be // suppressed in the resulting signature. protocol P17 { } protocol P18 { associatedtype A: P17 } struct X18: P18, P17 { typealias A = X18 } // CHECK-LABEL: .X19.foo@ // CHECK: Generic signature: <T, U where T == X18> struct X19<T: P18> where T == T.A { func foo<U>(_: U) where T == X18 { } } // rdar://problem/31520386 protocol P20 { } struct X20<T: P20> { } // CHECK-LABEL: .X21.f@ // CHECK: Generic signature: <T, U, V where T : P20, U == X20<T>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P20, τ_0_1 == X20<τ_0_0>> struct X21<T, U> { func f<V>(_: V) where U == X20<T> { } } struct X22<T, U> { func g<V>(_: V) where T: P20, U == X20<T> { } } // CHECK: Generic signature: <Self where Self : P22> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P22> // CHECK: Protocol requirement signature: // CHECK: .P22@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20> protocol P22 { associatedtype A associatedtype B: P20 where A == X20<B> } // CHECK: Generic signature: <Self where Self : P23> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P23> // CHECK: Protocol requirement signature: // CHECK: .P23@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20> protocol P23 { associatedtype A associatedtype B: P20 where A == X20<B> } protocol P24 { associatedtype C: P20 } struct X24<T: P20> : P24 { typealias C = T } // CHECK-LABEL: .P25a@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20> protocol P25a { associatedtype A: P24 // expected-warning{{redundant conformance constraint 'Self.A': 'P24'}} associatedtype B: P20 where A == X24<B> // expected-note{{conformance constraint 'Self.A': 'P24' implied here}} } // CHECK-LABEL: .P25b@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20> protocol P25b { associatedtype A associatedtype B: P20 where A == X24<B> } protocol P25c { associatedtype A: P24 associatedtype B where A == X<B> // expected-error{{use of undeclared type 'X'}} } protocol P25d { associatedtype A associatedtype B where A == X24<B> // expected-error{{type 'Self.B' does not conform to protocol 'P20'}} } // Similar to the above, but with superclass constraints. protocol P26 { associatedtype C: X3 } struct X26<T: X3> : P26 { typealias C = T } // CHECK-LABEL: .P27a@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3> protocol P27a { associatedtype A: P26 // expected-warning{{redundant conformance constraint 'Self.A': 'P26'}} associatedtype B: X3 where A == X26<B> // expected-note{{conformance constraint 'Self.A': 'P26' implied here}} } // CHECK-LABEL: .P27b@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3> protocol P27b { associatedtype A associatedtype B: X3 where A == X26<B> } // ---------------------------------------------------------------------------- // Inference of associated type relationships within a protocol hierarchy // ---------------------------------------------------------------------------- struct X28 : P2 { func p1() { } } // CHECK-LABEL: .P28@ // CHECK-NEXT: Requirement signature: <Self where Self : P3, Self.P3Assoc == X28> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : P3, τ_0_0.P3Assoc == X28> protocol P28: P3 { typealias P3Assoc = X28 // expected-warning{{typealias overriding associated type}} } // ---------------------------------------------------------------------------- // Inference of associated types by name match // ---------------------------------------------------------------------------- protocol P29 { associatedtype X } protocol P30 { associatedtype X } protocol P31 { } // CHECK-LABEL: .sameTypeNameMatch1@ // CHECK: Generic signature: <T where T : P29, T : P30, T.X : P31, T.X == T.X> func sameTypeNameMatch1<T: P29 & P30>(_: T) where T.X: P31 { } // ---------------------------------------------------------------------------- // Infer requirements from conditional conformances // ---------------------------------------------------------------------------- protocol P32 {} protocol P33 { associatedtype A: P32 } protocol P34 {} struct Foo<T> {} extension Foo: P32 where T: P34 {} // Inference chain: U.A: P32 => Foo<V>: P32 => V: P34 // CHECK-LABEL: conditionalConformance1@ // CHECK: Generic signature: <U, V where U : P33, V : P34, U.A == Foo<V>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1 where τ_0_0 : P33, τ_0_1 : P34, τ_0_0.A == Foo<τ_0_1>> func conditionalConformance1<U: P33, V>(_: U) where U.A == Foo<V> {} struct Bar<U: P32> {} // CHECK-LABEL: conditionalConformance2@ // CHECK: Generic signature: <V where V : P34> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P34> func conditionalConformance2<V>(_: Bar<Foo<V>>) {}
07a258a385ea461b954fd36f3ffb2d23
27.832947
149
0.615676
false
false
false
false