repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
brentsimmons/Evergreen
Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift
1
5869
// // OAuthAccountAuthorizationOperation.swift // NetNewsWire // // Created by Kiel Gillard on 8/11/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import Foundation import AuthenticationServices import RSCore public protocol OAuthAccountAuthorizationOperationDelegate: AnyObject { func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) } public enum OAuthAccountAuthorizationOperationError: LocalizedError { case duplicateAccount public var errorDescription: String? { return NSLocalizedString("There is already a Feedly account with that username created.", comment: "Duplicate Error") } } @objc public final class OAuthAccountAuthorizationOperation: NSObject, MainThreadOperation, ASWebAuthenticationPresentationContextProviding { public var isCanceled: Bool = false { didSet { if isCanceled { cancel() } } } public var id: Int? public weak var operationDelegate: MainThreadOperationDelegate? public var name: String? public var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock? public weak var presentationAnchor: ASPresentationAnchor? public weak var delegate: OAuthAccountAuthorizationOperationDelegate? private let accountType: AccountType private let oauthClient: OAuthAuthorizationClient private var session: ASWebAuthenticationSession? public init(accountType: AccountType) { self.accountType = accountType self.oauthClient = Account.oauthAuthorizationClient(for: accountType) } public func run() { assert(presentationAnchor != nil, "\(self) outlived presentation anchor.") let request = Account.oauthAuthorizationCodeGrantRequest(for: accountType) guard let url = request.url else { return DispatchQueue.main.async { self.didEndAuthentication(url: nil, error: URLError(.badURL)) } } guard let redirectUri = URL(string: oauthClient.redirectUri), let scheme = redirectUri.scheme else { assertionFailure("Could not get callback URL scheme from \(oauthClient.redirectUri)") return DispatchQueue.main.async { self.didEndAuthentication(url: nil, error: URLError(.badURL)) } } let session = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme) { url, error in DispatchQueue.main.async { [weak self] in self?.didEndAuthentication(url: url, error: error) } } session.presentationContextProvider = self guard session.start() else { /// Documentation does not say on why `ASWebAuthenticationSession.start` or `canStart` might return false. /// Perhaps it has something to do with an inter-process communication failure? No browsers installed? No browsers that support web authentication? struct UnableToStartASWebAuthenticationSessionError: LocalizedError { let errorDescription: String? = NSLocalizedString("Unable to start a web authentication session with the default web browser.", comment: "OAuth - error description - unable to authorize because ASWebAuthenticationSession did not start.") let recoverySuggestion: String? = NSLocalizedString("Check your default web browser in System Preferences or change it to Safari and try again.", comment: "OAuth - recovery suggestion - ensure browser selected supports web authentication.") } didFinish(UnableToStartASWebAuthenticationSessionError()) return } self.session = session } public func cancel() { session?.cancel() } private func didEndAuthentication(url: URL?, error: Error?) { guard !isCanceled else { didFinish() return } do { guard let url = url else { if let error = error { throw error } throw URLError(.badURL) } let response = try OAuthAuthorizationResponse(url: url, client: oauthClient) Account.requestOAuthAccessToken(with: response, client: oauthClient, accountType: accountType, completion: didEndRequestingAccessToken(_:)) } catch is ASWebAuthenticationSessionError { didFinish() // Primarily, cancellation. } catch { didFinish(error) } } public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { guard let anchor = presentationAnchor else { fatalError("\(self) has outlived presentation anchor.") } return anchor } private func didEndRequestingAccessToken(_ result: Result<OAuthAuthorizationGrant, Error>) { guard !isCanceled else { didFinish() return } switch result { case .success(let tokenResponse): saveAccount(for: tokenResponse) case .failure(let error): didFinish(error) } } private func saveAccount(for grant: OAuthAuthorizationGrant) { guard !AccountManager.shared.duplicateServiceAccount(type: .feedly, username: grant.accessToken.username) else { didFinish(OAuthAccountAuthorizationOperationError.duplicateAccount) return } let account = AccountManager.shared.createAccount(type: .feedly) do { // Store the refresh token first because it sends this token to the account delegate. if let token = grant.refreshToken { try account.storeCredentials(token) } // Now store the access token because we want the account delegate to use it. try account.storeCredentials(grant.accessToken) delegate?.oauthAccountAuthorizationOperation(self, didCreate: account) didFinish() } catch { didFinish(error) } } // MARK: Managing Operation State private func didFinish() { assert(Thread.isMainThread) operationDelegate?.operationDidComplete(self) } private func didFinish(_ error: Error) { assert(Thread.isMainThread) delegate?.oauthAccountAuthorizationOperation(self, didFailWith: error) didFinish() } }
mit
0d8d6635b45a379753e0041097bc97b3
30.891304
150
0.752386
4.445455
false
false
false
false
zcLu/DanTangSwift
DanTangSwift/DanTangSwift/Classes/Me/View/MeFooterView.swift
1
1676
// // MeFooterView.swift // DanTangSwift // // Created by LuzhiChao on 2017/4/26. // Copyright © 2017年 LuzhiChao. All rights reserved. // import UIKit import SnapKit class MeFooterView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { addSubview(likeBtn) addSubview(messageLab) likeBtn.snp.makeConstraints { (make) in make.center.equalTo(self.center) make.width.height.equalTo(50) } messageLab.snp.makeConstraints { (make) in make.left.right.equalTo(self) make.top.equalTo(likeBtn.snp.bottom).offset(10) } } private lazy var likeBtn: UIButton = { let likeBtn = UIButton() likeBtn.setImage(UIImage(named: "Me_blank_50x50_"), for: .normal) likeBtn.addTarget(self, action: #selector(login), for: .touchUpInside) return likeBtn }() private lazy var messageLab: UILabel = { let messageLab = UILabel() messageLab.text = "登录以享受功能" messageLab.textAlignment = .center messageLab.textColor = UIColor.colorWith(200, green: 200, blue: 200, alpha: 1) messageLab.font = UIFont.systemFont(ofSize: 15) return messageLab }() func login() { let nav = DTNavigationController(rootViewController: LoginController()) UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil) } }
mit
55c7158338e68175261084b5256ed59f
27.603448
105
0.617842
4.106436
false
false
false
false
Witcast/witcast-ios
Pods/Material/Sources/iOS/CollectionView.swift
1
4888
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class CollectionView: UICollectionView { /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsetsPreset } set(value) { (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsetsPreset = value } } open var contentEdgeInsets: EdgeInsets { get { return (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsets } set(value) { (collectionViewLayout as? CollectionViewLayout)!.contentEdgeInsets = value } } /// Scroll direction. open var scrollDirection: UICollectionViewScrollDirection { get { return (collectionViewLayout as? CollectionViewLayout)!.scrollDirection } set(value) { (collectionViewLayout as? CollectionViewLayout)!.scrollDirection = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset: InterimSpacePreset { get { return (collectionViewLayout as? CollectionViewLayout)!.interimSpacePreset } set(value) { (collectionViewLayout as? CollectionViewLayout)!.interimSpacePreset = value } } /// Spacing between items. @IBInspectable open var interimSpace: InterimSpace { get { return (collectionViewLayout as? CollectionViewLayout)!.interimSpace } set(value) { (collectionViewLayout as? CollectionViewLayout)!.interimSpace = value } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object. - Parameter frame: A CGRect defining the view's frame. - Parameter collectionViewLayout: A UICollectionViewLayout reference. */ public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) prepare() } /** An initializer that initializes the object. - Parameter collectionViewLayout: A UICollectionViewLayout reference. */ public init(collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: .zero, collectionViewLayout: layout) prepare() } /** An initializer that initializes the object. - Parameter frame: A CGRect defining the view's frame. */ public init(frame: CGRect) { super.init(frame: frame, collectionViewLayout: CollectionViewLayout()) prepare() } /// A convenience initializer that initializes the object. public init() { super.init(frame: .zero, collectionViewLayout: CollectionViewLayout()) prepare() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { backgroundColor = .white contentScaleFactor = Screen.scale register(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell") } }
apache-2.0
04325d990c2dc6e1c0d83be88e549dc9
34.165468
91
0.731792
4.922457
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0958-swift-nominaltypedecl-getdeclaredtypeincontext.swift
10
607
// RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func q<dc>() -> (dc, dc -> dc) -> dc { t m t.w = { } { dc) { k } } protocol q { } protocol A { func b(b: X.s) { } y(m: x) { } func v<t>() -> [dc<t>] { } class b<k : dc, w : dc where k.dc == w> : v { } class b<k, w> { } protocol dc { } class A: A { } class r : C { } func ^(v: q, o) -> o { } class v<q : b, dc : b where q.t == dc> { } protocol b { } struct dc<k : b> : b
apache-2.0
9e1b7659719bc8d13a24ee8fc06c8e06
14.175
87
0.558484
2.418327
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/DSUserInfoViewController.swift
1
3054
// // DSUserInfoViewController.swift // hackathon-for-hunger // // Created by ivan lares on 4/4/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit class DSUserInfoViewController: UIViewController { var donorSignupInfo: DonorSignupInfo! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var companyTextField: UITextField! @IBOutlet weak var adressTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var nextButton: UIButton! override func viewDidLoad() { donorSignupInfo = DonorSignupInfo() delegateRegistration() updateTextFieldsPlaceHolder(UIColor.whiteColor()) } override func viewWillAppear(animated: Bool) { } // MARK: Actions @IBAction func didPressNext(sender: UIButton) { if shouldTransition(){ updateInfoStruct() performSegueWithIdentifier("DonorAccountInfo", sender: nil) } else { print("\nempty textFields\n") updateTextFieldsPlaceHolder(UIColor.redColor()) // Shake effect or alert ? } } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "DonorAccountInfo"{ let accountInfoViewController = segue.destinationViewController as! DSAccountInfoViewController accountInfoViewController.donorSignupInfo = donorSignupInfo } } // MARK: Helper func shouldTransition() ->Bool { guard let name = nameTextField.text, company = companyTextField.text, adress = adressTextField.text, phone = phoneTextField.text else { return false } if name.isBlank { return false } if company.isBlank { return false } if adress.isBlank { return false } if phone.isBlank { return false } return true } func delegateRegistration() { nameTextField.delegate = self companyTextField.delegate = self adressTextField.delegate = self phoneTextField.delegate = self } func updateInfoStruct() { donorSignupInfo.name = nameTextField.text donorSignupInfo.company = companyTextField.text donorSignupInfo.adress = adressTextField.text donorSignupInfo.phone = phoneTextField.text } // MARK: UI func updateTextFieldsPlaceHolder(color: UIColor){ let textFields = [nameTextField, companyTextField, adressTextField, phoneTextField] for textField in textFields{ textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: color]) } } } extension DSUserInfoViewController: UITextFieldDelegate{ func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
mit
dfcc3d55d3aef0ca83a8aa61598e32f5
29.54
149
0.654438
5.38448
false
false
false
false
muenzpraeger/salesforce-einstein-vision-swift
SalesforceEinsteinVision/Classes/http/parts/MultiPartExample.swift
1
1445
// // MultiPartExample.swift // Pods // // Created by René Winkelmeyer on 02/28/2017. // // import Alamofire import Foundation public struct MultiPartExample : MultiPart { private let MAX_NAME = 180 private var _name:String? private var _labelId:Int? private var _file:URL? public init() {} public mutating func build(name: String, labelId: Int, file: URL) throws { if name.isEmpty { throw ModelError.noFieldValue(field: "name") } if (name.characters.count>MAX_NAME) { throw ModelError.stringTooLong(field: "name", maxValue: MAX_NAME, currentValue: name.characters.count) } if (labelId<0) { throw ModelError.intTooSmall(field: "labelId", minValue: 0, currentValue: labelId) } if file.absoluteString.isEmpty { throw ModelError.noFieldValue(field: "file") } _name = name _labelId = labelId _file = file } public func form(multipart: MultipartFormData) { let nameData = _name?.data(using: String.Encoding.utf8) multipart.append(nameData!, withName: "name") let labelIdData = String(describing: _labelId).data(using: String.Encoding.utf8) multipart.append(labelIdData!, withName: "labelId") multipart.append(_file!, withName: "data") } }
apache-2.0
82c59945d9b3c581c570d085398281bf
25.254545
114
0.590028
4.102273
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift
3
9352
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf // http://keccak.noekeon.org/specs_summary.html // #if canImport(Darwin) import Darwin #else import Glibc #endif public final class SHA3: DigestType { let round_constants: Array<UInt64> = [ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008 ] public let blockSize: Int public let digestLength: Int public let markByte: UInt8 fileprivate var accumulated = Array<UInt8>() fileprivate var accumulatedHash: Array<UInt64> public enum Variant { case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512 var digestLength: Int { 100 - (self.blockSize / 2) } var blockSize: Int { (1600 - self.outputLength * 2) / 8 } var markByte: UInt8 { switch self { case .sha224, .sha256, .sha384, .sha512: return 0x06 // 0x1F for SHAKE case .keccak224, .keccak256, .keccak384, .keccak512: return 0x01 } } public var outputLength: Int { switch self { case .sha224, .keccak224: return 224 case .sha256, .keccak256: return 256 case .sha384, .keccak384: return 384 case .sha512, .keccak512: return 512 } } } public init(variant: SHA3.Variant) { self.blockSize = variant.blockSize self.digestLength = variant.digestLength self.markByte = variant.markByte self.accumulatedHash = Array<UInt64>(repeating: 0, count: self.digestLength) } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let /// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z]. /// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let /// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w]. /// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ D[x,z]. private func θ(_ a: inout Array<UInt64>) { let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) c.initialize(repeating: 0, count: 5) defer { c.deinitialize(count: 5) c.deallocate() } let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5) d.initialize(repeating: 0, count: 5) defer { d.deinitialize(count: 5) d.deallocate() } for i in 0..<5 { c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] } d[0] = rotateLeft(c[1], by: 1) ^ c[4] d[1] = rotateLeft(c[2], by: 1) ^ c[0] d[2] = rotateLeft(c[3], by: 1) ^ c[1] d[3] = rotateLeft(c[4], by: 1) ^ c[2] d[4] = rotateLeft(c[0], by: 1) ^ c[3] for i in 0..<5 { a[i] ^= d[i] a[i &+ 5] ^= d[i] a[i &+ 10] ^= d[i] a[i &+ 15] ^= d[i] a[i &+ 20] ^= d[i] } } /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] private func π(_ a: inout Array<UInt64>) { let a1 = a[1] a[1] = a[6] a[6] = a[9] a[9] = a[22] a[22] = a[14] a[14] = a[20] a[20] = a[2] a[2] = a[12] a[12] = a[13] a[13] = a[19] a[19] = a[23] a[23] = a[15] a[15] = a[4] a[4] = a[24] a[24] = a[21] a[21] = a[8] a[8] = a[16] a[16] = a[5] a[5] = a[3] a[3] = a[18] a[18] = a[17] a[17] = a[11] a[11] = a[7] a[7] = a[10] a[10] = a1 } /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let /// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z]) private func χ(_ a: inout Array<UInt64>) { for i in stride(from: 0, to: 25, by: 5) { let a0 = a[0 &+ i] let a1 = a[1 &+ i] a[0 &+ i] ^= ~a1 & a[2 &+ i] a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] a[3 &+ i] ^= ~a[4 &+ i] & a0 a[4 &+ i] ^= ~a0 & a1 } } private func ι(_ a: inout Array<UInt64>, round: Int) { a[0] ^= self.round_constants[round] } fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) { // expand hh[0] ^= chunk[0].littleEndian hh[1] ^= chunk[1].littleEndian hh[2] ^= chunk[2].littleEndian hh[3] ^= chunk[3].littleEndian hh[4] ^= chunk[4].littleEndian hh[5] ^= chunk[5].littleEndian hh[6] ^= chunk[6].littleEndian hh[7] ^= chunk[7].littleEndian hh[8] ^= chunk[8].littleEndian if self.blockSize > 72 { // 72 / 8, sha-512 hh[9] ^= chunk[9].littleEndian hh[10] ^= chunk[10].littleEndian hh[11] ^= chunk[11].littleEndian hh[12] ^= chunk[12].littleEndian if self.blockSize > 104 { // 104 / 8, sha-384 hh[13] ^= chunk[13].littleEndian hh[14] ^= chunk[14].littleEndian hh[15] ^= chunk[15].littleEndian hh[16] ^= chunk[16].littleEndian if self.blockSize > 136 { // 136 / 8, sha-256 hh[17] ^= chunk[17].littleEndian // FULL_SHA3_FAMILY_SUPPORT if self.blockSize > 144 { // 144 / 8, sha-224 hh[18] ^= chunk[18].littleEndian hh[19] ^= chunk[19].littleEndian hh[20] ^= chunk[20].littleEndian hh[21] ^= chunk[21].littleEndian hh[22] ^= chunk[22].littleEndian hh[23] ^= chunk[23].littleEndian hh[24] ^= chunk[24].littleEndian } } } } // Keccak-f for round in 0..<24 { self.θ(&hh) hh[1] = rotateLeft(hh[1], by: 1) hh[2] = rotateLeft(hh[2], by: 62) hh[3] = rotateLeft(hh[3], by: 28) hh[4] = rotateLeft(hh[4], by: 27) hh[5] = rotateLeft(hh[5], by: 36) hh[6] = rotateLeft(hh[6], by: 44) hh[7] = rotateLeft(hh[7], by: 6) hh[8] = rotateLeft(hh[8], by: 55) hh[9] = rotateLeft(hh[9], by: 20) hh[10] = rotateLeft(hh[10], by: 3) hh[11] = rotateLeft(hh[11], by: 10) hh[12] = rotateLeft(hh[12], by: 43) hh[13] = rotateLeft(hh[13], by: 25) hh[14] = rotateLeft(hh[14], by: 39) hh[15] = rotateLeft(hh[15], by: 41) hh[16] = rotateLeft(hh[16], by: 45) hh[17] = rotateLeft(hh[17], by: 15) hh[18] = rotateLeft(hh[18], by: 21) hh[19] = rotateLeft(hh[19], by: 8) hh[20] = rotateLeft(hh[20], by: 18) hh[21] = rotateLeft(hh[21], by: 2) hh[22] = rotateLeft(hh[22], by: 61) hh[23] = rotateLeft(hh[23], by: 56) hh[24] = rotateLeft(hh[24], by: 14) self.π(&hh) self.χ(&hh) self.ι(&hh, round: round) } } } extension SHA3: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { self.accumulated += bytes if isLast { // Add padding let markByteIndex = self.accumulated.count // We need to always pad the input. Even if the input is a multiple of blockSize. let r = self.blockSize * 8 let q = (r / 8) - (accumulated.count % (r / 8)) self.accumulated += Array<UInt8>(repeating: 0, count: q) self.accumulated[markByteIndex] |= self.markByte self.accumulated[self.accumulated.count - 1] |= 0x80 } var processedBytes = 0 for chunk in self.accumulated.batched(by: self.blockSize) { if isLast || (self.accumulated.count - processedBytes) >= self.blockSize { self.process(block: chunk.toUInt64Array().slice, currentHash: &self.accumulatedHash) processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) // TODO: verify performance, reduce vs for..in let result = self.accumulatedHash.reduce(into: Array<UInt8>()) { (result, value) in result += value.bigEndian.bytes() } // reset hash value for instance if isLast { self.accumulatedHash = Array<UInt64>(repeating: 0, count: self.digestLength) } return Array(result[0..<self.digestLength]) } }
gpl-3.0
ec7ca706dd93f20577cb75efae79e40e
31.16263
217
0.579344
3.022764
false
false
false
false
hathway/JSONRequest
JSONRequest/JSONRequestVerbs.swift
1
1955
// // JSONRequestVerbs.swift // JSONRequest // // Created by Eneko Alonso on 1/11/16. // Copyright © 2016 Hathway. All rights reserved. // import Foundation public enum JSONRequestHttpVerb: String { case GET case POST case PUT case PATCH case DELETE } // MARK: Instance basic sync/async public extension JSONRequest { func send(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil, payload: Any? = nil, headers: JSONObject? = nil, timeOut: TimeInterval? = nil) -> JSONResult { return submitSyncRequest(method: method, url: url, queryParams: queryParams, payload: payload, headers: headers, timeOut: timeOut) } } // MARK: Instance HTTP Sync methods public extension JSONRequest { func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return send(method: .GET, url: url, queryParams: queryParams, headers: headers) } func post(url: String, queryParams: JSONObject? = nil, payload: Any? = nil, headers: JSONObject? = nil) -> JSONResult { return send(method: .POST, url: url, queryParams: queryParams, payload: payload, headers: headers) } func put(url: String, queryParams: JSONObject? = nil, payload: Any? = nil, headers: JSONObject? = nil) -> JSONResult { return send(method: .PUT, url: url, queryParams: queryParams, payload: payload, headers: headers) } func patch(url: String, queryParams: JSONObject? = nil, payload: Any? = nil, headers: JSONObject? = nil) -> JSONResult { return send(method: .PATCH, url: url, queryParams: queryParams, payload: payload, headers: headers) } func delete(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return send(method: .DELETE, url: url, queryParams: queryParams, headers: headers) } }
mit
a16c80ef5cc198e6f62b8be1849ac5ba
35.185185
182
0.653531
4.139831
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/UICollectionViewCell/AttachmentCollectionViewCell.swift
1
1983
// // AttachmentCollectionViewCell.swift // Inbbbox // // Created by Marcin Siemaszko on 15.11.2016. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation class AttachmentCollectionViewCell: UICollectionViewCell, Reusable { let imageView = UIImageView.newAutoLayout() fileprivate let attachmentIconImageView = UIImageView.newAutoLayout() fileprivate var didUpdateConstraints = false override init(frame: CGRect) { super.init(frame: frame) configureForAutoLayout() contentView.configureForAutoLayout() contentView.backgroundColor = .clear imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true imageView.layer.cornerRadius = 3 contentView.addSubview(imageView) attachmentIconImageView.image = UIImage(named: "ic_attachment") attachmentIconImageView.contentMode = .center attachmentIconImageView.layer.cornerRadius = 9 attachmentIconImageView.backgroundColor = UIColor.RGBA(175, 175, 175, 0.26) contentView.addSubview(attachmentIconImageView) setNeedsUpdateConstraints() } @available(*, unavailable, message: "Use init(frame:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { if !didUpdateConstraints { didUpdateConstraints = true imageView.autoPinEdgesToSuperviewEdges() attachmentIconImageView.autoPinEdge(toSuperviewEdge: .right, withInset: 3) attachmentIconImageView.autoPinEdge(toSuperviewEdge: .top, withInset: 3) attachmentIconImageView.autoSetDimensions(to: CGSize(width: 18, height: 18)) contentView.autoPinEdgesToSuperviewEdges() } super.updateConstraints() } }
gpl-3.0
7d41f962b079aa6d458ecf64a452362f
32.033333
88
0.66448
5.761628
false
false
false
false
jmgc/swift
stdlib/public/core/Sequence.swift
1
42614
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints Optional("Butterfly") /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type representing the sequence's elements. associatedtype Element /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator: IteratorProtocol where Iterator.Element == Element /// A type that represents a subsequence of some of the sequence's elements. // associatedtype SubSequence: Sequence = AnySequence<Element> // where Element == SubSequence.Element, // SubSequence.SubSequence == SubSequence // typealias SubSequence = AnySequence<Element> /// Returns an iterator over the elements of this sequence. __consuming func makeIterator() -> Iterator /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. var underestimatedCount: Int { get } func _customContainsEquatableElement( _ element: Element ) -> Bool? /// Create a native array buffer containing the elements of `self`, /// in the same order. __consuming func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, returning a partially-consumed /// iterator with any elements that didn't fit remaining. __consuming func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) /// Call `body(p)`, where `p` is a pointer to the collection's /// contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of contiguous storage, `body` is not /// called and `nil` is returned. /// /// A `Collection` that provides its own implementation of this method /// must also guarantee that an equivalent buffer of its `SubSequence` /// can be generated by advancing the pointer by the distance to the /// slice's `startIndex`. func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? } // Provides a default associated type witness for Iterator when the // Self type is both a Sequence and an Iterator. extension Sequence where Self: IteratorProtocol { // @_implements(Sequence, Iterator) public typealias _Default_Iterator = Self } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @inlinable public __consuming func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropFirstSequence<Base: Sequence> { @usableFromInline internal let _base: Base @usableFromInline internal let _limit: Int @inlinable public init(_ base: Base, dropping limit: Int) { _precondition(limit >= 0, "Can't drop a negative number of elements from a sequence") _base = base _limit = limit } } extension DropFirstSequence: Sequence { public typealias Element = Base.Element public typealias Iterator = Base.Iterator public typealias SubSequence = AnySequence<Element> @inlinable public __consuming func makeIterator() -> Iterator { var it = _base.makeIterator() var dropped = 0 while dropped < _limit, it.next() != nil { dropped &+= 1 } return it } @inlinable public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return DropFirstSequence(_base, dropping: _limit + k) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @frozen public struct PrefixSequence<Base: Sequence> { @usableFromInline internal var _base: Base @usableFromInline internal let _maxLength: Int @inlinable public init(_ base: Base, maxLength: Int) { _precondition(maxLength >= 0, "Can't take a prefix of negative length") _base = base _maxLength = maxLength } } extension PrefixSequence { @frozen public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal var _remaining: Int @inlinable internal init(_ base: Base.Iterator, maxLength: Int) { _base = base _remaining = maxLength } } } extension PrefixSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { if _remaining != 0 { _remaining &-= 1 return _base.next() } else { return nil } } } extension PrefixSequence: Sequence { @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_base.makeIterator(), maxLength: _maxLength) } @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> { let length = Swift.min(maxLength, self._maxLength) return PrefixSequence(_base, maxLength: length) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @frozen public struct DropWhileSequence<Base: Sequence> { public typealias Element = Base.Element @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows { _iterator = iterator _nextElement = _iterator.next() while let x = _nextElement, try predicate(x) { _nextElement = _iterator.next() } } @inlinable internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows { self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate) } } extension DropWhileSequence { @frozen public struct Iterator { @usableFromInline internal var _iterator: Base.Iterator @usableFromInline internal var _nextElement: Element? @inlinable internal init(_ iterator: Base.Iterator, nextElement: Element?) { _iterator = iterator _nextElement = nextElement } } } extension DropWhileSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element @inlinable public mutating func next() -> Element? { guard let next = _nextElement else { return nil } _nextElement = _iterator.next() return next } } extension DropWhileSequence: Sequence { @inlinable public func makeIterator() -> Iterator { return Iterator(_iterator, nextElement: _nextElement) } @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Base> { guard let x = _nextElement, try predicate(x) else { return self } return try DropWhileSequence(iterator: _iterator, predicate: predicate) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return 0 } @inlinable @inline(__always) public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_semantics("sequence.forEach") @inlinable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { for element in self { if try predicate(element) { return element } } return nil } } extension Sequence where Element: Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [ArraySlice<Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence { /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [ArraySlice<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") let whole = Array(self) return try whole.split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func suffix(_ maxLength: Int) -> [Element] { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") guard maxLength != 0 else { return [] } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into a copy and return it. // This saves memory for sequences particularly longer than `maxLength`. var ringBuffer = ContiguousArray<Element>() ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = 0 for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i = (i + 1) % maxLength } } if i != ringBuffer.startIndex { var rotated = ContiguousArray<Element>() rotated.reserveCapacity(ringBuffer.count) rotated += ringBuffer[i..<ringBuffer.endIndex] rotated += ringBuffer[0..<i] return Array(rotated) } else { return Array(ringBuffer) } } /// Returns a sequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop from the beginning of /// the sequence. `k` must be greater than or equal to zero. /// - Returns: A sequence starting after the specified number of /// elements. /// /// - Complexity: O(1), with O(*k*) deferred to each iteration of the result, /// where *k* is the number of elements to drop from the beginning of /// the sequence. @inlinable public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> { return DropFirstSequence(self, dropping: k) } /// Returns a sequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A sequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func dropLast(_ k: Int = 1) -> [Element] { _precondition(k >= 0, "Can't drop a negative number of elements from a sequence") guard k != 0 else { return Array(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= k. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `k` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result = ContiguousArray<Element>() var ringBuffer = ContiguousArray<Element>() var i = ringBuffer.startIndex for element in self { if ringBuffer.count < k { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = (i + 1) % k } } return Array(result) } /// Returns a sequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the number of elements to drop from /// the beginning of the sequence. @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> DropWhileSequence<Self> { return try DropWhileSequence(self, predicate: predicate) } /// Returns a sequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A sequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @inlinable public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> { return PrefixSequence(self, maxLength: maxLength) } /// Returns a sequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A sequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*k*), where *k* is the length of the result. @inlinable public __consuming func prefix( while predicate: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() for element in self { guard try predicate(element) else { break } result.append(element) } return Array(result) } } extension Sequence { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are /// initialized. @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return nil } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @frozen public struct IteratorSequence<Base: IteratorProtocol> { @usableFromInline internal var _base: Base /// Creates an instance whose iterator is a copy of `base`. @inlinable public init(_ base: Base) { _base = base } } extension IteratorSequence: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Base.Element? { return _base.next() } } /* FIXME: ideally for compatibility we would declare extension Sequence { @available(swift, deprecated: 5, message: "") public typealias SubSequence = AnySequence<Element> } */
apache-2.0
edf619a8f4691e89f66094e688ae6300
35.515853
100
0.638124
4.327173
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Widgets/Color-Extensions.swift
1
895
// // Color-Extensions.swift // Habitica // // Created by Phillip Thelen on 07.10.20. // Copyright © 2020 HabitRPG Inc. All rights reserved. // import SwiftUI extension Color { static let widgetBackground = Color("widgetBackground") static let widgetText = Color("widgetText") static let progressBackground = Color("progressBackground") static let barRed = Color(red: 1.0, green: 97.0 / 255.0, blue: 101.0 / 255.0) static let barOrange = Color(red: 1.0, green: 148.0 / 255.0, blue: 76.0 / 255.0) static let barYellow = Color(red: 1.0, green: 190.0 / 255.0, blue: 93.0 / 255.0) static let barGreen = Color(red: 36.0 / 255.0, green: 204.0 / 255.0, blue: 143.0 / 255.0) static let barTeal = Color(red: 59.0 / 255.0, green: 202.0 / 255.0, blue: 215.0 / 255.0) static let barBlue = Color(red: 80.0 / 255.0, green: 181.0 / 255.0, blue: 233.0 / 255.0) }
gpl-3.0
23276451faa57edcc324446845242975
39.636364
93
0.646532
2.921569
false
false
false
false
jjatie/Charts
ChartsDemo-iOS/Swift/Demos/BubbleChartViewController.swift
1
4406
// // BubbleChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class BubbleChartViewController: DemoBaseViewController { @IBOutlet var chartView: BubbleChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Bubble Chart" options = [.toggleValues, .toggleIcons, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription.isEnabled = false chartView.isDragEnabled = false chartView.setScaleEnabled(true) chartView.maxVisibleCount = 200 chartView.isPinchZoomEnabled = true chartView.legend.horizontalAlignment = .right chartView.legend.verticalAlignment = .top chartView.legend.orientation = .vertical chartView.legend.drawInside = false chartView.legend.font = UIFont(name: "HelveticaNeue-Light", size: 10)! chartView.leftAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)! chartView.leftAxis.spaceTop = 0.3 chartView.leftAxis.spaceBottom = 0.3 chartView.leftAxis.axisMinimum = 0 chartView.rightAxis.isEnabled = false chartView.xAxis.labelPosition = .bottom chartView.xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)! sliderX.value = 10 sliderY.value = 50 slidersValueChanged(nil) } override func updateChartData() { if shouldHideData { chartView.data = nil return } setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let yVals1 = (0 ..< count).map { (i) -> BubbleChartDataEntry in let val = Double(arc4random_uniform(range)) let size = CGFloat(arc4random_uniform(range)) return BubbleChartDataEntry(x: Double(i), y: val, size: size, icon: UIImage(named: "icon")) } let yVals2 = (0 ..< count).map { (i) -> BubbleChartDataEntry in let val = Double(arc4random_uniform(range)) let size = CGFloat(arc4random_uniform(range)) return BubbleChartDataEntry(x: Double(i), y: val, size: size, icon: UIImage(named: "icon")) } let yVals3 = (0 ..< count).map { (i) -> BubbleChartDataEntry in let val = Double(arc4random_uniform(range)) let size = CGFloat(arc4random_uniform(range)) return BubbleChartDataEntry(x: Double(i), y: val, size: size) } let set1 = BubbleChartDataSet(entries: yVals1, label: "DS 1") set1.isDrawIconsEnabled = false set1.setColor(ChartColorTemplates.colorful[0], alpha: 0.5) set1.isDrawValuesEnabled = true let set2 = BubbleChartDataSet(entries: yVals2, label: "DS 2") set2.isDrawIconsEnabled = false set2.iconsOffset = CGPoint(x: 0, y: 15) set2.setColor(ChartColorTemplates.colorful[1], alpha: 0.5) set2.isDrawValuesEnabled = true let set3 = BubbleChartDataSet(entries: yVals3, label: "DS 3") set3.setColor(ChartColorTemplates.colorful[2], alpha: 0.5) set3.isDrawValuesEnabled = true let data = [set1, set2, set3] as BubbleChartData data.setDrawValues(false) data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 7)!) data.setHighlightCircleWidth(1.5) data.setValueTextColor(.white) chartView.data = data } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } // MARK: - Actions @IBAction func slidersValueChanged(_: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" updateChartData() } }
apache-2.0
a4179402419f4bff28c5714192c718a2
33.147287
103
0.622474
4.51332
false
false
false
false
mcgraw/tomorrow
Tomorrow/IGIOnboardTitleViewController.swift
1
2123
// // IGIOnboardTitleViewController.swift // Tomorrow // // Created by David McGraw on 1/24/15. // Copyright (c) 2015 David McGraw. All rights reserved. // import UIKit import pop class IGIOnboardTitleViewController: GAITrackedViewController { @IBOutlet weak var logoIcon: IGIView! @IBOutlet weak var logoTitle: IGILabel! @IBOutlet weak var continueAction: IGIButton! @IBOutlet weak var logoImage: UIImageView! @IBOutlet weak var checkImage: UIImageView! var hasPlayedAnimation = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) screenName = "Onboard Title Screen" view.backgroundColor = UIColor.clearColor() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if hasPlayedAnimation == false { hasPlayedAnimation = true playIntroductionAnimation() } } @IBAction func continueActionPressed(sender: AnyObject) { playDismissAnimation() NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "advanceOnboarding", userInfo: nil, repeats: false) } func advanceOnboarding() { performSegueWithIdentifier("pushSegue", sender: self) } // MARK: Animation func playIntroductionAnimation() { logoIcon.revealViewWithDelay(constant: 80, delay: 0.0, view: logoTitle) continueAction.revealView(constant: 50) NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "showCheck", userInfo: nil, repeats: false) } func showCheck() { UIView.animateWithDuration(1.0, animations: { () -> Void in self.checkImage.alpha = 0.35 }) } func playDismissAnimation() { continueAction.dismissView(constant: -Int(100)) logoTitle.dismissViewWithDelay(constant: -Int((view.bounds.size.height / 2) + 60), delay: 0.5) logoIcon.dismissViewWithDelay(constant: -Int((view.bounds.size.height / 2) + 60), delay: 0.6) } }
bsd-2-clause
71828955077fe742fa4b33796082f042
28.486111
127
0.651437
4.488372
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/Main/LYCAnchorViewController.swift
1
3581
// // LYCAnchorViewController.swift // LYCSwiftDemo // // Created by 李玉臣 on 2017/6/10. // Copyright © 2017年 zsc. All rights reserved. // import UIKit private let kMargin : CGFloat = 8 private let kAnchorCellId : String = "kAnchorCellId" class LYCAnchorViewController: UIViewController { //对外属性 var mainTypeModel : LYCMainTypeModel! //对内属性 fileprivate lazy var mainVM : LYCMainViewModel = LYCMainViewModel() fileprivate lazy var collectionView : UICollectionView = { // 创建瀑布流布局 let waterFullLayout = LYCCollectionViewLayout() waterFullLayout.minimumLineSpacing = kMargin waterFullLayout.minimumInteritemSpacing = kMargin waterFullLayout.sectionInset = UIEdgeInsets(top: kMargin, left: kMargin, bottom: kMargin, right: kMargin) waterFullLayout.dataSource = self as LYCWaterfallLayoutDataSource // 创建 collectionView let collectionView = UICollectionView(frame: self.view.bounds , collectionViewLayout: waterFullLayout) collectionView .register(UINib.init(nibName: "LYCAnchorCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kAnchorCellId) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.white return collectionView }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData(mainTypeModel.type, index: 0) } } // MARK:- 1,初始化UI 2,加载数据 extension LYCAnchorViewController{ // 初始化UI fileprivate func setupUI(){ self.view.addSubview(collectionView) } // 加载数据 fileprivate func loadData(_ type : Int , index : Int){ mainVM.loadMainData(methodType: .GET, urlString: "http://qf.56.com/home/v4/moreAnchor.ios", parameter: ["type" : type, "index" : index , "size" : 48]) { self.collectionView.reloadData() } } } // MARK:- 瀑布流布局的代理方法 extension LYCAnchorViewController : LYCWaterfallLayoutDataSource{ func numberOfColsInWaterfallLayout(_ layout: LYCCollectionViewLayout) -> Int { return 2 } func waterfallLayout(_ layout: LYCCollectionViewLayout, indexPath: IndexPath) -> CGFloat { return indexPath.item % 2 == 0 ? kScreenWidth * 2 / 3.0 : kScreenWidth * 0.5 } } // MARK:- collectionView 的数据源 extension LYCAnchorViewController : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mainVM.anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: kAnchorCellId, for: indexPath) as! LYCAnchorCollectionViewCell collectionViewCell.anchorModel = mainVM.anchors[indexPath.item] // 上拉刷新 if indexPath.item == mainVM.anchors.count - 1 { loadData(mainTypeModel.type, index: mainVM.anchors.count) } return collectionViewCell } } extension LYCAnchorViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let roomVc = LYCRoomViewController() self.navigationController?.pushViewController(roomVc, animated:true) } }
mit
eb36090aa25869b9ab5df8bc3837a16d
33.058824
160
0.690558
4.955777
false
false
false
false
wilfreddekok/Antidote
Antidote/iPadNavigationView.swift
1
1929
// 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 UIKit import SnapKit private struct Constants { static let Width = 200.0 static let Height = 34.0 static let Offset = 12.0 } class iPadNavigationView: UIView { var avatarView: ImageViewWithStatus! var label: UILabel! var didTapHandler: (Void -> Void)? private var button: UIButton! init(theme: Theme) { super.init(frame: CGRect(x: 0.0, y: 0.0, width: Constants.Width, height: Constants.Height)) createViews(theme) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension iPadNavigationView { func buttonPressed() { didTapHandler?() } } private extension iPadNavigationView { func createViews(theme: Theme) { avatarView = ImageViewWithStatus() avatarView.userStatusView.theme = theme addSubview(avatarView) label = UILabel() label.font = UIFont.systemFontOfSize(22.0) addSubview(label) button = UIButton() button.addTarget(self, action: #selector(iPadNavigationView.buttonPressed), forControlEvents: .TouchUpInside) addSubview(button) } func installConstraints() { avatarView.snp_makeConstraints { $0.top.equalTo(self) $0.leading.equalTo(self) $0.size.equalTo(Constants.Height) } label.snp_makeConstraints { $0.leading.equalTo(avatarView.snp_trailing).offset(Constants.Offset) $0.trailing.equalTo(self) $0.top.equalTo(self) $0.bottom.equalTo(self) } button.snp_makeConstraints { $0.edges.equalTo(self) } } }
mpl-2.0
1e3811081a8e5eca77f406b8642ba72b
25.424658
117
0.634007
4.277162
false
false
false
false
yarshure/Surf
Surf/BuyViewController.swift
1
18055
// // ViewController.swift // SwiftyStoreKit // // Created by Andrea Bizzotto on 03/09/2015. // // 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 StoreKit import SwiftyStoreKit import ObjectMapper import SFSocket import XRuler class PurchaseCell: UITableViewCell { @IBOutlet weak var purchase:UIButton! } class ProductCell: PurchaseCell { var haveInfo:Bool = false @IBOutlet weak var production:UILabel! } let buyKey = "com.yarshure.Surf.buy" class ViewController: SFTableViewController { var receipt:Receipt? let purchase1Suffix = RegisteredPurchase.Pro //let purchase2Suffix = RegisteredPurchase.VIP// autoRenewablePurchase @IBOutlet var versionLable:UILabel? @IBOutlet weak var productInfoLabel:UILabel! //@IBOutlet weak var statusButton:UIButton! // MARK: actions @IBAction func getInfo1() { getInfo(purchase1Suffix) } @IBAction func purchase1() { purchase(purchase1Suffix) } @IBAction func verifyPurchase1() { verifyPurchase(purchase1Suffix) } // @IBAction func getInfo2() { // getInfo(purchase2Suffix) // } // @IBAction func purchase2() { // purchase(purchase2Suffix) // } // @IBAction func verifyPurchase2() { // verifyPurchase(purchase2Suffix) // } override func numberOfSections(in tableView: UITableView) -> Int{ return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 4 case 1: return 1 case 2: return 2 default: return 0 } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "purchase") as! PurchaseCell if indexPath.row == 1 { cell.purchase.setTitle("Restore Purchase", for: .normal) cell.purchase.addTarget(self, action: #selector(ViewController.restorePurchases), for: .touchUpInside) }else { cell.purchase.setTitle("Verify Purchase", for: .normal) cell.purchase.addTarget(self, action: #selector(ViewController.verifyPurchase1), for: .touchUpInside) } return cell }else { let cell = tableView.dequeueReusableCell(withIdentifier: "product") as! ProductCell var product = RegisteredPurchase.Pro let features = ["Enable KCP","Enable HTTP/Socks5","Enable Customize Rules","Enable Analyze"] if indexPath.section == 0 { cell.purchase.tag = indexPath.row switch indexPath.row { case 0: product = RegisteredPurchase.KCP cell.production.text = features[0] case 1: product = RegisteredPurchase.HTTP cell.production.text = features[1] case 2: product = RegisteredPurchase.Rule cell.production.text = features[2] case 3: product = RegisteredPurchase.Analyze cell.production.text = features[3] default: break } }else { cell.purchase.tag = 999 } if ProxyGroupSettings.share.wwdcStyle { cell.production.textColor = UIColor.white }else { cell.production.textColor = UIColor.black } if !cell.haveInfo { print("get product info \(product.rawValue)") NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + product.rawValue]) { result in NetworkActivityIndicatorManager.networkOperationFinished() cell.haveInfo = true cell.production.text = self.messageForProductRetrievalInfo(result) //self.showAlert(self.alertForProductRetrievalInfo(result)) } } var test:Bool = false if test { if let r = self.receipt { for ps in r.in_app { print("***** purchsed \(ps.product_id) \(product.rawValue)") if ps.product_id == appBundleId + "." + product.rawValue { cell.purchase.isEnabled = false cell.purchase.setTitle("Purchased", for: .normal) print("purchsed \(ps.product_id)") break } } } }else { if verifyReceiptBuy(.Pro) { cell.purchase.isEnabled = false cell.purchase.setTitle("Purchased", for: .normal) }else { //验证单个商品有没有买 if let r = self.receipt { for ps in r.in_app { print("***** purchsed \(ps.product_id) \(product.rawValue)") if ps.product_id == appBundleId + "." + product.rawValue { cell.purchase.isEnabled = false cell.purchase.setTitle("Purchased", for: .normal) print("purchsed \(ps.product_id)") break } } } } } if cell.purchase.allTargets.isEmpty { cell.purchase.addTarget(self, action: #selector(ViewController.buyProduct(_:)), for: .touchUpInside) } return cell } } @objc func buyProduct(_ sender:UIButton){ switch sender.tag { case 999: purchase(RegisteredPurchase.Pro) case 0: purchase(RegisteredPurchase.KCP) case 1: purchase(RegisteredPurchase.HTTP) case 2: purchase(RegisteredPurchase.Rule) case 3: purchase(RegisteredPurchase.Analyze) default: break } } override func viewDidLoad() { super.viewDidLoad() self.title = "Purchase" if let r = ProxyGroupSettings.share.receipt { self.receipt = r }else { _ = verifyReceipt(.Pro) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let r = ProxyGroupSettings.share.receipt { if let ts = Int64(r.original_purchase_date_ms) { let buy_date = Date.init(timeIntervalSince1970:TimeInterval(ts/1000)) let df = DateFormatter() df.dateFormat = "yyyy/MM/dd HH:mm:ss" df.timeZone = NSTimeZone.system versionLable?.text = "Version " + String(r.original_application_version) + " \(df.string(from: buy_date))" } } } func verifyReceiptBuy(_ product:RegisteredPurchase = RegisteredPurchase.Pro) ->Bool{ if (Int(appBuild())! % 2) != 0 { return true } if findPurchase(product) { return true }else { verifyProduct(product, result: { t in print("111 verifyReceiptBuy \(product.rawValue)") if t { if product == .Pro { print("pro version \(product.rawValue)") } self.tableView.reloadData() }else { print("not pro version \(product.rawValue)") } }) return false } } //只是Pro而已,其他独立feature 单独 func verify(result: @escaping (Bool) ->Void) { NetworkActivityIndicatorManager.networkOperationStarted() verifyReceipt { appresult in NetworkActivityIndicatorManager.networkOperationFinished() //self.showAlert(self.alertForVerifyReceipt(result)) switch appresult { case .success(let receipt): //print("Verify receipt Success: \(receipt)") let r = Mapper<SFStoreReceiptResult>().map(JSON: receipt) if let rr = r?.receipt { self.receipt = rr do { try ProxyGroupSettings.share.saveReceipt(rr) }catch let e { print(" \(e.localizedDescription)") } //按版本,不是购买时间3.2 以后免费 let buyversion = rr.original_application_version.components(separatedBy: ".") let localversion = "3.2".components(separatedBy: ".") var purched = false for (idx,item) in buyversion.enumerated() { if idx < localversion.count { let x = localversion[idx] if Int(x)! > Int(item)! { purched = true break }else { continue } }else { break } } if purched { result(purched) }else { for inapp in rr.in_app { if inapp.product_id == "com.yarshure.Surf.Pro" { print("version buy version > 3.2 ,buy \(inapp.product_id)") purched = true break } } } result(purched) }else { result(false) } case .error(let error): print("Verify receipt Failed: \(error)") var alert:UIAlertController switch error { case .noReceiptData: alert = self.alertWithTitle("Receipt verification", message: "No receipt data. Try again.") case .networkError(let error): alert = self.alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)") default: alert = self.alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)") } self.showAlert(alert) } } } func getInfo(_ purchase: RegisteredPurchase) { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in NetworkActivityIndicatorManager.networkOperationFinished() self.productInfoLabel.text = self.messageForProductRetrievalInfo(result) //self.showAlert(self.alertForProductRetrievalInfo(result)) } } func purchase(_ purchase: RegisteredPurchase) { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: true) { result in NetworkActivityIndicatorManager.networkOperationFinished() if case .success(let purchase) = result { // Deliver content from server, then: if purchase.needsFinishTransaction { SwiftyStoreKit.finishTransaction(purchase.transaction) } self.verify(result: { t in if t { self.tableView.reloadData() } }) } if let alert = self.alertForPurchaseResult(result) { self.showAlert(alert) } } } @IBAction func restorePurchases() { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.restorePurchases(atomically: true) { results in NetworkActivityIndicatorManager.networkOperationFinished() for purchase in results.restoredPurchases where purchase.needsFinishTransaction { // Deliver content from server, then: SwiftyStoreKit.finishTransaction(purchase.transaction) } self.showAlert(self.alertForRestorePurchases(results)) } } // @IBAction func verifyReceipt() { // // NetworkActivityIndicatorManager.networkOperationStarted() // verifyReceipt { result in // NetworkActivityIndicatorManager.networkOperationFinished() // self.showAlert(self.alertForVerifyReceipt(result)) // } // } // func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) { // // let appleValidator = AppleReceiptValidator(service: .production) // let password = "e09dbf3ea2454af4bb5f55c8a5d00d8c" // SwiftyStoreKit.verifyReceipt(using: appleValidator, password: password, completion: completion) // } func verifyPurchase(_ purchase: RegisteredPurchase) { NetworkActivityIndicatorManager.networkOperationStarted() verifyReceipt { result in NetworkActivityIndicatorManager.networkOperationFinished() switch result { case .success(let receipt): let productId = self.appBundleId + "." + purchase.rawValue switch purchase { case .autoRenewablePurchase: let purchaseResult = SwiftyStoreKit.verifySubscription( ofType: .autoRenewable, productId: productId, inReceipt: receipt, validUntil: Date() ) self.showAlert(self.alertForVerifySubscription(purchaseResult)) case .nonRenewingPurchase: let purchaseResult = SwiftyStoreKit.verifySubscription( ofType: .nonRenewing(validDuration: 60), productId: productId, inReceipt: receipt, validUntil: Date() ) self.showAlert(self.alertForVerifySubscription(purchaseResult)) default: let purchaseResult = SwiftyStoreKit.verifyPurchase( productId: productId, inReceipt: receipt ) self.showAlert(self.alertForVerifyPurchase(purchaseResult)) } case .error: self.showAlert(self.alertForVerifyReceipt(result)) } } } #if os(iOS) override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } #endif override func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController { if results.restoreFailedPurchases.count > 0 { print("Restore Failed: \(results.restoreFailedPurchases)") return alertWithTitle("Restore failed", message: "Unknown error. Please contact support") } else if results.restoredPurchases.count > 0 { print("Restore Success: \(results.restoredPurchases)") //statusButton.setTitle("Not Purchased", for: .normal) UserDefaults.standard.set("", forKey: buyKey) UserDefaults.standard.synchronize() return alertWithTitle("Purchases Restored", message: "All purchases have been restored") } else { print("Nothing to Restore") return alertWithTitle("Nothing to restore", message: "No previous purchases were found") } } } // MARK: User facing alerts extension ViewController { }
bsd-3-clause
5d0c6755d32cc9750a4e4adcc0262af5
37.265957
131
0.529775
5.55607
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/PresentAnimatior/UIViewController+Category.swift
1
751
// // UIViewController+Category.swift // LSYWeiBo // // Created by 李世洋 on 16/6/27. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit extension UIViewController { func transitionAnimatior(transitior: Transitior, animationType: PresentationAnimations, showMask: Bool, presented: UIViewController, presentingFrame: () -> CGRect?) { self.transitioningDelegate = transitior self.modalPresentationStyle = UIModalPresentationStyle.Custom transitior.animationType = animationType transitior.showMask = showMask transitior.presentationViewFrame = presentingFrame() presented.presentViewController(self, animated: true, completion: nil) } }
artistic-2.0
6449f77519460eaf3d86bf302e9efdb7
29.708333
170
0.706522
4.842105
false
false
false
false
tjw/swift
benchmark/single-source/CSVParsing.swift
2
7822
import TestsUtils public let CSVParsing = BenchmarkInfo( name: "CSVParsing", runFunction: run_CSVParsing, tags: [.miniapplication, .api, .String], setUpFunction: { buildWorkload() }, tearDownFunction: nil) public let CSVParsingAlt = BenchmarkInfo( name: "CSVParsingAlt", runFunction: run_CSVParsingAlt, tags: [.miniapplication, .api, .String], setUpFunction: { buildWorkload() }, tearDownFunction: nil) public let CSVParsingAltIndices = BenchmarkInfo( name: "CSVParsingAltIndices", runFunction: run_CSVParsingAltIndices, tags: [.miniapplication, .api, .String], setUpFunction: { buildWorkload() }, tearDownFunction: nil) struct ParseError: Error { var message: String } let comma = ",".utf16.first! let newline = "\n".utf16.first! let carriageReturn = "\n".utf16.first! let quote = "\"".utf16.first! func parseQuotedField(_ remainder: inout Substring) throws -> Substring? { var result: Substring = "" // we accumulate the result while !remainder.isEmpty { guard let nextQuoteIndex = remainder.index(of: "\"") else { throw ParseError(message: "Expected a closing \"") } // Append until the next quote result += remainder.prefix(upTo: nextQuoteIndex) remainder.remove(upToAndIncluding: nextQuoteIndex) if let peek = remainder.utf16.first { switch peek { case quote: // two quotes after each other is an escaped quote remainder.removeFirst() result.append("\"") case comma: // field ending remainder.removeFirst() return result default: return result } } else { // End of the string return result } } throw ParseError(message: "Expected a closing quote") } // Consume a single field from `remainder` func parseField(_ remainder: inout Substring) throws -> Substring? { guard let start = remainder.utf16.first else { return nil } switch start { case quote: remainder.removeFirst() // remove the first quote return try parseQuotedField(&remainder) case newline: return nil default: // This is the most common case and should ideally be super fast... var index = remainder.utf16.startIndex while index < remainder.utf16.endIndex { switch remainder.utf16[index] { case comma: defer { remainder.remove(upToAndIncluding: index) } return remainder.prefix(upTo: index) case newline: let result = remainder.prefix(upTo: index) remainder.remove(upTo: index) return result default: remainder.utf16.formIndex(after: &index) } } let result = remainder remainder.removeAll() return result } } extension Substring { mutating func remove(upTo index: Index) { self = suffix(from: index) } mutating func remove(upToAndIncluding index: Index) { self = suffix(from: self.index(after: index)) } } // Consume a single line from `remainder` func parseLine<State>(_ remainder: inout Substring, result: inout State, processField: (inout State, Int, Substring) -> ()) throws -> Bool { var fieldNumber = 0 while let field = try parseField(&remainder) { processField(&result, fieldNumber, field) fieldNumber += 1 } if !remainder.isEmpty { let next = remainder.utf16[remainder.utf16.startIndex] guard next == carriageReturn || next == newline else { throw ParseError(message: "Expected a newline or CR, got \(next)") } while let x = remainder.utf16.first, x == carriageReturn || x == newline { remainder.utf16.removeFirst() } } return !remainder.isEmpty && fieldNumber > 0 } extension String { func parseAlt() -> [[String]] { var result: [[String]] = [[]] var currentField = "".unicodeScalars var inQuotes = false func flush() { result[result.endIndex-1].append(String(currentField)) currentField.removeAll() } for c in self.unicodeScalars { switch (c, inQuotes) { case (",", false): flush() case ("\n", false): flush() result.append([]) case ("\"", _): inQuotes = !inQuotes currentField.append(c) default: currentField.append(c) } } flush() return result } func parseAltIndices() -> [[Substring]] { var result: [[Substring]] = [[]] var fieldStart = self.startIndex var inQuotes = false func flush(endingAt end: Index) { result[result.endIndex-1].append(self[fieldStart..<end]) } for i in self.unicodeScalars.indices { switch (self.unicodeScalars[i], inQuotes) { case (",", false): flush(endingAt: i) fieldStart = self.unicodeScalars.index(after: i) case ("\n", false): flush(endingAt: i) fieldStart = self.unicodeScalars.index(after: i) result.append([]) case ("\"", _): inQuotes = !inQuotes default: continue } } flush(endingAt: endIndex) return result } } let workloadBase = """ Heading1,Heading2,Heading3,Heading4,Heading5,Heading6,Heading7 FirstEntry,"secondentry",third,fourth,fifth,sixth,seventh zéro,un,deux,trois,quatre,cinq,six pagh,wa',cha',wej,IoS,vagh,jav ᬦᬸᬮ᭄,ᬲᬶᬓᬶ,ᬤᬸᬯ,ᬢᭂᬮᬸ,ᬧᬧᬢ᭄,ᬮᬶᬫᬾ,ᬦᭂᬦᭂᬫ᭄ unu,du,tri,kvar,kvin,ses,sep "quoted", "f""i"e"l"d, "with a comma ',' in it", "and some \n for good measure", five, six, seven 𐌏𐌉𐌍𐌏,𐌃𐌏,𐌕𐌓𐌉,𐌐𐌄𐌕𐌏𐌓,𐌐𐌄𐌌𐌐𐌄,𐌔𐌖𐌄𐌊𐌏𐌔,𐌔𐌄𐌗𐌕𐌀𐌌 zero,un,duo.tres.quantro,cinque,sex nolla,yksi,kaksi,kolme,neljä,viisi,kuusi really long field, because otherwise, small string opt,imizations may trivial,ize the copies that, were trying to also, measure here!!!! нула,једин,два,три,четыри,петь,шесть 一,二,三,四,五,六,七, saquui,ta'lo,tso'i,nvgi,hisgi,sudali,galiquogi """ let targetRowNumber = 200_000 let repeatCount = targetRowNumber / workloadBase.split(separator: "\n").count let workload: String = repeatElement(workloadBase, count: repeatCount).joined() public func buildWorkload() { let contents = workload let alt: [[String]] = contents.parseAlt() let altIndices: [[String]] = contents.parseAltIndices().map { $0.map { String($0) } } CheckResults(alt.elementsEqual(altIndices)) } @inline(never) public func run_CSVParsing(_ N: Int) { let contents = workload for _ in 0..<N { var remainder = contents[...] var result: Int = 0 var x: () = () while !remainder.isEmpty { blackHole(try? parseLine(&remainder, result: &x, processField: { state, _, field in () })) blackHole(x) result += 1 } blackHole(result) } } @inline(never) public func run_CSVParsingAlt(_ N: Int) { let contents = workload for _ in 0..<N { blackHole(contents.parseAlt()) } } @inline(never) public func run_CSVParsingAltIndices(_ N: Int) { let contents = workload for _ in 0..<N { blackHole(contents.parseAltIndices()) } }
apache-2.0
07b292cd855ba69beed2caaf2c2bfa65
29.5
140
0.58623
3.784119
false
false
false
false
lorentey/swift
stdlib/public/Darwin/Foundation/NSStringAPI.swift
4
77933
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Important Note // ============== // // This file is shared between two projects: // // 1. https://github.com/apple/swift/tree/master/stdlib/public/Darwin/Foundation // 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation // // If you change this file, you must update it in both places. #if !DEPLOYMENT_RUNTIME_SWIFT @_exported import Foundation // Clang module #endif // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } #if !DEPLOYMENT_RUNTIME_SWIFT // We only need this for UnsafeMutablePointer, but there's not currently a way // to write that constraint. extension Optional { /// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the /// address of `object` to `body`. /// /// This is intended for use with Foundation APIs that return an Objective-C /// type via out-parameter where it is important to be able to *ignore* that /// parameter by passing `nil`. (For some APIs, this may allow the /// implementation to avoid some work.) /// /// In most cases it would be simpler to just write this code inline, but if /// `body` is complicated than that results in unnecessarily repeated code. internal func _withNilOrAddress<NSType : AnyObject, ResultType>( of object: inout NSType?, _ body: (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } #endif /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. internal func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let cString = p else { return nil } let len = UTF8._nullCodeUnitOffset(in: cString) var result = [CChar](repeating: 0, count: len + 1) for i in 0..<len { result[i] = cString[i] } return result } extension String { //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// An array of the encodings that strings support in the application's /// environment. public static var availableStringEncodings: [Encoding] { var result = [Encoding]() var p = NSString.availableStringEncodings while p.pointee != 0 { result.append(Encoding(rawValue: p.pointee)) p += 1 } return result } // @property (class) NSStringEncoding defaultCStringEncoding; /// The C-string encoding assumed for any method accepting a C string as an /// argument. public static var defaultCStringEncoding: Encoding { return Encoding(rawValue: NSString.defaultCStringEncoding) } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of the specified encoding. /// /// - Parameter encoding: A string encoding. For possible values, see /// `String.Encoding`. /// - Returns: A human-readable string giving the name of `encoding` in the /// current locale. public static func localizedName( of encoding: Encoding ) -> String { return NSString.localizedName(of: encoding.rawValue) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. public static func localizedStringWithFormat( _ format: String, _ arguments: CVarArg... ) -> String { return String(format: format, locale: Locale.current, arguments: arguments) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Creates a string by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let str = String(validatingUTF8: bytes) { self = str return } if let ns = NSString(utf8String: bytes) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } } extension String { //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Creates a new string equivalent to the given bytes interpreted in the /// specified encoding. /// /// - Parameters: /// - bytes: A sequence of bytes to interpret using `encoding`. /// - encoding: The ecoding to use to interpret `bytes`. public init?<S: Sequence>(bytes: __shared S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if encoding == .utf8, let str = byteArray.withUnsafeBufferPointer({ String._tryFromUTF8($0) }) { self = str return } if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of bytes from the /// given buffer, interpreted in the specified encoding, and optionally /// frees the buffer. /// /// - Warning: This initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Creates a new string that contains the specified number of characters /// from the given C array of Unicode characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count)) } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of characters /// from the given C array of UTF-16 code units. public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = String._unconditionallyBridgeFromObjectiveC(NSString( charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)) } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: __shared String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: __shared String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOfFile path: __shared String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOf url: __shared URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOf url: __shared URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOf url: __shared URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( cString: UnsafePointer<CChar>, encoding enc: Encoding ) { if enc == .utf8, let str = String(validatingUTF8: cString) { self = str return } if let ns = NSString(cString: cString, encoding: enc.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: __shared Data, encoding: Encoding) { if encoding == .utf8, let str = data.withUnsafeBytes({ String._tryFromUTF8($0.bindMemory(to: UInt8.self)) }) { self = str return } guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = String._unconditionallyBridgeFromObjectiveC(s) } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: __shared String, _ arguments: CVarArg...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user's default locale. public init(format: __shared String, arguments: __shared [CVarArg]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, _ args: CVarArg...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, arguments: __shared [CVarArg]) { #if DEPLOYMENT_RUNTIME_SWIFT self = withVaList(arguments) { String._unconditionallyBridgeFromObjectiveC( NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0) ) } #else self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } #endif } } extension StringProtocol where Index == String.Index { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. // FIXME(strings): There is probably a better way to bridge Self to NSString var _ns: NSString { return self._ephemeralString._bridgeToObjectiveC() } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _toIndex(_ utf16Index: Int) -> Index { return self._toUTF16Index(utf16Index) } /// Return the UTF-16 code unit offset corresponding to an Index func _toOffset(_ idx: String.Index) -> Int { return self._toUTF16Offset(idx) } @inlinable internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange(self._toUTF16Offsets(r)) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _toRange(_ r: NSRange) -> Range<Index> { return self._toUTF16Indices(Range(r)!) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. func _optionalRange(_ r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return nil } return _toRange(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( _ index: UnsafeMutablePointer<Index>?, _ body: (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = _toIndex(utf16Index) return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( _ range: UnsafeMutablePointer<Range<Index>>?, _ body: (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._toRange(nsRange) return result } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the string can be /// converted to the specified encoding without loss of information. /// /// - Parameter encoding: A string encoding. /// - Returns: `true` if the string can be encoded in `encoding` without loss /// of information; otherwise, `false`. public func canBeConverted(to encoding: String.Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// A copy of the string with each word changed to its corresponding /// capitalized spelling. /// /// This property performs the canonical (non-localized) mapping. It is /// suitable for programming operations that require stable results not /// depending on the current locale. /// /// A capitalized string is a string with the first character in each word /// changed to its corresponding uppercase value, and all remaining /// characters set to their corresponding lowercase values. A "word" is any /// sequence of characters delimited by spaces, tabs, or line terminators. /// Some common word delimiting punctuation isn't considered, so this /// property may not generally produce the desired results for multiword /// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for /// additional information. /// /// Case transformations aren’t guaranteed to be symmetrical or to produce /// strings of the same lengths as the originals. public var capitalized: String { return _ns.capitalized } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the string that is produced /// using the current locale. @available(macOS 10.11, iOS 9.0, *) public var localizedCapitalized: String { return _ns.localizedCapitalized } // - (NSString *)capitalizedStringWithLocale:(Locale *)locale /// Returns a capitalized representation of the string /// using the specified locale. public func capitalized(with locale: Locale?) -> String { return _ns.capitalized(with: locale) } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString._ephemeralString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(StringCompareOptions)mask /// Returns a string containing characters this string and the /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix< T : StringProtocol >(with aString: T, options: String.CompareOptions = []) -> String { return _ns.commonPrefix(with: aString._ephemeralString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. public func compare<T : StringProtocol>( _ aString: T, options mask: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil ) -> ComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. let aString = aString._ephemeralString return locale != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange( range ?? startIndex..<endIndex ), locale: locale?._bridgeToObjectiveC() ) : range != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange(range!) ) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the string as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the string. /// /// - Returns: The actual number of matching paths. public func completePath( into outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { #if DEPLOYMENT_RUNTIME_SWIFT var outputNamePlaceholder: String? var outputArrayPlaceholder = [String]() let res = self._ns.completePath( into: &outputNamePlaceholder, caseSensitive: caseSensitive, matchesInto: &outputArrayPlaceholder, filterTypes: filterTypes ) if let n = outputNamePlaceholder { outputName?.pointee = n } else { outputName?.pointee = "" } outputArray?.pointee = outputArrayPlaceholder return res #else // DEPLOYMENT_RUNTIME_SWIFT var nsMatches: NSArray? var nsOutputName: NSString? let result: Int = outputName._withNilOrAddress(of: &nsOutputName) { outputName in outputArray._withNilOrAddress(of: &nsMatches) { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 let outputNonOptionalName = unsafeBitCast( outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self) let outputNonOptionalArray = unsafeBitCast( outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, matchesInto: outputNonOptionalArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion outputArray?.pointee = matches as! [String] } if let n = nsOutputName { outputName?.pointee = n as String } return result #endif // DEPLOYMENT_RUNTIME_SWIFT } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the string /// that have been divided by characters in the given set. public func components(separatedBy separator: CharacterSet) -> [String] { return _ns.components(separatedBy: separator) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the string that have been /// divided by the given separator. /// /// The substrings in the resulting array appear in the same order as the /// original string. Adjacent occurrences of the separator string produce /// empty strings in the result. Similarly, if the string begins or ends /// with the separator, the first or last substring, respectively, is empty. /// The following example shows this behavior: /// /// let list1 = "Karin, Carrie, David" /// let items1 = list1.components(separatedBy: ", ") /// // ["Karin", "Carrie", "David"] /// /// // Beginning with the separator: /// let list2 = ", Norman, Stanley, Fletcher" /// let items2 = list2.components(separatedBy: ", ") /// // ["", "Norman", "Stanley", "Fletcher" /// /// If the list has no separators, the array contains only the original /// string itself. /// /// let name = "Karin" /// let list = name.components(separatedBy: ", ") /// // ["Karin"] /// /// - Parameter separator: The separator string. /// - Returns: An array containing substrings that have been divided from the /// string using `separator`. // FIXME(strings): now when String conforms to Collection, this can be // replaced by split(separator:maxSplits:omittingEmptySubsequences:) public func components< T : StringProtocol >(separatedBy separator: T) -> [String] { return _ns.components(separatedBy: separator._ephemeralString) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the string as a C string /// using a given encoding. public func cString(using encoding: String.Encoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cString(using: encoding.rawValue)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns a `Data` containing a representation of /// the `String` encoded using a given encoding. public func data( using encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { switch encoding { case .utf8: return Data(self.utf8) default: return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } } // @property NSString* decomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines( invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void ) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line, &stop_) if stop_ { stop.pointee = true } } } // @property NSStringEncoding fastestEncoding; /// The fastest encoding to which the string can be converted without loss /// of information. public var fastestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.fastestEncoding) } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`'s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( _ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: Swift.min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and the given string using a case-insensitive, /// localized, comparison. public func localizedCaseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and the given string using a localized comparison. public func localizedCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCompare(aString._ephemeralString) } /// Compares the string and the given string as sorted by the Finder. public func localizedStandardCompare< T : StringProtocol >(_ string: T) -> ComparisonResult { return _ns.localizedStandardCompare(string._ephemeralString) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedLowercase: String { return _ns.localizedLowercase } // - (NSString *)lowercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. public func lowercased(with locale: Locale?) -> String { return _ns.lowercased(with: locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. public func maximumLengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // @property NSString* precomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } #if !DEPLOYMENT_RUNTIME_SWIFT // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. public func propertyList() -> Any { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:] } #endif // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns a Boolean value indicating whether the string contains the given /// string, taking the current locale into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardContains< T : StringProtocol >(_ string: T) -> Bool { return _ns.localizedStandardContains(string._ephemeralString) } // @property NSStringEncoding smallestEncoding; /// The smallest encoding to which the string can be converted without /// loss of information. public var smallestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.smallestEncoding) } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string created by replacing all characters in the string /// not in the specified set with percent encoded characters. public func addingPercentEncoding( withAllowedCharacters allowedCharacters: CharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.addingPercentEncoding(withAllowedCharacters: allowedCharacters ) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string created by appending a string constructed from a given /// format string and the following arguments. public func appendingFormat< T : StringProtocol >( _ format: T, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format._ephemeralString, arguments: arguments)) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string created by appending the given string. // FIXME(strings): shouldn't it be deprecated in favor of `+`? public func appending< T : StringProtocol >(_ aString: T) -> String { return _ns.appending(aString._ephemeralString) } /// Returns a string with the given character folding options /// applied. public func folding( options: String.CompareOptions = [], locale: Locale? ) -> String { return _ns.folding(options: options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. public func padding< T : StringProtocol >( toLength newLength: Int, withPad padString: T, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString._ephemeralString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// A new string made from the string by replacing all percent encoded /// sequences with the matching UTF-8 characters. public var removingPercentEncoding: String? { return _ns.removingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. public func replacingCharacters< T : StringProtocol, R : RangeExpression >(in range: R, with replacement: T) -> String where R.Bound == Index { return _ns.replacingCharacters( in: _toRelativeNSRange(range.relative(to: self)), with: replacement._ephemeralString) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(StringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the string are replaced by /// another given string. public func replacingOccurrences< Target : StringProtocol, Replacement : StringProtocol >( of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { let target = target._ephemeralString let replacement = replacement._ephemeralString return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } #endif // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. public func trimmingCharacters(in set: CharacterSet) -> String { return _ns.trimmingCharacters(in: set) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase } // - (NSString *)uppercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. public func uppercased(with locale: Locale?) -> String { return _ns.uppercased(with: locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func write< T : StringProtocol >( toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( toFile: path._ephemeralString, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func write( to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); #if !DEPLOYMENT_RUNTIME_SWIFT /// Perform string transliteration. @available(macOS 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, invoking body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) where R.Bound == Index { let range = range.relative(to: self) _ns.enumerateLinguisticTags( in: _toRelativeNSRange(range), scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString), options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0!.rawValue, self._toRange($1), self._toRange($2), &stop_) if stop_ { $3.pointee = true } } } #endif // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the specified range of /// the string. /// /// Mutation of a string value while enumerating its substrings is not /// supported. If you need to mutate a string from within `body`, convert /// your string to an `NSMutableString` instance and then call the /// `enumerateSubstrings(in:options:using:)` method. /// /// - Parameters: /// - range: The range within the string to enumerate substrings. /// - opts: Options specifying types of substrings and enumeration styles. /// If `opts` is omitted or empty, `body` is called a single time with /// the range of the string specified by `range`. /// - body: The closure executed for each substring in the enumeration. The /// closure takes four arguments: /// - The enumerated substring. If `substringNotRequired` is included in /// `opts`, this parameter is `nil` for every execution of the /// closure. /// - The range of the enumerated substring in the string that /// `enumerate(in:options:_:)` was called on. /// - The range that includes the substring as well as any separator or /// filler characters that follow. For instance, for lines, /// `enclosingRange` contains the line terminators. The enclosing /// range for the first string enumerated also contains any characters /// that occur before the string. Consecutive enclosing ranges are /// guaranteed not to overlap, and every single character in the /// enumerated range is included in one and only one enclosing range. /// - An `inout` Boolean value that the closure can use to stop the /// enumeration by setting `stop = true`. public func enumerateSubstrings< R : RangeExpression >( in range: R, options opts: String.EnumerationOptions = [], _ body: @escaping ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) where R.Bound == Index { _ns.enumerateSubstrings( in: _toRelativeNSRange(range.relative(to: self)), options: opts) { var stop_ = false body($0, self._toRange($1), self._toRange($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(StringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver's contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` if some characters were converted, `false` otherwise. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes< R : RangeExpression >( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: R, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool where R.Bound == Index { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: Swift.min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toRelativeNSRange(range.relative(to: self)), remaining: $0) } } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _toRange(_ns.lineRange( for: _toRelativeNSRange(aRange.relative(to: self)))) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. public func linguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] where R.Bound == Index { var nsTokenRanges: NSArray? let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toRelativeNSRange(range.relative(to: self)), scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString), options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if let nsTokenRanges = nsTokenRanges { tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map { self._toRange($0.rangeValue) } } return result as! [String] } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _toRange( _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self)))) } #endif // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. public func rangeOfCharacter( from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toRelativeNSRange( aRange ?? startIndex..<endIndex ) ) ) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. public func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> { return _toRange( _ns.rangeOfComposedCharacterSequence(at: _toOffset(anIndex))) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences< R : RangeExpression >( for range: R ) -> Range<Index> where R.Bound == Index { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _toRange( _ns.rangeOfComposedCharacterSequences( for: _toRelativeNSRange(range.relative(to: self)))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(StringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)searchRange // locale:(Locale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. public func range< T : StringProtocol >( of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { let aString = aString._ephemeralString return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardRange< T : StringProtocol >(of string: T) -> Range<Index>? { return _optionalRange( _ns.localizedStandardRange(of: string._ephemeralString)) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func addingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } #endif //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` if `other` is non-empty and contained within `self` by /// case-sensitive, non-literal search. Otherwise, returns `false`. /// /// Equivalent to `self.range(of: other) != nil` public func contains<T : StringProtocol>(_ other: T) -> Bool { let r = self.range(of: other) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.contains(other._ephemeralString)) } return r } /// Returns a Boolean value indicating whether the given string is non-empty /// and contained within this string by case-insensitive, non-literal /// search, taking into account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, can be /// achieved by calling `range(of:options:range:locale:)`. /// /// Equivalent to: /// /// range(of: other, options: .caseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains< T : StringProtocol >(_ other: T) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.localizedCaseInsensitiveContains(other._ephemeralString)) } return r } } // Deprecated slicing extension StringProtocol where Index == String.Index { // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range from' operator.") public func substring(from index: Index) -> String { return _ns.substring(from: _toOffset(index)) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range upto' operator.") public func substring(to index: Index) -> String { return _ns.substring(to: _toOffset(index)) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript.") public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toRelativeNSRange(aRange)) } } extension StringProtocol { // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { fatalError("unavailable function can't be called") } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public func getFileSystemRepresentation( _ buffer: inout [CChar], maxLength: Int) -> Bool { fatalError("unavailable function can't be called") } //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message: "Use lastPathComponent on URL instead.") public var lastPathComponent: String { fatalError("unavailable function can't be called") } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { fatalError("unavailable function can't be called") } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message: "Use pathComponents on URL instead.") public var pathComponents: [String] { fatalError("unavailable function can't be called") } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`'s extension, if any. @available(*, unavailable, message: "Use pathExtension on URL instead.") public var pathExtension: String { fatalError("unavailable function can't be called") } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.") public var abbreviatingWithTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message: "Use appendingPathComponent on URL instead.") public func appendingPathComponent(_ aString: String) -> String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message: "Use appendingPathExtension on URL instead.") public func appendingPathExtension(_ ext: String) -> String? { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.") public var deletingLastPathComponent: String { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message: "Use deletingPathExtension on URL instead.") public var deletingPathExtension: String { fatalError("unavailable function can't be called") } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.") public var expandingTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: String.CompareOptions = [], locale: Locale? ) -> String { fatalError("unavailable function can't be called") } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.") public var resolvingSymlinksInPath: String { fatalError("unavailable property") } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message: "Use standardizingPath on URL instead.") public var standardizingPath: String { fatalError("unavailable function can't be called") } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in a given array. @available(*, unavailable, message: "Map over paths with appendingPathComponent instead.") public func strings(byAppendingPaths paths: [String]) -> [String] { fatalError("unavailable function can't be called") } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: String.Encoding ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func pathWithComponents(_ components: [String]) -> String { fatalError("unavailable function can't be called") } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func path(withComponents components: [String]) -> String { fatalError("unavailable function can't be called") } } extension StringProtocol { @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "capitalizedString(with:)") public func capitalizedStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "commonPrefix(with:options:)") public func commonPrefixWith( _ aString: String, options: String.CompareOptions) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)") public func completePathInto( _ outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedByCharactersIn( _ separator: CharacterSet ) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)") public func enumerateLinguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: String.EnumerationOptions = [], _ body: ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") public func getBytes( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)") public func getLineStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)") public func getParagraphStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lengthOfBytes(using:)") public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lineRange(for:)") public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)") public func linguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil ) -> [String] { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "lowercased(with:)") public func lowercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "maximumLengthOfBytes(using:)") public func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "paragraphRange(for:)") public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)") public func rangeOfCharacterFrom( _ aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)") public func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)") public func rangeOfComposedCharacterSequencesFor( _ range: Range<Index> ) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "range(of:options:range:locale:)") public func rangeOf( _ aString: String, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "localizedStandardRange(of:)") public func localizedStandardRangeOf(_ string: String) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)") public func addingPercentEncodingWithAllowedCharacters( _ allowedCharacters: CharacterSet ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEscapes(using:)") public func addingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "appendingFormat") public func stringByAppendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "padding(toLength:with:startingAt:)") public func byPaddingToLength( _ newLength: Int, withString padString: String, startingAt padIndex: Int ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingCharacters(in:with:)") public func replacingCharactersIn( _ range: Range<Index>, withString replacement: String ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)") public func replacingOccurrencesOf( _ target: String, withString replacement: String, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "trimmingCharacters(in:)") public func byTrimmingCharactersIn(_ set: CharacterSet) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "strings(byAppendingPaths:)") public func stringsByAppendingPaths(_ paths: [String]) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(from:)") public func substringFrom(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(to:)") public func substringTo(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(with:)") public func substringWith(_ aRange: Range<Index>) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased(with:)") public func uppercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(toFile:atomically:encoding:)") public func writeToFile( _ path: String, atomically useAuxiliaryFile:Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(to:atomically:encoding:)") public func writeToURL( _ url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } }
apache-2.0
2402d7cb86526774051481e0d3cee479
34.326836
279
0.675854
4.763217
false
false
false
false
swiftde/16-CoreData
BuchVerleih-Tutorial/BuchVerleih-Tutorial/AppDelegate.swift
2
6896
// // AppDelegate.swift // BuchVerleih-Tutorial // // Created by Benjamin Herzog on 04.07.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func saveContext () { var error: NSError? = nil let managedObjectContext = self.managedObjectContext if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } // #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. var managedObjectContext: NSManagedObjectContext { if _managedObjectContext == nil { let coordinator = self.persistentStoreCoordinator _managedObjectContext = NSManagedObjectContext() _managedObjectContext!.persistentStoreCoordinator = coordinator } return _managedObjectContext! } var _managedObjectContext: NSManagedObjectContext? = nil // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. var managedObjectModel: NSManagedObjectModel { if _managedObjectModel == nil { let modelURL = NSBundle.mainBundle().URLForResource("BuchVerleih_Tutorial", withExtension: "momd") _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!) } return _managedObjectModel! } var _managedObjectModel: NSManagedObjectModel? = nil // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. var persistentStoreCoordinator: NSPersistentStoreCoordinator { if _persistentStoreCoordinator == nil { let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("BuchVerleih_Tutorial.sqlite") var error: NSError? = nil _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ //println("Unresolved error \(error), \(error.userInfo)") abort() } } return _persistentStoreCoordinator! } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil // #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as NSURL } }
gpl-2.0
6b71015dbab80b3836c8bb6603fa5866
52.046154
285
0.709832
6.070423
false
false
false
false
marcopolee/glimglam
Glimglam WatchKit Extension/ExtensionDelegate.swift
1
3824
// // ExtensionDelegate.swift // Glimglam WatchKit Extension // // Created by Tyrone Trevorrow on 12/10/17. // Copyright © 2017 Marco Polee. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { var context: CoreContext! class var shared: ExtensionDelegate { return WKExtension.shared().delegate as! ExtensionDelegate } struct State { var loggedIn = false } var state = State() var watchBridge: WatchBridge! func applicationDidFinishLaunching() { // Perform any final initialization of your application. context = CoreContext() context.readFromKeychain() watchBridge = WatchBridge(context: context) NotificationCenter.default.addObserver(forName: .coreContextUpdate, object: nil, queue: OperationQueue.main) { [weak self] notification in self?.reloadRoots() } reloadRoots() } // Calling this will reset the UI func reloadRoots() { print("context changed previous state = \(state.loggedIn) new login = \(String(describing: context.gitLabLogin))") if state.loggedIn && context.gitLabLogin == nil { // was logged in, now not state.loggedIn = false WKInterfaceController.reloadRootControllers(withNamesAndContexts: [(name: "SignIn", context: context)]) } else if !state.loggedIn && context.gitLabLogin != nil { state.loggedIn = true WKInterfaceController.reloadRootControllers(withNamesAndContexts: [(name: "Namespaces", context: InterfaceContext(context: context))]) } } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. backgroundTask.setTaskCompletedWithSnapshot(false) case let snapshotTask as WKSnapshotRefreshBackgroundTask: // Snapshot tasks have a unique completion call, make sure to set your expiration date snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // Be sure to complete the connectivity task once you’re done. connectivityTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // Be sure to complete the URL session task once you’re done. urlSessionTask.setTaskCompletedWithSnapshot(false) default: // make sure to complete unhandled task types task.setTaskCompletedWithSnapshot(false) } } } }
mit
ae101aa6b31cb91e589ff10cb2e5ad63
45.54878
285
0.679591
5.507937
false
false
false
false
zeushin/RGInnerBadgeButton
RGInnerBadgeButton/Classes/RGInnerBadgeButton.swift
1
4380
// // RGInnerBadgeButton.swift // RGInnerBadgeButton // // Created by Masher Shin on 03/01/2017. // Copyright © 2017 Masher Shin. All rights reserved. // import UIKit @IBDesignable @objc open class RGInnerBadgeButton: UIButton { @IBInspectable open var margin: CGFloat = 10 { didSet { setNeedsDisplay() } } @IBInspectable open var countDiffSize: CGFloat = 4 { didSet { setNeedsDisplay() } } @IBInspectable open var countInsetTop: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable open var countInsetLeft: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable open var countInsetBottom: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable open var countInsetRight: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable open var lineWidth: CGFloat = 1 / UIScreen.main.nativeScale { didSet { setNeedsDisplay() } } @IBInspectable open var badgeNumber: Int = 0 { didSet { setNeedsDisplay() } } private var countEdgeInsets: UIEdgeInsets { return UIEdgeInsets(top: countInsetTop, left: countInsetLeft, bottom: countInsetBottom, right: countInsetRight) } override open func layoutSubviews() { super.layoutSubviews() setNeedsDisplay() } override open func draw(_ rect: CGRect) { guard let titleLabel = titleLabel else { return } if badgeNumber == 0 { super.draw(rect) } else { let countFont = UIFont(name: titleLabel.font.fontName, size: titleLabel.font.pointSize - countDiffSize)! var countStringAttributes: [String: Any] = [:] countStringAttributes[convertFromNSAttributedStringKey(NSAttributedString.Key.font)] = countFont if let textColor = titleLabel.textColor { countStringAttributes[convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)] = textColor.withAlphaComponent(titleLabel.alpha) } else { countStringAttributes[convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)] = UIColor.clear } let countString = NSAttributedString(string: String(badgeNumber), attributes: convertToOptionalNSAttributedStringKeyDictionary(countStringAttributes)) let badgeSize = CGSize(width: countString.size().width + countEdgeInsets.left + countEdgeInsets.right, height: countString.size().height + countEdgeInsets.top + countEdgeInsets.bottom) let inset = (badgeSize.width + margin) / 2 titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -inset, bottom: 0, right: inset) let countPoint = CGPoint(x: titleLabel.frame.maxX + margin + countEdgeInsets.left - inset + titleEdgeInsets.right, y: titleLabel.frame.midY - (countString.size().height / 2)) countString.draw(at: countPoint) let badgeRect = CGRect(x: countPoint.x - countEdgeInsets.left, y: countPoint.y - countEdgeInsets.top, width: badgeSize.width, height: badgeSize.height) let badgePath = UIBezierPath(rect: badgeRect) badgePath.lineWidth = lineWidth titleLabel.textColor.withAlphaComponent(titleLabel.alpha).set() badgePath.stroke() } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
mit
d381b18e03c5ff57363b50efd80ca060
32.684615
162
0.600822
5.340244
false
false
false
false
Chakery/AyLoading
Classes/NSButton+Loading.swift
1
1523
// // NSButton+Loading.swift // talkpal // // Created by Chakery on 2017/9/6. // Copyright © 2017年 Chakery. All rights reserved. // import Cocoa private var subViewsTempKey: Void? extension AyLoading where Base: NSButton { private var subViewsTemp: [NSView] { get { return objc_getAssociatedObject(base, &subViewsTempKey) as? [NSView] ?? [] } set { objc_setAssociatedObject(base, &subViewsTempKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } @discardableResult public func startLoading(message: String? = nil) -> Bool { guard !base.ay.indicatorView.isLoading else { return false } base.isEnabled = false prepareStartLoading() base.ay.startAnimation(message) return true } @discardableResult public func stopLoading() -> Bool { guard base.ay.indicatorView.isLoading else { return false } prepareStopLoading() base.ay.stopAnimation { [weak base] in base?.isEnabled = true } return true } private func prepareStartLoading() { subViewsTemp = base.subviews.filter { "NSButtonTextField" == String(describing: type(of: $0)) } for item in subViewsTemp { item.ay.removeFromSuperview(animated: true) } } private func prepareStopLoading() { for item in subViewsTemp { base.ay.addSubview(item, animated: true) } } }
mit
b149f7388ad16b674617fede9292dfc7
25.666667
104
0.603289
4.342857
false
false
false
false
roambotics/swift
test/Generics/protocol_where_clause.swift
4
2715
// RUN: %target-typecheck-verify-swift -swift-version 4 func needsSameType<T>(_: T.Type, _: T.Type) {} protocol Foo {} func needsFoo<T: Foo>(_: T.Type) {} protocol Foo2 {} func needsFoo2<T: Foo2>(_: T.Type) {} extension Int: Foo, Foo2 {} extension Float: Foo {} protocol Parent { associatedtype T } func needsParent<X: Parent>(_: X.Type) {} struct ConcreteParent: Parent { typealias T = Int } struct ConcreteParent2: Parent { typealias T = Int } struct ConcreteParentNonFoo2: Parent { typealias T = Float } protocol SecondParent { associatedtype U } struct ConcreteSecondParent: SecondParent { typealias U = Int } struct ConcreteSecondParent2: SecondParent { typealias U = Int } struct ConcreteSecondParentNonFoo2: SecondParent { typealias U = Float } protocol Conforms: Parent where T: Foo {} extension Conforms { func foo(_: T) {} } func needsConforms<X: Conforms>(_: X.Type) { needsFoo(X.T.self) } struct ConcreteConforms: Conforms { typealias T = Int } struct BadConcreteConforms: Conforms { // expected-error@-1 {{type 'BadConcreteConforms' does not conform to protocol 'Conforms}} // expected-error@-2 {{type 'BadConcreteConforms.T' (aka 'String') does not conform to protocol 'Foo'}} typealias T = String } protocol SameType: Parent, SecondParent where T == U { } func needsSameTypeProtocol<X: SameType>(_: X.Type) { needsSameType(X.T.self, X.U.self) } struct ConcreteSameType: SameType { typealias T = Int typealias U = Int } struct BadConcreteSameType: SameType { // expected-error@-1 {{type 'BadConcreteSameType' does not conform to protocol 'SameType'}} // expected-error@-2 {{'SameType' requires the types 'BadConcreteSameType.T' (aka 'Int') and 'BadConcreteSameType.U' (aka 'Float') be equivalent}} // expected-note@-3 {{requirement specified as 'Self.T' == 'Self.U' [with Self = BadConcreteSameType]}} typealias T = Int typealias U = Float } // <rdar://problem/31041997> Some where-clause requirements aren't checked on conforming types protocol NestedConforms: SecondParent where U: Parent, U.T: Foo2 {} func needsNestedConforms<X: NestedConforms>(_: X.Type) { needsParent(X.U.self) needsFoo2(X.U.T.self) } struct ConcreteNestedConforms: NestedConforms { typealias U = ConcreteParent } struct BadConcreteNestedConforms: NestedConforms { // expected-error@-1 {{type 'BadConcreteNestedConforms' does not conform to protocol 'NestedConforms'}} // expected-error@-2 {{type 'ConcreteParentNonFoo2.T' (aka 'Float') does not conform to protocol 'Foo2'}} typealias U = ConcreteParentNonFoo2 } // https://github.com/apple/swift/issues/47270 protocol P1 {} struct X: P1 {} struct Y<T: P1> {} protocol P2 { associatedtype AT } protocol P3: P2 where AT == Y<X> {}
apache-2.0
b7e6b7f7e45abb8c0626883d2a754fc7
31.321429
148
0.726703
3.544386
false
false
false
false
IngmarStein/swift
test/SILGen/objc_generic_class.swift
3
1796
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s // REQUIRES: objc_interop import gizmo // Although we don't ever expose initializers and methods of generic classes // to ObjC yet, a generic subclass of an ObjC class must still use ObjC // deallocation. // CHECK-NOT: sil hidden @_TFCSo7Genericd // CHECK-NOT: sil hidden @_TFCSo8NSObjectd class Generic<T>: NSObject { var x: Int = 10 // CHECK-LABEL: sil hidden @_TFC18objc_generic_class7GenericD : $@convention(method) <T> (@owned Generic<T>) -> () { // CHECK: bb0({{%.*}} : $Generic<T>): // CHECK-LABEL: sil hidden [thunk] @_TToFC18objc_generic_class7GenericD : $@convention(objc_method) <T> (Generic<T>) -> () { // CHECK: bb0([[SELF:%.*]] : $Generic<T>): // CHECK: [[NATIVE:%.*]] = function_ref @_TFC18objc_generic_class7GenericD // CHECK: apply [[NATIVE]]<T>([[SELF]]) deinit { // Don't blow up when 'self' is referenced inside an @objc deinit method // of a generic class. <rdar://problem/16325525> self.x = 0 } } // CHECK-NOT: sil hidden @_TFC18objc_generic_class7Genericd // CHECK-NOT: sil hidden @_TFCSo8NSObjectd // CHECK-LABEL: sil hidden @_TFC18objc_generic_class11SubGeneric1D : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () { // CHECK: bb0([[SELF:%.*]] : $SubGeneric1<U, V>): // CHECK: [[SUPER_DEALLOC:%.*]] = super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.foreign : <T> (Generic<T>) -> () -> () , $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> () // CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int> // CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]]) class SubGeneric1<U, V>: Generic<Int> { }
apache-2.0
76b4d8b96c033b9f9fdb1f80157e5459
43.85
211
0.623188
3.255898
false
false
false
false
reproio/firefox-ios
Client/Frontend/Browser/SearchViewController.swift
10
30923
/* 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 UIKit import Shared import Storage private let PromptMessage = NSLocalizedString("Turn on search suggestions?", tableName: "Search", comment: "Prompt shown before enabling provider search queries") private let PromptYes = NSLocalizedString("Yes", tableName: "Search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.") private let PromptNo = NSLocalizedString("No", tableName: "Search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.") private enum SearchListSection: Int { case SearchSuggestions case BookmarksAndHistory static let Count = 2 } private struct SearchViewControllerUX { static let SearchEngineScrollViewBackgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8).CGColor static let SearchEngineScrollViewBorderColor = UIColor.blackColor().colorWithAlphaComponent(0.2).CGColor // TODO: This should use ToolbarHeight in BVC. Fix this when we create a shared theming file. static let EngineButtonHeight: Float = 44 static let EngineButtonWidth = EngineButtonHeight * 1.4 static let EngineButtonBackgroundColor = UIColor.clearColor().CGColor static let SearchImage = "search" static let SearchEngineTopBorderWidth = 0.5 static let SearchImageHeight: Float = 44 static let SearchImageWidth: Float = 24 static let SuggestionBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.8) static let SuggestionBorderColor = UIConstants.HighlightBlue static let SuggestionBorderWidth: CGFloat = 1 static let SuggestionCornerRadius: CGFloat = 4 static let SuggestionFont = UIFont.systemFontOfSize(13, weight: UIFontWeightRegular) static let SuggestionInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) static let SuggestionMargin: CGFloat = 8 static let SuggestionCellVerticalPadding: CGFloat = 10 static let SuggestionCellMaxRows = 2 static let PromptColor = UIConstants.PanelBackgroundColor static let PromptFont = UIFont.systemFontOfSize(12, weight: UIFontWeightRegular) static let PromptYesFont = UIFont.systemFontOfSize(15, weight: UIFontWeightBold) static let PromptNoFont = UIFont.systemFontOfSize(15, weight: UIFontWeightRegular) static let PromptInsets = UIEdgeInsets(top: 15, left: 12, bottom: 15, right: 12) static let PromptButtonColor = UIColor(rgb: 0x007aff) } protocol SearchViewControllerDelegate: class { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) func presentSearchSettingsController() } class SearchViewController: SiteTableViewController, KeyboardHelperDelegate, LoaderListener { var searchDelegate: SearchViewControllerDelegate? private var suggestClient: SearchSuggestClient? // Views for displaying the bottom scrollable search engine list. searchEngineScrollView is the // scrollable container; searchEngineScrollViewContent contains the actual set of search engine buttons. private let searchEngineScrollView = ButtonScrollView() private let searchEngineScrollViewContent = UIView() private lazy var defaultIcon: UIImage = { return UIImage(named: "defaultFavicon")! }() // Cell for the suggestion flow layout. Since heightForHeaderInSection is called *before* // cellForRowAtIndexPath, we create the cell to find its height before it's added to the table. private let suggestionCell = SuggestionCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) private var suggestionPrompt: UIView? convenience init() { self.init(nibName: nil, bundle: nil) } required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { view.backgroundColor = UIConstants.PanelBackgroundColor let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) view.addSubview(blur) super.viewDidLoad() KeyboardHelper.defaultHelper.addDelegate(self) searchEngineScrollView.layer.backgroundColor = SearchViewControllerUX.SearchEngineScrollViewBackgroundColor searchEngineScrollView.layer.shadowRadius = 0 searchEngineScrollView.layer.shadowOpacity = 100 searchEngineScrollView.layer.shadowOffset = CGSize(width: 0, height: -SearchViewControllerUX.SearchEngineTopBorderWidth) searchEngineScrollView.layer.shadowColor = SearchViewControllerUX.SearchEngineScrollViewBorderColor searchEngineScrollView.clipsToBounds = false searchEngineScrollView.decelerationRate = UIScrollViewDecelerationRateFast view.addSubview(searchEngineScrollView) searchEngineScrollViewContent.layer.backgroundColor = UIColor.clearColor().CGColor searchEngineScrollView.addSubview(searchEngineScrollViewContent) layoutTable() layoutSearchEngineScrollView() searchEngineScrollViewContent.snp_makeConstraints { make in make.center.equalTo(self.searchEngineScrollView).priorityLow() //left-align the engines on iphones, center on ipad if(UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact) { make.left.equalTo(self.searchEngineScrollView).priorityHigh() } else { make.left.greaterThanOrEqualTo(self.searchEngineScrollView).priorityHigh() } make.right.lessThanOrEqualTo(self.searchEngineScrollView).priorityHigh() make.top.equalTo(self.searchEngineScrollView) make.bottom.equalTo(self.searchEngineScrollView) } blur.snp_makeConstraints { make in make.edges.equalTo(self.view) } suggestionCell.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadSearchEngines() reloadData() } private func layoutSearchEngineScrollView() { let keyboardHeight = KeyboardHelper.defaultHelper.currentState?.intersectionHeightForView(self.view) ?? 0 searchEngineScrollView.snp_remakeConstraints { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.view).offset(-keyboardHeight) } } var searchEngines: SearchEngines! { didSet { suggestClient?.cancelPendingRequest() // Query and reload the table with new search suggestions. querySuggestClient() // Show the default search engine first. suggestClient = SearchSuggestClient(searchEngine: searchEngines.defaultEngine) // Reload the footer list of search engines. reloadSearchEngines() layoutSuggestionsOptInPrompt() } } private func layoutSuggestionsOptInPrompt() { if !(searchEngines?.shouldShowSearchSuggestionsOptIn ?? false) { // Make sure any pending layouts are drawn so they don't get coupled // with the "slide up" animation below. view.layoutIfNeeded() // Set the prompt to nil so layoutTable() aligns the top of the table // to the top of the view. We still need a reference to the prompt so // we can remove it from the controller after the animation is done. let prompt = suggestionPrompt suggestionPrompt = nil layoutTable() UIView.animateWithDuration(0.2, animations: { self.view.layoutIfNeeded() prompt?.alpha = 0 }, completion: { _ in prompt?.removeFromSuperview() return }) return } let prompt = UIView() prompt.backgroundColor = SearchViewControllerUX.PromptColor let promptBottomBorder = UIView() promptBottomBorder.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.1) prompt.addSubview(promptBottomBorder) // Insert behind the tableView so the tableView slides on top of it // when the prompt is dismissed. view.insertSubview(prompt, belowSubview: tableView) suggestionPrompt = prompt let promptImage = UIImageView() promptImage.image = UIImage(named: SearchViewControllerUX.SearchImage) prompt.addSubview(promptImage) let promptLabel = UILabel() promptLabel.text = PromptMessage promptLabel.font = SearchViewControllerUX.PromptFont promptLabel.numberOfLines = 0 promptLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping prompt.addSubview(promptLabel) let promptYesButton = InsetButton() promptYesButton.setTitle(PromptYes, forState: UIControlState.Normal) promptYesButton.setTitleColor(SearchViewControllerUX.PromptButtonColor, forState: UIControlState.Normal) promptYesButton.titleLabel?.font = SearchViewControllerUX.PromptYesFont promptYesButton.titleEdgeInsets = SearchViewControllerUX.PromptInsets // If the prompt message doesn't fit, this prevents it from pushing the buttons // off the row and makes it wrap instead. promptYesButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) promptYesButton.addTarget(self, action: "SELdidClickOptInYes", forControlEvents: UIControlEvents.TouchUpInside) prompt.addSubview(promptYesButton) let promptNoButton = InsetButton() promptNoButton.setTitle(PromptNo, forState: UIControlState.Normal) promptNoButton.setTitleColor(SearchViewControllerUX.PromptButtonColor, forState: UIControlState.Normal) promptNoButton.titleLabel?.font = SearchViewControllerUX.PromptNoFont promptNoButton.titleEdgeInsets = SearchViewControllerUX.PromptInsets // If the prompt message doesn't fit, this prevents it from pushing the buttons // off the row and makes it wrap instead. promptNoButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) promptNoButton.addTarget(self, action: "SELdidClickOptInNo", forControlEvents: UIControlEvents.TouchUpInside) prompt.addSubview(promptNoButton) // otherwise the label (i.e. question) is visited by VoiceOver *after* yes and no buttons prompt.accessibilityElements = [promptImage, promptLabel, promptYesButton, promptNoButton] promptImage.snp_makeConstraints { make in make.left.equalTo(prompt).offset(SearchViewControllerUX.PromptInsets.left) make.centerY.equalTo(prompt) } promptLabel.snp_makeConstraints { make in make.left.equalTo(promptImage.snp_right).offset(SearchViewControllerUX.PromptInsets.left) let insets = SearchViewControllerUX.PromptInsets make.top.equalTo(prompt).inset(insets.top) make.bottom.equalTo(prompt).inset(insets.bottom) make.right.lessThanOrEqualTo(promptYesButton.snp_left) return } promptNoButton.snp_makeConstraints { make in make.right.equalTo(prompt).inset(SearchViewControllerUX.PromptInsets.right) make.centerY.equalTo(prompt) } promptYesButton.snp_makeConstraints { make in make.right.equalTo(promptNoButton.snp_left).inset(SearchViewControllerUX.PromptInsets.right) make.centerY.equalTo(prompt) } promptBottomBorder.snp_makeConstraints { make in make.trailing.leading.equalTo(self.view) make.top.equalTo(prompt.snp_bottom).offset(-1) make.height.equalTo(1) } prompt.snp_makeConstraints { make in make.top.leading.trailing.equalTo(self.view) } layoutTable() } var searchQuery: String = "" { didSet { // Reload the tableView to show the updated text in each engine. reloadData() } } override func reloadData() { querySuggestClient() } private func layoutTable() { tableView.snp_remakeConstraints { make in make.top.equalTo(self.suggestionPrompt?.snp_bottom ?? self.view.snp_top) make.leading.trailing.equalTo(self.view) make.bottom.equalTo(self.searchEngineScrollView.snp_top) } } private func reloadSearchEngines() { searchEngineScrollViewContent.subviews.forEach { $0.removeFromSuperview() } var leftEdge = searchEngineScrollViewContent.snp_left //search settings icon let searchButton = UIButton() searchButton.setImage(UIImage(named: "quickSearch"), forState: UIControlState.Normal) searchButton.imageView?.contentMode = UIViewContentMode.Center searchButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor searchButton.addTarget(self, action: "SELdidClickSearchButton", forControlEvents: UIControlEvents.TouchUpInside) searchButton.accessibilityLabel = String(format: NSLocalizedString("Search Settings", tableName: "Search", comment: "Label for search settings button.")) searchButton.imageView?.snp_makeConstraints { make in make.width.height.equalTo(SearchViewControllerUX.SearchImageWidth) return } searchEngineScrollViewContent.addSubview(searchButton) searchButton.snp_makeConstraints { make in make.width.equalTo(SearchViewControllerUX.SearchImageWidth) make.height.equalTo(SearchViewControllerUX.SearchImageHeight) //offset the left edge to align with search results make.left.equalTo(leftEdge).offset(SearchViewControllerUX.PromptInsets.left) make.top.equalTo(self.searchEngineScrollViewContent) make.bottom.equalTo(self.searchEngineScrollViewContent) } //search engines leftEdge = searchButton.snp_right for engine in searchEngines.quickSearchEngines { let engineButton = UIButton() engineButton.setImage(engine.image, forState: UIControlState.Normal) engineButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit engineButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor engineButton.addTarget(self, action: "SELdidSelectEngine:", forControlEvents: UIControlEvents.TouchUpInside) engineButton.accessibilityLabel = String(format: NSLocalizedString("%@ search", tableName: "Search", comment: "Label for search engine buttons. The argument corresponds to the name of the search engine."), engine.shortName) engineButton.imageView?.snp_makeConstraints { make in make.width.height.equalTo(OpenSearchEngine.PreferredIconSize) return } searchEngineScrollViewContent.addSubview(engineButton) engineButton.snp_makeConstraints { make in make.width.equalTo(SearchViewControllerUX.EngineButtonWidth) make.height.equalTo(SearchViewControllerUX.EngineButtonHeight) make.left.equalTo(leftEdge) make.top.equalTo(self.searchEngineScrollViewContent) make.bottom.equalTo(self.searchEngineScrollViewContent) if engine === self.searchEngines.quickSearchEngines.last { make.right.equalTo(self.searchEngineScrollViewContent) } } leftEdge = engineButton.snp_right } } func SELdidSelectEngine(sender: UIButton) { // The UIButtons are the same cardinality and order as the array of quick search engines for i in 0..<searchEngineScrollViewContent.subviews.count { if let button = searchEngineScrollViewContent.subviews[i] as? UIButton { if button === sender { //subtract 1 from index to account for magnifying glass accessory if let url = searchEngines.quickSearchEngines[i-1].searchURLForQuery(searchQuery) { searchDelegate?.searchViewController(self, didSelectURL: url) } } } } } func SELdidClickSearchButton() { self.searchDelegate?.presentSearchSettingsController() } func SELdidClickOptInYes() { searchEngines.shouldShowSearchSuggestions = true searchEngines.shouldShowSearchSuggestionsOptIn = false querySuggestClient() layoutSuggestionsOptInPrompt() } func SELdidClickOptInNo() { searchEngines.shouldShowSearchSuggestions = false searchEngines.shouldShowSearchSuggestionsOptIn = false layoutSuggestionsOptInPrompt() } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { animateSearchEnginesWithKeyboard(state) } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { animateSearchEnginesWithKeyboard(state) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // The height of the suggestions row may change, so call reloadData() to recalculate cell heights. coordinator.animateAlongsideTransition({ _ in self.tableView.reloadData() }, completion: nil) } private func animateSearchEnginesWithKeyboard(keyboardState: KeyboardState) { layoutSearchEngineScrollView() UIView.animateWithDuration(keyboardState.animationDuration, animations: { UIView.setAnimationCurve(keyboardState.animationCurve) self.view.layoutIfNeeded() }) } private func querySuggestClient() { suggestClient?.cancelPendingRequest() if searchQuery.isEmpty || !searchEngines.shouldShowSearchSuggestions || searchQuery.looksLikeAURL() { suggestionCell.suggestions = [] tableView.reloadData() return } suggestClient?.query(searchQuery, callback: { suggestions, error in if let error = error { let isSuggestClientError = error.domain == SearchSuggestClientErrorDomain switch error.code { case NSURLErrorCancelled where error.domain == NSURLErrorDomain: // Request was cancelled. Do nothing. break case SearchSuggestClientErrorInvalidEngine where isSuggestClientError: // Engine does not support search suggestions. Do nothing. break case SearchSuggestClientErrorInvalidResponse where isSuggestClientError: print("Error: Invalid search suggestion data") default: print("Error: \(error.description)") } } else { self.suggestionCell.suggestions = suggestions! } // If there are no suggestions, just use whatever the user typed. if suggestions?.isEmpty ?? true { self.suggestionCell.suggestions = [self.searchQuery] } // Reload the tableView to show the new list of search suggestions. self.tableView.reloadData() }) } func loader(dataLoaded data: Cursor<Site>) { self.data = data tableView.reloadData() } } extension SearchViewController { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let section = SearchListSection(rawValue: indexPath.section)! if section == SearchListSection.BookmarksAndHistory { if let site = data[indexPath.row] { if let url = NSURL(string: site.url) { searchDelegate?.searchViewController(self, didSelectURL: url) } } } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if let currentSection = SearchListSection(rawValue: indexPath.section) { switch currentSection { case .SearchSuggestions: // heightForRowAtIndexPath is called *before* the cell is created, so to get the height, // force a layout pass first. suggestionCell.layoutIfNeeded() return suggestionCell.frame.height default: return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } return 0 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } } extension SearchViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch SearchListSection(rawValue: indexPath.section)! { case .SearchSuggestions: suggestionCell.imageView?.image = searchEngines.defaultEngine.image suggestionCell.imageView?.isAccessibilityElement = true suggestionCell.imageView?.accessibilityLabel = String(format: NSLocalizedString("Search suggestions from %@", tableName: "Search", comment: "Accessibility label for image of default search engine displayed left to the actual search suggestions from the engine. The parameter substituted for \"%@\" is the name of the search engine. E.g.: Search suggestions from Google"), searchEngines.defaultEngine.shortName) return suggestionCell case .BookmarksAndHistory: let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if let site = data[indexPath.row] { if let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView?.setIcon(site.icon, withPlaceholder: self.defaultIcon) } } return cell } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch SearchListSection(rawValue: section)! { case .SearchSuggestions: return searchEngines.shouldShowSearchSuggestions && !searchQuery.looksLikeAURL() ? 1 : 0 case .BookmarksAndHistory: return data.count } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return SearchListSection.Count } } extension SearchViewController: SuggestionCellDelegate { private func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) { var url = URIFixup().getURL(suggestion) if url == nil { // Assume that only the default search engine can provide search suggestions. url = searchEngines?.defaultEngine.searchURLForQuery(suggestion) } if let url = url { searchDelegate?.searchViewController(self, didSelectURL: url) } } } /** * Private extension containing string operations specific to this view controller */ private extension String { func looksLikeAURL() -> Bool { // The assumption here is that if the user is typing in a forward slash and there are no spaces // involved, it's going to be a URL. If we type a space, any url would be invalid. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1192155 for additional details. return self.contains("/") && !self.contains(" ") } } /** * UIScrollView that prevents buttons from interfering with scroll. */ private class ButtonScrollView: UIScrollView { private override func touchesShouldCancelInContentView(view: UIView) -> Bool { return true } } private protocol SuggestionCellDelegate: class { func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) } /** * Cell that wraps a list of search suggestion buttons. */ private class SuggestionCell: UITableViewCell { weak var delegate: SuggestionCellDelegate? let container = UIView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) isAccessibilityElement = false accessibilityLabel = nil layoutMargins = UIEdgeInsetsZero separatorInset = UIEdgeInsetsZero selectionStyle = UITableViewCellSelectionStyle.None container.backgroundColor = UIColor.clearColor() contentView.backgroundColor = UIColor.clearColor() backgroundColor = UIColor.clearColor() contentView.addSubview(container) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var suggestions: [String] = [] { didSet { for view in container.subviews { view.removeFromSuperview() } for suggestion in suggestions { let button = SuggestionButton() button.setTitle(suggestion, forState: UIControlState.Normal) button.addTarget(self, action: "SELdidSelectSuggestion:", forControlEvents: UIControlEvents.TouchUpInside) // If this is the first image, add the search icon. if container.subviews.isEmpty { let image = UIImage(named: SearchViewControllerUX.SearchImage) button.setImage(image, forState: UIControlState.Normal) button.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0) } container.addSubview(button) } setNeedsLayout() } } @objc func SELdidSelectSuggestion(sender: UIButton) { delegate?.suggestionCell(self, didSelectSuggestion: sender.titleLabel!.text!) } private override func layoutSubviews() { super.layoutSubviews() // The left bounds of the suggestions, aligned with where text would be displayed. let textLeft: CGFloat = 48 // The maximum width of the container, after which suggestions will wrap to the next line. let maxWidth = contentView.frame.width let imageSize = CGFloat(OpenSearchEngine.PreferredIconSize) // The height of the suggestions container (minus margins), used to determine the frame. // We set it to imageSize.height as a minimum since we don't want the cell to be shorter than the icon var height: CGFloat = imageSize var currentLeft = textLeft var currentTop = SearchViewControllerUX.SuggestionCellVerticalPadding var currentRow = 0 for view in container.subviews { let button = view as! UIButton var buttonSize = button.intrinsicContentSize() // Update our base frame height by the max size of either the image or the button so we never // make the cell smaller than any of the two if height == imageSize { height = max(buttonSize.height, imageSize) } var width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin if width > maxWidth { // Only move to the next row if there's already a suggestion on this row. // Otherwise, the suggestion is too big to fit and will be resized below. if currentLeft > textLeft { currentRow++ if currentRow >= SearchViewControllerUX.SuggestionCellMaxRows { // Don't draw this button if it doesn't fit on the row. button.frame = CGRectZero continue } currentLeft = textLeft currentTop += buttonSize.height + SearchViewControllerUX.SuggestionMargin height += buttonSize.height + SearchViewControllerUX.SuggestionMargin width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin } // If the suggestion is too wide to fit on its own row, shrink it. if width > maxWidth { buttonSize.width = maxWidth - currentLeft - SearchViewControllerUX.SuggestionMargin } } button.frame = CGRectMake(currentLeft, currentTop, buttonSize.width, buttonSize.height) currentLeft += buttonSize.width + SearchViewControllerUX.SuggestionMargin } frame.size.height = height + 2 * SearchViewControllerUX.SuggestionCellVerticalPadding contentView.frame = frame container.frame = frame let imageX = (48 - imageSize) / 2 let imageY = (frame.size.height - imageSize) / 2 imageView!.frame = CGRectMake(imageX, imageY, imageSize, imageSize) } } /** * Rounded search suggestion button that highlights when selected. */ private class SuggestionButton: InsetButton { override init(frame: CGRect) { super.init(frame: frame) setTitleColor(UIConstants.HighlightBlue, forState: UIControlState.Normal) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted) titleLabel?.font = SearchViewControllerUX.SuggestionFont backgroundColor = SearchViewControllerUX.SuggestionBackgroundColor layer.borderColor = SearchViewControllerUX.SuggestionBorderColor.CGColor layer.borderWidth = SearchViewControllerUX.SuggestionBorderWidth layer.cornerRadius = SearchViewControllerUX.SuggestionCornerRadius contentEdgeInsets = SearchViewControllerUX.SuggestionInsets accessibilityHint = NSLocalizedString("Searches for the suggestion", comment: "Accessibility hint describing the action performed when a search suggestion is clicked") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc override var highlighted: Bool { didSet { backgroundColor = highlighted ? UIConstants.HighlightBlue : SearchViewControllerUX.SuggestionBackgroundColor } } }
mpl-2.0
ff6a8ceb7c90af48ec218120855c2f87
42.370266
422
0.681338
5.59591
false
false
false
false
zjjzmw1/robot
robot/robot/Macro/UtilMacros.swift
1
760
// // UtilMacros.swift // ZMWJoke // // Created by xiaoming on 16/9/3. // Copyright © 2016年 shandandan. All rights reserved. // import Foundation import UIKit // iOS系统版本 let IS_IOS7 = (UIDevice.current.systemVersion as NSString).doubleValue >= 7.0 let IS_IOS8 = (UIDevice.current.systemVersion as NSString).doubleValue >= 8.0 let IS_IOS9 = (UIDevice.current.systemVersion as NSString).doubleValue >= 9.0 let IS_IOS10 = (UIDevice.current.systemVersion as NSString).doubleValue >= 10.0 /// 获取字体的方法 public func FONT_PingFang(fontSize: CGFloat) -> UIFont { var font = UIFont.init(name: "PingFangSC-Regular", size: fontSize) if !IS_IOS9 { font = UIFont.init(name: "Helvetica", size: fontSize) } return font! }
mit
abdbeb1fff19997bef151958acd07a77
29.625
79
0.706122
3.37156
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
03-YFPageViewExtensionDemo/YFPageViewExtensionDemo/YFPageView/YFPageStyle.swift
1
800
// // YFPageStyle.swift // YFPageViewDemo // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit class YFPageStyle { var titleViewHeight : CGFloat = 44 var normalColor : UIColor = UIColor(r: 0, g: 0, b: 0) var selectColor : UIColor = UIColor(r: 255, g: 127, b: 0) var fontSize : CGFloat = 15 var titleFont : UIFont = UIFont.systemFont(ofSize: 15.0) //是否滚动 var isScrollEnable : Bool = false //间距 var itemMargin : CGFloat = 20 var isShowBottomLine : Bool = true var bottomLineColor : UIColor = UIColor.orange var bottomLineHeight : CGFloat = 2 //YFPageCollectionView ///title的高度 var titleHeight : CGFloat = 44 }
mit
65ba438e92082d14b24de97cd6da9597
18.974359
61
0.614891
4.1
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/GalleryMenuItem.swift
1
2193
// // GalleryMenuItem.swift // DingshanSwift // // Created by song jufeng on 15/9/6. // Copyright (c) 2015年 song jufeng. All rights reserved. // import Foundation class GalleryMenuItem:UIButton { let borderColorNormal = UIColor(white: 151/255.0, alpha: 1.0) let titleColorNormal = UIColor(white: 160/255.0, alpha: 1.0) let borderColorHighLighted = UIColor(red: 252/255.0, green: 74/255.0, blue: 100/255.0, alpha: 1.0) let titleColorHighLighted = UIColor(red: 252/255.0, green: 74/255.0, blue: 100/255.0, alpha: 1.0) var container:UIView? var keyName = String() var curSelected:Bool = false{ didSet{ if (curSelected){ self.setTitleColor(titleColorHighLighted, forState: UIControlState.Normal) container?.layer.borderColor = borderColorHighLighted.CGColor }else{ self.setTitleColor(titleColorNormal, forState: UIControlState.Normal) container?.layer.borderColor = borderColorNormal.CGColor } } } override internal var highlighted:Bool{ didSet{ if (highlighted){ container?.layer.borderColor = borderColorHighLighted.CGColor }else{ container?.layer.borderColor = borderColorNormal.CGColor } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame aRect: CGRect) { super.init(frame: aRect); container = UIView(frame: CGRect(x: (frame.size.width-frame.size.width*96.0/160.0)/2.0, y: frame.size.height*(1.0 - 50.0/80.0)/2.0, width: frame.size.width*96.0/160.0, height: frame.size.height*50.0/80.0)) self.addSubview(container!) container?.userInteractionEnabled = false container?.backgroundColor = UIColor.clearColor() container?.layer.cornerRadius = 3.0; container?.layer.borderWidth = 0.5; self.setTitleColor(titleColorNormal, forState: UIControlState.Normal) self.setTitleColor(titleColorHighLighted, forState: UIControlState.Highlighted) self.titleLabel?.font = UIFont.systemFontOfSize(13.0) } }
mit
9b4812a7beb46c5adb9e7f18973e5367
40.358491
213
0.648106
4.049908
false
false
false
false
pascaljette/PokeBattleDemo
PokeBattleDemo/PokeBattleDemo/PokeApi/Fetchers/RandomPokemonFetcher.swift
1
3989
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // 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 /// Delegate for a fetcher that retrieves a single random pokemon. protocol RandomPokemonFetcherDelegate: class { /// Did get random pokemon from the fetcher. /// /// - parameter success: Whether the list retrieval succeeded. /// - parameter result: Retrieved list or nil on failure. /// - parameter error: Error object or nil on failure. func didGetPokemon(success: Bool, result: Pokemon?, error: NSError?) } /// Fetcher that retrieves a single random pokemon. class RandomPokemonFetcher : PokemonFetcherProtocol { // // MARK: PokemonFetcherProtocol implementation // /// Request type typealias RequestType = GetPokemonRequest /// Response type typealias ResponseType = GetPokemonResponse // // MARK: Stored properties // /// Weak reference on the delegate. weak var delegate: RandomPokemonFetcherDelegate? // TODO: AllPokemonList stays immutable for the whole lifecycle of the application. // Consider making it a singleton to avoid passing it all the time. /// List of all available pokemon from which to retrieve a single detailed one. private var allPokemonList: AllPokemonList // // MARK: Initialisation // /// Initialise with the list of available pokemon. /// /// - parameter allPokemonList: List of all available pokemon (and their URLs) init(allPokemonList: AllPokemonList) { self.allPokemonList = allPokemonList } } extension RandomPokemonFetcher { // // MARK: Public functions // /// Fetch the data and calls the delegate on completion. func fetch() { let pokemonUrl = allPokemonList.pokemonUrlStrings[Int(arc4random_uniform(UInt32(allPokemonList.pokemonUrlStrings.count)))] let call: ConnectionType = ConnectionType() let getPokemonRequest = GetPokemonRequest(fullUrl: pokemonUrl) call.onCompletion = { [weak self] (status, error, response) in guard let strongSelf = self else { return } switch status { case .Success: strongSelf.delegate?.didGetPokemon(true, result: response!.model, error: nil) // Cache the types right now. PokemonTypeCache.sharedInstance.downloadAndCacheMultiple(response!.model.types) case .ConnectionError: strongSelf.delegate?.didGetPokemon(false, result: nil, error: error) case .UrlError: strongSelf.delegate?.didGetPokemon(false, result: nil, error: error) } } call.execute(getPokemonRequest) } }
mit
fa604568c5473cbd329c4d6990245395
33.686957
130
0.65831
5.023929
false
false
false
false
ianrahman/HackerRankChallenges
Swift/Algorithms/Warmup/time-conversion.swift
1
659
import Foundation // Read input let s = readLine()! // separate components var timeArr = s.components(separatedBy: ":") // find time period let index = timeArr[2].index(timeArr[2].startIndex, offsetBy: 2) let period = timeArr[2].substring(from: index) // assign component variables var hours = timeArr[0] let minutes = timeArr[1] let seconds = timeArr[2].substring(to: index) // adjust hours and remove period from seconds switch period { case "AM": if Int(hours)! == 12 { hours = "00" } default: if Int(hours)! != 12 { hours = String(Int(hours)! + 12) } } // recombine components print("\(hours):\(minutes):\(seconds)")
mit
d5bde179c0fe0cf3145baaefee21b9db
20.258065
64
0.657056
3.432292
false
false
false
false
arn00s/cariocamenu
CariocaMenuDemo/DemoControllers/DemoIdeaViewController.swift
1
1770
import UIKit import WebKit class DemoIdeaViewController: UIViewController, DemoController, UIWebViewDelegate { @IBOutlet weak var webview: WKWebView! @IBOutlet weak var loader: UIActivityIndicatorView! @IBOutlet weak var errorMessage: UILabel! @IBOutlet weak var tryAgain: UIButton! weak var menuController: CariocaController? override func viewWillAppear(_ animated: Bool) { self.view.addCariocaGestureHelpers([.left, .right]) } override func viewDidLoad() { loader.hidesWhenStopped = true loader.stopAnimating() } override func viewDidAppear(_ animated: Bool) { self.loadURL() } func loadURL() { guard let url = URL(string: "https://medium.com/search?q=Hamburger%20menu") else { return } errorMessage.isHidden = true tryAgain.isHidden = true webview.load(URLRequest(url: url)) } func webViewDidStartLoad(_ webView: UIWebView) { loader.startAnimating() } func webViewDidFinishLoad(_ webView: UIWebView) { webview.scrollView.isScrollEnabled = true loader.stopAnimating() } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { webview.scrollView.isScrollEnabled = false loader.stopAnimating() webview.isHidden = true errorMessage.isHidden = false tryAgain.isHidden = false } @IBAction func tryAgainAction(_ sender: AnyObject) { loadURL() } override func viewDidDisappear(_ animated: Bool) { cleanWebView() menuController = nil } private func cleanWebView() { webview.loadHTMLString("", baseURL: nil) webview.stopLoading() webview.removeFromSuperview() webview = nil } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func didReceiveMemoryWarning() { cleanWebView() } }
mit
cb1388314473e60fc16f563b809ad54f
27.548387
93
0.725989
4.306569
false
false
false
false
jordanhamill/SwiftyJSONMilk
SwiftyJSONMilkTests/ExampleTest.swift
1
1706
import Quick import Nimble import SwiftyJSON @testable import SwiftyJSONMilk class ExampleTest: QuickSpec { override func spec() { describe("when serializing a github single repository to JSON") { let serializer = JSONSerializer() beforeEach { let owner = GitHubProfile(id: 122094, url: NSURL(string: "https://github.com/jordanhamill")!, login: "jordanhamill", avatarURL: NSURL(string: "https://github.com/jordanhamill/avatar.png")!) let repo = GitHubRepository(id: 99345, url: NSURL(string: "https://github.com/jordanhamill/repos/milk")!, owner: owner) repo.serialize(serializer) } it("has the correct repo id") { expect(serializer.json["id"].int) == 99345 } it("has the correct repo url") { expect(serializer.json["url"].string) == "https://github.com/jordanhamill/repos/milk" } it("has the correct owner id") { expect(serializer.json["owner"]["id"].int) == 122094 } it("has the correct owner url") { expect(serializer.json["owner"]["url"].string) == "https://github.com/jordanhamill" } it("has the correct owner login name") { expect(serializer.json["owner"]["login"].string) == "jordanhamill" } it("has the correct owner avatar url") { expect(serializer.json["owner"]["avatar"].string) == "https://github.com/jordanhamill/avatar.png" } } } }
mit
198786572cfeec930c7954b6be1b6013
32.45098
113
0.531067
4.408269
false
false
false
false
Dsternheim/Pokedex
Pokedex/Pokemon.swift
1
8359
// // Pokemon.swift // Pokedex // // Created by David Sternheim on 8/7/17. // Copyright © 2017 David Sternheim. All rights reserved. // import Foundation import Alamofire class Pokemon{ private var _name: String! private var _pokedexID: Int! private var _description: String! private var _type: String! private var _defense: String! private var _attack: String! private var _height: String! private var _weight: String! private var _nextEvolutionTxt: String! private var _pokemonURL: String! private var _nextEvolutionName: String! private var _nextEvolutionID: String! private var _nextEvolutionLvl: String! var nextEvolutionName: String { if _nextEvolutionName == nil { _nextEvolutionName = "" } return _nextEvolutionName } var nextEvolutionID: String { if _nextEvolutionID == nil { _nextEvolutionID = "" } return _nextEvolutionID } var nextEvolutionLvl: String { if _nextEvolutionLvl == nil { _nextEvolutionLvl = "" } return _nextEvolutionLvl } var name: String{ return _name } var pokedexID: Int{ return _pokedexID } var nextEvolutionTxt: String { if _nextEvolutionTxt == nil { _nextEvolutionTxt = "" } return _nextEvolutionTxt } var type: String { if _type == nil { _type = "" } return _type } var description: String { if _description == nil { _description = "" } return _description } var defense: String { if _defense == nil { _defense = "" } return _defense } var attack: String { if _attack == nil { _attack = "" } return _attack } var height: String { if _height == nil { _height = "" } return _height } var weight: String { if _weight == nil { _weight = "" } return _weight } init(name: String, pokedexID: Int) { self._name=name self._pokedexID=pokedexID self._pokemonURL="\(URL_BASE)\(URL_POKEMON)\(self.pokedexID)/" } func downloadPokemonDetails(completed:@escaping DownloadComplete) { Alamofire.request(_pokemonURL).responseJSON { response in if let dict = response.result.value as? Dictionary<String, AnyObject> { if let weight = dict["weight"] as? String { self._weight = weight } if let height = dict["height"] as? String { self._height = height } if let defense = dict["defense"] as? Int { self._defense = "\(defense)" } if let attack = dict["attack"] as? Int { self._attack = "\(attack)" } if let descArr = dict["descriptions"] as? [Dictionary<String, String>], descArr.count > 0 { if let url = descArr[0]["resource_uri"] { let descURL = "\(URL_BASE)\(url)" Alamofire.request(descURL).responseJSON(completionHandler: { (response) in if let descDict = response.result.value as? Dictionary<String, AnyObject> { if let description = descDict["description"] as? String? { let newDescription = description?.replacingOccurrences(of: "POKMON", with: "Pokemon") self._description = newDescription print(newDescription!) } } completed() }) } } if let types = dict["types"] as? [Dictionary<String, String>], types.count>0 { if let name = types[0]["name"] { self._type = name.capitalized } if types.count > 1 { for x in 1..<types.count { if let name = types[x]["name"] { self._type! += "/\(name.capitalized)" } } } print(self._type) } else{ self._type = "" } print(self._attack) print(self._defense) print(self._height) print(self._weight) //completed() if let evolutions = dict["evolutions"] as? [Dictionary<String, AnyObject>], evolutions.count>0 { if let nextEvolution = evolutions[0]["to"] as? String { if nextEvolution.range(of: "mega") == nil { self._nextEvolutionName = nextEvolution if let uri = evolutions[0]["resource_uri"] as? String { let newStr = uri.replacingOccurrences(of: "/api/v1/pokemon/", with: "") let nextEvoID = newStr.replacingOccurrences(of: "/", with: "") self._nextEvolutionID = nextEvoID if let lvlExist = evolutions[0]["level"] { if let lvl = lvlExist as? Int { self._nextEvolutionLvl = "\(lvl)" } } else { self._nextEvolutionLvl = "" } } } } } } completed() } } }
mit
2cf0406b9eb53cda6ae4298518f42e32
25.788462
121
0.32101
7.059122
false
false
false
false
MaddTheSane/WWDC
WWDC/VideoDetailsViewController.swift
1
7357
// // VideoDetailsViewController.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class VideoDetailsViewController: NSViewController { var videoControllers: [VideoWindowController] = [] var slideControllers: [PDFWindowController] = [] var searchTerm: String? { didSet { updateTranscriptsViewController() } } private var transcriptSearchResultsVC: TranscriptSearchResultsController? @IBOutlet weak var transcriptControllerContainerView: NSView! var selectedCount = 1 var multipleSelection: Bool { get { return selectedCount > 1 } } var session: Session? { didSet { updateUI() } } @IBOutlet weak var titleLabel: NSTextField! @IBOutlet weak var subtitleLabel: NSTextField! @IBOutlet weak var descriptionLabel: NSTextField! @IBOutlet weak var downloadController: DownloadProgressViewController! @IBOutlet weak var actionButtonsController: ActionButtonsViewController! private func updateUI() { if multipleSelection { handleMultipleSelection() return } actionButtonsController.view.hidden = false downloadController.view.hidden = false actionButtonsController.session = session setupActionCallbacks() if let session = self.session { titleLabel.stringValue = session.title subtitleLabel.stringValue = "\(session.track) | Session \(session.id)" descriptionLabel.stringValue = session.summary descriptionLabel.hidden = false downloadController.session = session downloadController.downloadFinishedCallback = { [unowned self] in self.updateUI() } } else { titleLabel.stringValue = "No session selected" subtitleLabel.stringValue = "Select a session to see It here" descriptionLabel.hidden = true downloadController.session = nil } setupTranscriptResultsViewIfNeeded() updateTranscriptsViewController() } private func setupTranscriptResultsViewIfNeeded() { guard transcriptSearchResultsVC == nil else { return } transcriptSearchResultsVC = TranscriptSearchResultsController() transcriptSearchResultsVC!.view.frame = self.transcriptControllerContainerView.bounds transcriptSearchResultsVC!.view.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable] transcriptSearchResultsVC!.playCallback = { [unowned self] time in self.watchVideo(time) } self.transcriptControllerContainerView.addSubview(transcriptSearchResultsVC!.view) } private func updateTranscriptsViewController() { guard let term = searchTerm else { transcriptSearchResultsVC?.lines = nil return } guard term != "" else { transcriptSearchResultsVC?.lines = nil return } transcriptSearchResultsVC?.lines = session?.transcript?.lines.filter("text CONTAINS[c] %@", searchTerm!) } private func handleMultipleSelection() { titleLabel.stringValue = "\(selectedCount) sessions selected" subtitleLabel.stringValue = "" descriptionLabel.hidden = true actionButtonsController.view.hidden = true downloadController.view.hidden = true } private func setupActionCallbacks() { actionButtonsController.watchHDVideoCallback = { [unowned self] in if self.session!.hd_url != nil { if VideoStore.SharedStore().hasVideo(self.session!.hd_url!) { self.doWatchVideo(nil, url: VideoStore.SharedStore().localVideoAbsoluteURLString(self.session!.hd_url!), startTime: nil) } else { self.doWatchVideo(nil, url: self.session!.hd_url!, startTime: nil) } } } actionButtonsController.watchVideoCallback = { [unowned self] in self.doWatchVideo(nil, url: self.session!.videoURL, startTime: nil) } actionButtonsController.showSlidesCallback = { [unowned self] in if self.session!.slidesURL != "" { let slidesWindowController = PDFWindowController(session: self.session!) slidesWindowController.showWindow(nil) self.followWindowLifecycle(slidesWindowController.window) self.slideControllers.append(slidesWindowController) } } actionButtonsController.toggleWatchedCallback = { [unowned self] in WWDCDatabase.sharedDatabase.doChanges { if self.session!.progress < 100 { self.session!.progress = 100 } else { self.session!.progress = 0 } } } actionButtonsController.afterCallback = { [unowned self] in self.actionButtonsController.session = self.session } } private func playerControllerForSession(session: Session) -> VideoWindowController? { let filteredControllers = videoControllers.filter { videoWC in return videoWC.session?.uniqueId == session.uniqueId } return filteredControllers.first } private func watchVideo(startTime: Double) { if let existingController = playerControllerForSession(session!) { existingController.seekTo(startTime) return } if session!.hd_url != nil { if VideoStore.SharedStore().hasVideo(session!.hd_url!) { doWatchVideo(nil, url: VideoStore.SharedStore().localVideoAbsoluteURLString(session!.hd_url!), startTime: startTime) } else { doWatchVideo(nil, url: session!.videoURL, startTime: startTime) } } else { doWatchVideo(nil, url: session!.videoURL, startTime: startTime) } } private func doWatchVideo(sender: AnyObject?, url: String, startTime: Double?) { let playerWindowController = VideoWindowController(session: session!, videoURL: url, startTime: startTime) playerWindowController.showWindow(sender) followWindowLifecycle(playerWindowController.window) videoControllers.append(playerWindowController) } private func followWindowLifecycle(window: NSWindow!) { NSNotificationCenter.defaultCenter().addObserverForName(NSWindowWillCloseNotification, object: window, queue: nil) { note in if let window = note.object as? NSWindow { if let controller = window.windowController as? VideoWindowController { self.videoControllers.remove(controller) } else if let controller = window.windowController as? PDFWindowController { self.slideControllers.remove(controller) } } } } override func viewDidLoad() { super.viewDidLoad() updateUI() } }
bsd-2-clause
8e6511022b9820b675d57b327f49c676
35.063725
140
0.622808
5.628921
false
false
false
false
dsantosp12/DResume
Sources/App/Models/Attachment.swift
1
2466
// // Attachment.swift // App // // Created by Daniel Santos on 10/2/17. // import Vapor import FluentProvider import HTTP final class Attachment: Model { let storage = Storage() let name: String let url: String let addedOn: Date let userID: Identifier? static let nameKey = "name" static let urlKey = "url" static let addedOnKey = "added_on" static let userIDKey = "user_id" init(name: String, url: String, addedOn: Date, user: User ) { self.name = name self.url = url self.addedOn = addedOn self.userID = user.id } required init(row: Row) throws { self.name = try row.get(Attachment.nameKey) self.url = try row.get(Attachment.urlKey) self.addedOn = try row.get(Attachment.addedOnKey) self.userID = try row.get(User.foreignIdKey) } func makeRow() throws -> Row { var row = Row() try row.set(Attachment.nameKey, self.name) try row.set(Attachment.urlKey, self.url) try row.set(Attachment.addedOnKey, self.addedOn) try row.set(User.foreignIdKey, self.userID) return row } } // MARK: Relation extension Attachment { var owner: Parent<Attachment, User> { return parent(id: self.userID) } } // MARK: JSON extension Attachment: JSONConvertible { convenience init(json: JSON) throws { let userID: Identifier = try json.get(Attachment.userIDKey) guard let user = try User.find(userID) else { throw Abort.badRequest } try self.init( name: json.get(Attachment.nameKey), url: json.get(Attachment.urlKey), addedOn: json.get(Attachment.addedOnKey), user: user ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(Attachment.idKey, self.id) try json.set(Attachment.nameKey, self.name) try json.set(Attachment.urlKey, self.url) try json.set(Attachment.addedOnKey, self.addedOn) try json.set(Attachment.userIDKey, self.userID) return json } } // MARK: HTTP extension Attachment: ResponseRepresentable { } extension Attachment: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string(Attachment.nameKey) builder.string(Attachment.urlKey) builder.date(Attachment.addedOnKey) builder.parent(User.self) } } static func revert(_ database: Database) throws { try database.delete(self) } }
mit
399f3fd4f7d079e3902d0e0655b25e89
21.418182
63
0.659773
3.642541
false
false
false
false
peferron/algo
EPI/Sorting/Partitioning and sorting an array with many repeated entries/swift/main.swift
1
3099
public typealias Student = (name: String, age: Int) public func group(_ students: inout [Student]) { // Count the number of students in each age group. var ageCounts = [Int: Int]() for student in students { ageCounts[student.age] = (ageCounts[student.age] ?? 0) + 1 } // Compute the indexes at which each age group should start. var ageStartIndexes = [Int: Int]() var nextFreeIndex = 0 // The sorting step below increases the time complexity of the overall algorithm from O(n) to // O(n + m log m), where m is the number of age groups. To skip sorting, which is described as // optional in the book, simply remove `.sorted(by: ...)`. for (age, count) in ageCounts.sorted(by: { $0.key < $1.key }) { ageStartIndexes[age] = nextFreeIndex nextFreeIndex += count } // Last phase: iterate through the students array, making sure at each step that the current // index holds a student of the correct age group. // This phase is implemented very differently than in the book. I'm keeping it because I find it // more intuitive while still being O(n). var ageTargetIndexes = ageStartIndexes var index = 0 while index < students.count { let age = students[index].age let ageStartIndex = ageStartIndexes[age]! let ageTargetIndex = ageTargetIndexes[age]! if index >= ageStartIndex && index < ageTargetIndex { // The current student is already well-positioned. index += 1 } else { // Move the current student to the target index for this age group. if index != ageTargetIndex { students.swapAt(index, ageTargetIndex) } ageTargetIndexes[age]! += 1 } } // The code below implements the last phase of the algorithm in the same way as in the book. // Note this implementation can put students of the same age in a different order than the // other implementation above, so tests might have to be slightly amended before they pass. /* while let ageStartIndex = ageStartIndexes.first?.value { // What is the age of the student currently occupying the ageStartIndex spot? let currentStudentAge = students[ageStartIndex].age // Where should this student be moved instead? let currentStudentTargetIndex = ageStartIndexes[currentStudentAge]! // Move it! if ageStartIndex != currentStudentTargetIndex { swap(&students[ageStartIndex], &students[currentStudentTargetIndex]) } // Now that the student is placed in a correct spot, there is one less student to move in // its age group. ageCounts[currentStudentAge]! -= 1 if ageCounts[currentStudentAge]! == 0 { // All students in this age group are correctly placed. ageStartIndexes[currentStudentAge] = nil } else { // The next student of the same age group should take the next spot. ageStartIndexes[currentStudentAge]! += 1 } } */ }
mit
3923e8201e12dd2cea91ad1d7a382f58
41.452055
100
0.645369
4.497823
false
false
false
false
yoonhg84/ModalPresenter
Example/RxModalityStackExample/ViewControllers/ToolView.swift
1
4970
// // Created by Chope on 2018. 4. 24.. // Copyright (c) 2018 Chope Industry. All rights reserved. // import UIKit import RxSwift import RxModalityStack class ToolView: UIView { private let disposeBag = DisposeBag() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureViews() } override init(frame: CGRect) { super.init(frame: frame) configureViews() } private func configureViews() { backgroundColor = UIColor.black addSubview(createControlButton(title: "dismiss all", origin: CGPoint(x: 6, y: 6), action: #selector(self.dismissAll))) addSubview(createControlButton(title: "dismiss front", origin: CGPoint(x: 90, y: 6), action: #selector(self.dismissFront))) addSubview(createControlButton(title: "dismiss except", origin: CGPoint(x: 180, y: 6), action: #selector(self.dismissExceptGreenAndBlue))) addSubview(createControlButton(title: "first to front", origin: CGPoint(x: 6, y: 40), action: #selector(self.firstToFront))) addSubview(createControlButton(title: "activity", origin: CGPoint(x: 95, y: 40), action: #selector(self.presentActivityController))) addSubview(createControlButton(title: "alert", origin: CGPoint(x: 6, y: 74), action: #selector(self.presentAlert))) addSubview(createControlButton(title: "imagePicker", origin: CGPoint(x: 50, y: 74), action: #selector(self.presentImagePicker))) addSubview(createControlButton(title: "blue", origin: CGPoint(x: 140, y: 74), action: #selector(self.presentBlue))) addSubview(createControlButton(title: "green", origin: CGPoint(x: 180, y: 74), action: #selector(self.presentGreen))) addSubview(createControlButton(title: "red", origin: CGPoint(x: 230, y: 74), action: #selector(self.presentRed))) addSubview(createControlButton(title: "yellow", origin: CGPoint(x: 270, y: 74), action: #selector(self.presentYellow))) } private func createControlButton(title: String, origin: CGPoint, action: Selector) -> UIButton { let button = UIButton(type: .custom) button.backgroundColor = UIColor.white button.setTitleColor(UIColor.black, for: .normal) button.setTitle(title, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 12) button.frame.origin = origin button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6) button.sizeToFit() button.addTarget(self, action: action, for: .touchUpInside) return button } @objc func dismissAll() { Modal.shared.dismissAll(animated: true).debug().subscribe().disposed(by: disposeBag) } @objc func dismissFront() { Modal.shared.dismissFront(animated: true).debug().subscribe().disposed(by: disposeBag) } @objc func dismissExceptGreenAndBlue() { Modal.shared.dismissAll(except: [.green, .blue]).debug().subscribe().disposed(by: disposeBag) } @objc func firstToFront() { guard Modal.shared.stack.count > 0 else { return } let modality = Modal.shared.stack[0] Modal.shared.bringModality(toFront: modality.id).debug().subscribe().disposed(by: disposeBag) } @objc func presentActivityController() { Modal.shared.present(.activity, with: .empty, animated: true).subscribe().disposed(by: disposeBag) } @objc func presentBlue() { Modal.shared.present(.blue, with: .none, animated: true).subscribe().disposed(by: disposeBag) } @objc func presentGreen() { Modal.shared.present(.green, with: .none, animated: true).subscribe().disposed(by: disposeBag) } @objc func presentRed() { Modal.shared.present(.red, with: .none, animated: true).subscribe().disposed(by: disposeBag) } @objc func presentYellow() { Modal.shared.present(.color, with: .color(.yellow), animated: true).subscribe().disposed(by: disposeBag) } @objc func presentAlert() { Modal.shared.present(.alert, with: .alert(title: "title", message: "message"), animated: true).subscribe().disposed(by: disposeBag) } @objc func presentImagePicker() { Modal.shared.present(.imagePicker, with: .empty, animated: true) .asObservable() .flatMap { (modality: Modality<Modal, ModalData>) -> Observable<(UIViewController, UIImage)> in guard let vc = modality.viewController as? UIImagePickerController else { throw ToolError.invalidVC } return vc.rx.didSelectImage.asObservable().map { (vc, $0) } } .flatMap { result in return Modal.shared.dismiss(result.0, animated: true).map { _ in result.1 } } .flatMap { return Modal.shared.present(.image, with: .image($0), animated: true) } .subscribe() .disposed(by: disposeBag) } }
mit
172bbc39e768b7dd8fc2ccd6f02e0ba7
42.217391
146
0.652716
4.155518
false
false
false
false
Kevin-De-Koninck/Sub-It
Sub It/optionsTextfield.swift
1
1077
// // optionsTextfield.swift // Sub It // // Created by Kevin De Koninck on 04/02/2017. // Copyright © 2017 Kevin De Koninck. All rights reserved. // import Cocoa class optionsTextfield: NSTextField { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) var bgColor = NSColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0) bgColor = NSColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0) self.focusRingType = .none self.isBordered = false self.drawsBackground = false self.backgroundColor = bgColor self.layer?.backgroundColor = bgColor.cgColor //underline let border = CALayer() let width = CGFloat(1.0) border.borderColor = blueColor.cgColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer?.addSublayer(border) self.layer?.masksToBounds = true } }
mit
8486698cf3ae6d04ebe99a412cceb08d
28.888889
133
0.627323
3.80212
false
false
false
false
sanghapark/Vigorous
Example/VigorousExample/TestView.swift
1
961
// // TestView.swift // VigorousExample // // Created by ParkSangHa on 2017. 3. 29.. // Copyright © 2017년 sanghapark1021. All rights reserved. // import UIKit import Vigorous class TestView: UIView, CornerRadiusChangeable { lazy var vigorously: Vigorously = { return Vigorously(self) }() func animate() { vigorously.animate( Animator() .serial(Animatable(3) { self.backgroundColor = .blue }) .parallel([ Animatable(2) { self.backgroundColor = .red }, cornerRadius(value: frame.height / 2), Animatable(2) { self.center.x += 200 } ]) .serial(Animatable(1) { self.center.x -= 200 }) .serial(cornerRadius(value: 0)) { _ in self.animate() } ) DispatchQueue.main.asyncAfter(deadline: .now() + 20) { self.vigorously .cancelAll() .animate(Animatable(3) { self.backgroundColor = .yellow }) } } }
mit
3570f3ef4c24097041d7d455b708134f
21.809524
66
0.583507
3.832
false
false
false
false
jhurray/SQLiteModel-Example-Project
iOS+SQLiteModel/Blogz4Dayz/AppDelegate.swift
1
3043
// // AppDelegate.swift // Blogz4Dayz // // Created by Jeff Hurray on 4/8/16. // Copyright © 2016 jhurray. All rights reserved. // import UIKit import SQLiteModel let color = UIColor(red: 68/255.0, green: 108/255.0, blue: 179/255.0, alpha: 1.0) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { SQLiteModelLogManager.startLogging() try! BlogModel.createTable() try! ImageModel.createTable() UINavigationBar.appearance().tintColor = color let blogListViewController = BlogListViewController() blogListViewController.title = "Blogz" let navController1 = UINavigationController(rootViewController: blogListViewController) let imageListViewController = ImageListViewController() imageListViewController.title = "Images" let navController2 = UINavigationController(rootViewController: imageListViewController) let tabController = UITabBarController() tabController.viewControllers = [navController1, navController2] window?.rootViewController = tabController window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
92318b2259649ba20765f37f0953e3ba
42.457143
285
0.73044
5.622921
false
false
false
false
react-native-kit/react-native-track-player
ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/NowPlayingInfoController/NowPlayingInfoProperty.swift
2
9603
// // NowPlayingInfo.swift // SwiftAudio // // Created by Jørgen Henrichsen on 15/03/2018. // import Foundation import MediaPlayer /** Enum representing MPNowPlayingInfoProperties. Docs for each property is taken from [Apple docs](https://developer.apple.com/documentation/mediaplayer/mpnowplayinginfocenter/additional_metadata_properties). */ public enum NowPlayingInfoProperty: NowPlayingInfoKeyValue { /** The identifier of the collection the now playing item belongs to. The identifier can be an album, artist, playlist, etc. */ case collectionIdentifier(String?) /** The available language option groups for the now playing item. Value is an array of MPNowPlayingInfoLanguageOptionGroup items. Only one language option in a given group can be played at a time. */ case availableLanguageOptions([MPNowPlayingInfoLanguageOptionGroup]?) /** The URL pointing to the now playing item's underlying asset. This constant is used by the system UI when video thumbnails or audio waveform visualizations are applicable. */ @available(iOS 10.3, *) case assetUrl(URL?) /** The total number of chapters in the now-playing item. Value is an NSNumber object configured as an NSUInteger. */ case chapterCount(UInt64?) /** The number corresponding to the chapter currently being played. Value is an NSNumber object configured as an NSUInteger. Chapter numbering uses zero-based indexing. If you want the first chapter in the now-playing item to be displayed as “Chapter 1,” for example, set the chapter number to 0. */ case chapterNumber(UInt64?) /** The currently active language options for the now playing item. Value is an array of MPNowPlayingInfoLanguageOption items. */ case currentLanguageOptions([MPNowPlayingInfoLanguageOption]?) /** The default playback rate for the now playing item. Value is an NSNumber object configured as a double. Set this property if your app is playing a media item at a playback rate other than 1.0 as its default rate. */ case defaultPlaybackRate(Double?) /** The elapsed time of the now playing item, in seconds. Value is an NSNumber object configured as a double. Elapsed time is automatically calculated, by the system, from the previously provided elapsed time and the playback rate. Do not update this property frequently—it is not necessary */ case elapsedPlaybackTime(Double?) /** The opaque identifier that uniquely identifies the now playing item, even through app relaunches. This is only used to reference the item to the now playing app and can be in any format. */ case externalContentIdentifier(Any?) /** The opaque identifier that uniquely identifies the profile the now playing item is played from, even through app relaunches. This is only used to reference the profile to the now playing app and can be in any format. */ case externalUserProfileIdentifier(Any?) /** Denotes whether the now playing item is a live stream. Value is an NSNumber object configured as a boolean. A value of 1.0 indicates the now playing item is a live stream. */ case isLiveStream(Bool?) /** The media type of the now playing item. Value is an NSNumber object configured as a MPNowPlayingInfoMediaType. */ case mediaType(MPNowPlayingInfoMediaType?) /** The current progress of the now playing item. Value is an NSNumber object configured as a float. A value of 0.0 indicates the item has not been watched while a value of 1.0 indicates the item has been fully watched. This is a high-level indicator. Use MPNowPlayingInfoPropertyElapsedPlaybackTime for fine-detailed information on how much of the item has been watched. */ case playbackProgress(Float?) /** The total number of items in the app’s playback queue. Value is an NSNumber object configured as an NSUInteger. */ case playbackQueueCount(UInt64?) /** The index of the now-playing item in the app’s playback queue. Value is an NSNumber object configured as an NSUInteger. The playback queue uses zero-based indexing. If you want the first item in the queue to be displayed as “item 1 of 10,” for example, set the item’s index to 0. */ case playbackQueueIndex(UInt64?) /** The playback rate of the now-playing item, with a value of 1.0 indicating the normal playback rate. Value is an NSNumber object configured as a double. The default value is 1.0. A playback rate value of 2.0 means twice the normal playback rate; a piece of media played at this rate would take half as long to play to completion. A value of 0.5 means half the normal playback rate; a piece of media played at this rate would take twice as long to play to completion. */ case playbackRate(Double?) /** The service provider associated with the now-playing item. Value is a unique NSString that identifies the service provider for the now-playing item. If the now-playing item belongs to a channel or subscription service, this key can be used to coordinate various types of now-playing content from the service provider. */ @available(iOS 11.0, *) case serviceIdentifier(String?) public func getKey() -> String { switch self { case .collectionIdentifier(_): return MPNowPlayingInfoCollectionIdentifier case .availableLanguageOptions(_): return MPNowPlayingInfoPropertyAvailableLanguageOptions case .assetUrl(_): if #available(iOS 10.3, *) { return MPNowPlayingInfoPropertyAssetURL } else { return "" } case .chapterCount(_): return MPNowPlayingInfoPropertyChapterCount case .chapterNumber(_): return MPNowPlayingInfoPropertyChapterNumber case .currentLanguageOptions(_): return MPNowPlayingInfoPropertyCurrentLanguageOptions case .defaultPlaybackRate(_): return MPNowPlayingInfoPropertyDefaultPlaybackRate case .elapsedPlaybackTime(_): return MPNowPlayingInfoPropertyElapsedPlaybackTime case .externalContentIdentifier(_): return MPNowPlayingInfoPropertyExternalContentIdentifier case .externalUserProfileIdentifier(_): return MPNowPlayingInfoPropertyExternalUserProfileIdentifier case .isLiveStream(_): return MPNowPlayingInfoPropertyIsLiveStream case .mediaType(_): return MPNowPlayingInfoPropertyMediaType case .playbackProgress(_): return MPNowPlayingInfoPropertyPlaybackProgress case .playbackQueueCount(_): return MPNowPlayingInfoPropertyPlaybackQueueCount case .playbackQueueIndex(_): return MPNowPlayingInfoPropertyPlaybackQueueIndex case .playbackRate(_): return MPNowPlayingInfoPropertyPlaybackRate case .serviceIdentifier(_): if #available(iOS 11.0, *) { return MPNowPlayingInfoPropertyServiceIdentifier } else { return "" } } } public func getValue() -> Any? { switch self { case .collectionIdentifier(let identifier): return identifier case .availableLanguageOptions(let options): return options case .assetUrl(let url): if #available(iOS 10.3, *) { return url } return false case .chapterCount(let count): return count != nil ? NSNumber(value: count!) : nil case .chapterNumber(let number): return number != nil ? NSNumber(value: number!) : nil case .currentLanguageOptions(let options): return options case .defaultPlaybackRate(let rate): return rate != nil ? NSNumber(floatLiteral: rate!) : nil case .elapsedPlaybackTime(let time): return time != nil ? NSNumber(floatLiteral: time!) : nil case .externalContentIdentifier(let id): return id case .externalUserProfileIdentifier(let id): return id case .isLiveStream(let status): return status case .mediaType(let type): return type != nil ? NSNumber(value: type!.rawValue) : nil case .playbackProgress(let progress): return progress != nil ? NSNumber(value: progress!) : nil case .playbackQueueCount(let count): return count != nil ? NSNumber(value: count!) : nil case .playbackQueueIndex(let index): return index != nil ? NSNumber(value: index!) : nil case .playbackRate(let rate): return rate != nil ? NSNumber(floatLiteral: rate!) : nil case .serviceIdentifier(let id): return id != nil ? NSString(string: id!) : nil } } }
apache-2.0
a442d1d81c37977cfb46137f14339a01
37.809717
370
0.641561
5.576498
false
false
false
false
hsylife/SwiftyPickerPopover
SwiftyPickerPopover/StringPickerPopoverViewController.swift
1
8969
// // StringPickerPopoverViewController.swift // SwiftyPickerPopover // // Created by Yuta Hoshino on 2016/09/14. // Copyright © 2016 Yuta Hoshino. All rights reserved. // public class StringPickerPopoverViewController: AbstractPickerPopoverViewController { // MARK: Types /// Popover type typealias PopoverType = StringPickerPopover // MARK: Properties /// Popover private var popover: PopoverType! { return anyPopover as? PopoverType } @IBOutlet weak private var cancelButton: UIBarButtonItem! @IBOutlet weak private var doneButton: UIBarButtonItem! @IBOutlet weak private var picker: UIPickerView! @IBOutlet weak private var clearButton: UIButton! override public func viewDidLoad() { super.viewDidLoad() picker.delegate = self } /// Make the popover properties reflect on this view controller override func refrectPopoverProperties(){ super.refrectPopoverProperties() // Select row if needed picker?.selectRow(popover.selectedRow, inComponent: 0, animated: true) // Set up cancel button if #available(iOS 11.0, *) { } else { navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = nil } cancelButton.title = popover.cancelButton.title if let font = popover.cancelButton.font { cancelButton.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal) } cancelButton.tintColor = popover.cancelButton.color ?? popover.tintColor navigationItem.setLeftBarButton(cancelButton, animated: false) doneButton.title = popover.doneButton.title if let font = popover.doneButton.font { doneButton.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal) } doneButton.tintColor = popover.doneButton.color ?? popover.tintColor navigationItem.setRightBarButton(doneButton, animated: false) clearButton.setTitle(popover.clearButton.title, for: .normal) if let font = popover.clearButton.font { clearButton.titleLabel?.font = font } clearButton.tintColor = popover.clearButton.color ?? popover.tintColor clearButton.isHidden = popover.clearButton.action == nil enableClearButtonIfNeeded() } private func enableClearButtonIfNeeded() { guard !clearButton.isHidden else { return } clearButton.isEnabled = false if let selectedRow = picker?.selectedRow(inComponent: 0), let selectedValue = popover.choices[safe: selectedRow] { clearButton.isEnabled = selectedValue != popover.kValueForCleared } } /// Action when tapping done button /// /// - Parameter sender: Done button @IBAction func tappedDone(_ sender: AnyObject? = nil) { tapped(button: popover.doneButton) } /// Action when tapping cancel button /// /// - Parameter sender: Cancel button @IBAction func tappedCancel(_ sender: AnyObject? = nil) { tapped(button: popover.cancelButton) } private func tapped(button: StringPickerPopover.ButtonParameterType?) { let selectedRow = picker.selectedRow(inComponent: 0) if let selectedValue = popover.choices[safe: selectedRow] { button?.action?(popover, selectedRow, selectedValue) } popover.removeDimmedView() dismiss(animated: false) } /// Action when tapping clear button /// /// - Parameter sender: Clear button @IBAction func tappedClear(_ sender: AnyObject? = nil) { let kTargetRow = 0 picker.selectRow(kTargetRow, inComponent: 0, animated: true) enableClearButtonIfNeeded() if let selectedValue = popover.choices[safe: kTargetRow] { popover.clearButton.action?(popover, kTargetRow, selectedValue) } popover.redoDisappearAutomatically() } /// Action to be executed after the popover disappears /// /// - Parameter popoverPresentationController: UIPopoverPresentationController func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { tappedCancel() } } // MARK: - UIPickerViewDataSource extension StringPickerPopoverViewController: UIPickerViewDataSource { public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return popover.choices.count } } // MARK: - UIPickerViewDelegate extension StringPickerPopoverViewController: UIPickerViewDelegate { public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let value: String = popover.choices[row] return popover.displayStringFor?(value) ?? value } public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let value: String = popover.choices[row] let adjustedValue: String = popover.displayStringFor?(value) ?? value let label: UILabel = view as? UILabel ?? UILabel() label.text = adjustedValue label.attributedText = getAttributedText(image: popover.images?[row], text: adjustedValue) label.textAlignment = .center return label } private func getAttributedText(image: UIImage?, text: String?) -> NSAttributedString? { let result: NSMutableAttributedString = NSMutableAttributedString() if let attributedImage = getAttributedImage(image), let space = getAttributedText(" ") { result.append(attributedImage) result.append(space) } if let attributedText = getAttributedText(text) { result.append(attributedText) } return result } private func getAttributedText(_ text: String?) -> NSAttributedString? { guard let text = text else { return nil } let font: UIFont = { if let f = popover.font { if let size = popover.fontSize { return UIFont(name: f.fontName, size: size)! } return UIFont(name: f.fontName, size: f.pointSize)! } let size = popover.fontSize ?? popover.kDefaultFontSize return UIFont.systemFont(ofSize: size) }() let color: UIColor = popover.fontColor return NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: color]) } private func getAttributedImage(_ image: UIImage?) -> NSAttributedString? { guard let image = image else { return nil } let imageAttachment = NSTextAttachment() imageAttachment.image = image return NSAttributedString(attachment: imageAttachment) } public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let attributedResult = NSMutableAttributedString() if let image = popover.images?[row] { let imageAttachment = NSTextAttachment() imageAttachment.image = image let attributedImage = NSAttributedString(attachment: imageAttachment) attributedResult.append(attributedImage) let AttributedMargin = NSAttributedString(string: " ") attributedResult.append(AttributedMargin) } let value: String = popover.choices[row] let title: String = popover.displayStringFor?(value) ?? value let font: UIFont = { if let f = popover.font { if let fontSize = popover.fontSize { return UIFont(name: f.fontName, size: fontSize)! } return UIFont(name: f.fontName, size: f.pointSize)! } let fontSize = popover.fontSize ?? popover.kDefaultFontSize return UIFont.systemFont(ofSize: fontSize) }() let attributedTitle: NSAttributedString = NSAttributedString(string: title, attributes: [.font: font, .foregroundColor: popover.fontColor]) attributedResult.append(attributedTitle) return attributedResult } public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return popover.rowHeight } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { enableClearButtonIfNeeded() popover.valueChangeAction?(popover, row, popover.choices[row]) popover.redoDisappearAutomatically() } }
mit
4970147c70213476339125eeaed7144f
37.822511
147
0.653323
5.44836
false
false
false
false
DrabWeb/Keijiban
Keijiban/Keijiban/KJChangeCursorOnHoverView.swift
1
1940
// // KJChangeCursorOnHoverView.swift // Keijiban // // Created by Seth on 2016-06-10. // import Cocoa class KJChangeCursorOnHoverView: NSView { /// The cursor to change to when hovering this view var hoverCursor : NSCursor = NSCursor.pointingHandCursor(); override func mouseEntered(theEvent: NSEvent) { super.mouseEntered(theEvent); // Change the cursor hoverCursor.set(); } override func mouseExited(theEvent: NSEvent) { super.mouseExited(theEvent); // Change the cursor back to the default cursor NSCursor.arrowCursor().set(); } deinit { // Change the cursor back to the default cursor NSCursor.arrowCursor().set(); } /// The tracking area for this view private var trackingArea : NSTrackingArea? = nil; override func viewWillDraw() { // Update the tracking areas self.updateTrackingAreas(); } override func updateTrackingAreas() { // Remove the tracking are we added before if(trackingArea != nil) { self.removeTrackingArea(trackingArea!); } /// The same as the original tracking area, but updated to match the frame of this view trackingArea = NSTrackingArea(rect: frame, options: [NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveInKeyWindow], owner: self, userInfo: nil); // Add the tracking area self.addTrackingArea(trackingArea!); } override func awakeFromNib() { /// The tracking are we will use for getting mouse entered and exited events trackingArea = NSTrackingArea(rect: frame, options: [NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveInKeyWindow], owner: self, userInfo: nil); // Add the tracking area self.addTrackingArea(trackingArea!); } }
gpl-3.0
e6779ddc614962f8a0447fb1431c7c4e
30.803279
176
0.647423
5.257453
false
false
false
false
IBM-Swift/BluePic
BluePic-iOS/BluePic/Controllers/TabBarViewController.swift
1
10808
/** * Copyright IBM Corporation 2016, 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit import SVProgressHUD class TabBarViewController: UITabBarController { /// Image view to temporarily cover feed and content so it doesn't appear to flash when showing login screen var backgroundImageView: UIImageView! // A view model that will keep state and do all the data handling for the TabBarViewController var viewModel: TabBarViewModel! /** Method called upon view did load. It creates an instance of the TabBarViewModel, sets the tabBar tint color, adds a background image view, and sets its delegate */ override func viewDidLoad() { super.viewDidLoad() SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.custom) SVProgressHUD.setBackgroundColor(UIColor.white) viewModel = TabBarViewModel(notifyTabBarVC: handleTabBarViewModelNotifications) self.tabBar.tintColor = UIColor.white self.addBackgroundImageView() self.delegate = self } /** Method called upon view did appear, it trys to show the login vc - parameter animated: Bool */ override func viewDidAppear(_ animated: Bool) { self.tryToShowLogin() } /** Method called as a callback from the OS when the app recieves a memory warning from the OS */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Method adds image view so no flickering occurs before showing login. */ func addBackgroundImageView() { self.backgroundImageView = UIImageView(frame: self.view.frame) self.backgroundImageView.image = UIImage(named: "login_background") self.view.addSubview(self.backgroundImageView) } /** Method trys to show the login by asking the viewModel to try to show login */ func tryToShowLogin() { viewModel.tryToShowLogin() } /** Method hides the background image */ func hideBackgroundImage() { //hide temp background image used to prevent flash animation self.backgroundImageView.isHidden = true self.backgroundImageView.removeFromSuperview() } /** Method to show the login VC with or without animation - parameter animated: Bool to determine if VC should be animated on presentation - parameter callback: callback for actions once presentation is done */ func presentLoginVC(_ animated: Bool, callback: (() -> Void)?) { if let loginVC = Utils.vcWithNameFromStoryboardWithName("loginVC", storyboardName: "Main") as? LoginViewController { /// Return to home screen replacing TabBarViewController. ARC will garbage collect. guard let window = UIApplication.shared.delegate?.window else { print("Logout Failed: Could not unwrap root view controller") return } window?.rootViewController = loginVC } } /** Method switches to the feed tab and pops the view controller stack to the first vc */ func switchToFeedTabAndPopToRootViewController() { self.selectedIndex = 0 if let feedNavigationVC = self.viewControllers?[0] as? FeedNavigationController { feedNavigationVC.popToRootViewController(animated: false) } } override var shouldAutomaticallyForwardAppearanceMethods: Bool { return true } } extension TabBarViewController: UITabBarControllerDelegate { /** Method is called right when the user selects a tab. It expects a return value that tells the TabBarViewController whether it should select that tab or not. If the camera tab is selected, then we always return false and then call the handleCameraTabBeingSelected method. If the profile tab is selected, we return whatever the shouldShowProfileViewControllerAndHandleIfShouldnt method returns - parameter tabBarController: UITabBarController - parameter viewController: UIViewController - returns: Bool */ func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { if viewController as? CameraViewController != nil { //if camera tab is selected, show camera picker handleCameraTabBeingSelected() return false } else if viewController as? ProfileNavigationController != nil { return shouldShowProfileViewControllerAndHandleIfShouldnt() } else { //if feed selected, actually show it everytime return true } } /** Method is called when the profile tab is selected. If the user pressed login later, then we return false because we dont want to show the the user the profile vc and instead we want to present the login vc to the user. If the user didn't press login later, then we return true so the user is presented with the profile vc - returns: Bool */ func shouldShowProfileViewControllerAndHandleIfShouldnt() -> Bool { if !viewModel.isUserAuthenticated() { presentLoginVC(true, callback: nil) return false } else { return true } } /** Method handles the camera tab being selected. If the user pressed login later, then we present to the user the login vc. If the user didn't press login later, then we check if location services had been enabled or not. If it has been enabled, we show them the image picker action sheet. Else we show the user the location services required alert */ func handleCameraTabBeingSelected() { LocationDataManager.SharedInstance.isLocationServicesEnabledAndIfNotHandleIt({ isEnabled in if isEnabled { CameraDataManager.SharedInstance.showImagePickerActionSheet(self) } else { self.showLocationServiceRequiredAlert() } }) } /** Method shows the location services required alert */ func showLocationServiceRequiredAlert() { let alertController = UIAlertController(title: NSLocalizedString("Location Services Required", comment: ""), message: NSLocalizedString("Please go to Settings to enable Location Services for BluePic", comment: ""), preferredStyle: .alert) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: NSLocalizedString("Settings", comment: ""), style: .default) { (_) in if let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(settingsUrl, options: [:]) } } alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } /** Method to show the image upload failure alert */ func showImageUploadFailureAlert() { let alert = UIAlertController(title: NSLocalizedString("Failed To Upload Image", comment: ""), message: "", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .default, handler: { (_: UIAlertAction) in self.viewModel.tellBluemixDataManagerToCancelUploadingImagesThatFailedToUpload() })) alert.addAction(UIAlertAction(title: NSLocalizedString("Try Again", comment: ""), style: .default, handler: { (_: UIAlertAction) in self.viewModel.tellBluemixDataManagerToRetryUploadingImagesThatFailedToUpload() })) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } } //ViewModel -> View Controller Communication extension TabBarViewController { /** Method that handles tab bar view model notifications from the tab bar view model - parameter tabBarNotification: TabBarViewModelNotification */ func handleTabBarViewModelNotifications(_ tabBarNotification: TabBarViewModelNotification) { if tabBarNotification == TabBarViewModelNotification.showLoginVC { presentLoginVC(false, callback: nil) } else if tabBarNotification == TabBarViewModelNotification.hideLoginVC { hideBackgroundImage() } else if tabBarNotification == TabBarViewModelNotification.switchToFeedTab { switchToFeedTabAndPopToRootViewController() } else if tabBarNotification == TabBarViewModelNotification.showImageUploadFailureAlert { showImageUploadFailureAlert() } else if tabBarNotification == TabBarViewModelNotification.showSettingsActionSheet { showSettingsActionSheet() } else if tabBarNotification == TabBarViewModelNotification.logOutSuccess { handleLogOutSuccess() } } /** Method shows the settings action sheet. */ func showSettingsActionSheet() { let alert: UIAlertController=UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet) let cameraAction = UIAlertAction(title: NSLocalizedString("Log Out", comment: ""), style: UIAlertActionStyle.default) { _ in SVProgressHUD.show() self.viewModel.logOutUser() } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: UIAlertActionStyle.cancel) { _ in } // Add the actions alert.addAction(cameraAction) alert.addAction(cancelAction) // on iPad, this will be a Popover // on iPhone, this will be an action sheet alert.modalPresentationStyle = .popover // Present the controller self.present(alert, animated: true, completion: nil) } /** Method handles when logout was a success. It dismisses the SVProgressHUD, presents the login vc and then sets the tab bar selected index 0 (feed vc) */ func handleLogOutSuccess() { SVProgressHUD.dismiss() DispatchQueue.main.async { self.presentLoginVC(true, callback: { self.selectedIndex = 0 }) } } }
apache-2.0
4a57219dddea93f2ecce83970874fbc9
36.268966
395
0.687731
5.42298
false
false
false
false
joshdholtz/Few.swift
Few-Mac/Password.swift
1
594
// // Password.swift // Few // // Created by Josh Abernathy on 12/19/14. // Copyright (c) 2014 Josh Abernathy. All rights reserved. // import Foundation import AppKit public class Password: Input { public override func createView() -> ViewType { let field = NSSecureTextField(frame: frame) field.editable = true field.stringValue = text ?? initialText ?? "" field.delegate = inputDelegate field.enabled = enabled field.alphaValue = alpha field.hidden = hidden let cell = field.cell() as? NSTextFieldCell cell?.placeholderString = placeholder ?? "" return field } }
mit
25da5ed039cb17728409360e73c3df5e
21.846154
59
0.705387
3.621951
false
false
false
false
alecthomas/EVReflection
EVReflection/pod/EVReflection.swift
1
24407
// // EVReflection.swift // // Created by Edwin Vermeer on 28-09-14. // Copyright (c) 2014 EVICT BV. All rights reserved. // import Foundation import CloudKit /** Reflection methods */ final public class EVReflection { /** Create an object from a dictionary :param: dictionary The dictionary that will be converted to an object :param: anyobjectTypeString The string representation of the object type that will be created :return: The object that is created from the dictionary */ public class func fromDictionary(dictionary:NSDictionary, anyobjectTypeString: String) -> NSObject? { if var nsobject = swiftClassFromString(anyobjectTypeString) { nsobject = setPropertiesfromDictionary(dictionary, anyObject: nsobject) return nsobject } return nil } /** Set object properties from a dictionary :param: dictionary The dictionary that will be converted to an object :param: anyObject The object where the properties will be set :return: The object that is created from the dictionary */ public class func setPropertiesfromDictionary<T where T:NSObject>(dictionary:NSDictionary, anyObject: T) -> T { var (hasKeys, hasTypes) = toDictionary(anyObject) for (k, v) in dictionary { if var key = k as? String { var skipKey = false var toKey = key if let evObject = anyObject as? EVObject { if let mapping = filter(evObject.propertyMapping(), {$0.1 == key}).first { if mapping.0 == nil { skipKey = true } else { toKey = mapping.0! } } } if !skipKey{ var newValue: AnyObject? = dictionary[key]! if let type = hasTypes[toKey] { if type.hasPrefix("Swift.Array<") && newValue as? NSDictionary != nil { if var value = v as? [NSObject] { value.append(newValue! as! NSObject) newValue = value } } else if type != "NSDictionary" && newValue as? NSDictionary != nil { newValue = dictToObject(type, original:hasKeys[key] as! NSObject ,dict: newValue as! NSDictionary) } else if type.rangeOfString("<NSDictionary>") == nil && newValue as? [NSDictionary] != nil { newValue = dictArrayToObjectArray(type, array: newValue as! [NSDictionary]) as [NSObject] } } let keywords = ["self", "description", "class", "deinit", "enum", "extension", "func", "import", "init", "let", "protocol", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "if", "in", "for", "return", "switch", "where", "while", "as", "dynamicType", "is", "new", "super", "Self", "Type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "didSet", "get", "infix", "inout", "left", "mutating", "none", "nonmutating", "operator", "override", "postfix", "precedence", "prefix", "right", "set", "unowned", "unowned", "safe", "unowned", "unsafe", "weak", "willSet", "private", "public", "internal", "zone"] if contains(keywords, toKey) { toKey = "_\(key)" } var error: NSError? if anyObject.validateValue(&newValue, forKey: toKey, error: &error) { if newValue == nil || newValue as? NSNull != nil { anyObject.setValue(Optional.None, forKey: toKey) } else { // Let us put a number into a string property by taking it's stringValue if let typeInObject = hasTypes[toKey] { let (_, type) = valueForAny("", key: toKey, anyValue: newValue) if (typeInObject == "Swift.String" || typeInObject == "NSString") && type == "NSNumber" { if let convertedValue = newValue as? NSNumber { newValue = convertedValue.stringValue } } } // TODO: This will trigger setvalue for undefined key for specific types like enums, arrays of optionals or optional types. anyObject.setValue(newValue, forKey: toKey) } } } } } return anyObject } /** Set sub object properties from a dictionary :param: type The object type that will be created :param: dict The dictionary that will be converted to an object :return: The object that is created from the dictionary */ private class func dictToObject<T where T:NSObject>(type:String, original:T ,dict:NSDictionary) -> T { var returnObject:NSObject = swiftClassFromString(type) returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject) return returnObject as! T } /** Create an Array of objects from an array of dictionaries :param: type The object type that will be created :param: array The array of dictionaries that will be converted to the array of objects :return: The array of objects that is created from the array of dictionaries */ private class func dictArrayToObjectArray(type:String, array:[NSDictionary]) -> [NSObject] { var subtype = "EVObject" if (split(type) {$0 == "<"}).count > 1 { // Remove the Swift.Array prefix subtype = type.substringFromIndex((split(type) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) // Remove the optional prefix from the subtype if subtype.hasPrefix("Swift.Optional<") { subtype = subtype.substringFromIndex((split(subtype) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) } } var result = [NSObject]() for item in array { let arrayObject = self.dictToObject(subtype, original:swiftClassFromString(subtype), dict: item) result.append(arrayObject) } return result } /** Helper function that let us get the actual type of an object that is used inside an array :param: array The array of objects where we want the type of the object */ private class func getArrayObjectType<T where T:NSObject>(array:[T]) -> String { return NSStringFromClass(T().dynamicType) as String } /** Convert an object to a dictionary :param: theObject The object that will be converted to a dictionary :return: The dictionary that is created from theObject plus a dictionary of propery types. */ public class func toDictionary(theObject: NSObject) -> (NSDictionary, Dictionary<String,String>) { let reflected = reflect(theObject) return reflectedSub(theObject, reflected: reflected) } /** for parsing an object to a dictionary. including properties from it's super class (recursive) :param: reflected The object parsed using the reflect method. :return: The dictionary that is created from the object plus an dictionary of property types. */ private class func reflectedSub(theObject:Any, reflected: MirrorType) -> (NSDictionary, Dictionary<String, String>) { var propertiesDictionary : NSMutableDictionary = NSMutableDictionary() var propertiesTypeDictionary : Dictionary<String,String> = Dictionary<String,String>() for i in 0..<reflected.count { let property = reflected[i] let key: String = property.0 let mirrorType = property.1 let value = mirrorType.value var valueType:String = "" if key != "super" || i != 0 { var skipKey = false var toKey = key if let evObject = theObject as? EVObject { if let mapping = filter(evObject.propertyMapping(), {$0.0 == key}).first { if mapping.1 == nil { skipKey = true } else { toKey = mapping.1! } } } if !skipKey { var (unboxedValue: AnyObject, valueType: String) = valueForAny(theObject, key: key, anyValue: value) if unboxedValue as? EVObject != nil { let (dict, _) = toDictionary(unboxedValue as! NSObject) propertiesDictionary.setValue(dict, forKey: toKey) } else if let array = unboxedValue as? [EVObject] { var tempValue = [NSDictionary]() for av in array { let (dict, type) = toDictionary(av) tempValue.append(dict) } unboxedValue = tempValue propertiesDictionary.setValue(unboxedValue, forKey: toKey) } else { propertiesDictionary.setValue(unboxedValue, forKey: toKey) } propertiesTypeDictionary[toKey] = valueType } } else { let (addProperties,_) = reflectedSub(value, reflected: mirrorType) for (k, v) in addProperties { propertiesDictionary.setValue(v, forKey: k as! String) } } } return (propertiesDictionary, propertiesTypeDictionary) } /** Dump the content of this object :param: theObject The object that will be loged */ public class func logObject(theObject: NSObject) { NSLog(description(theObject)) } /** Return a string representation of this object :param: theObject The object that will be loged :return: The string representation of the object */ public class func description(theObject: NSObject) -> String { var description: String = swiftStringFromClass(theObject) + " {\n hash = \(theObject.hash)\n" let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { description = description + " key = \(key), value = \(value)\n" } description = description + "}\n" return description } /** Return a Json string representation of this object :param: theObject The object that will be loged :return: The string representation of the object */ public class func toJsonString(theObject: NSObject) -> String { var (dict,_) = EVReflection.toDictionary(theObject) dict = convertDictionaryForJsonSerialization(dict) var error:NSError? = nil if var jsonData = NSJSONSerialization.dataWithJSONObject(dict , options: .PrettyPrinted, error: &error) { if var jsonString = NSString(data:jsonData, encoding:NSUTF8StringEncoding) { return jsonString as String } } return "" } /** Clean up dictionary so that it can be converted to json */ private class func convertDictionaryForJsonSerialization(dict: NSDictionary) -> NSDictionary { for (key, value) in dict { dict.setValue(convertValueForJsonSerialization(value), forKey: key as! String) } return dict } /** Clean up a value so that it can be converted to json */ private class func convertValueForJsonSerialization(value : AnyObject) -> AnyObject { switch(value) { case let stringValue as NSString: return stringValue case let numberValue as NSNumber: return numberValue case let nullValue as NSNull: return nullValue case let arrayValue as NSArray: var tempArray: NSMutableArray = NSMutableArray() for value in arrayValue { tempArray.addObject(convertValueForJsonSerialization(value)) } return tempArray case let ok as NSDictionary: return convertDictionaryForJsonSerialization(ok) case let dateValue as NSDate: var dateFormatter = NSDateFormatter() return dateFormatter.stringFromDate(dateValue) case let recordIdValue as CKRecordID: return recordIdValue.recordName default: return "\(value)" } } /** Return a dictionary representation for the json string :param: json The json string that will be converted :return: The dictionary representation of the json */ public class func dictionaryFromJson(json: String?) -> Dictionary<String, AnyObject> { if json == nil { return Dictionary<String, AnyObject>() } var error:NSError? = nil if let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding) { if let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Dictionary<String, AnyObject> { return jsonDic } } return Dictionary<String, AnyObject>() } /** Return an array representation for the json string :param: json The json string that will be converted :return: The array of dictionaries representation of the json */ public class func arrayFromJson<T where T:EVObject>(type:T, json: String?) -> [T] { if json == nil { return [T]() } var error:NSError? = nil if let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding) { if let jsonDic: [Dictionary<String, AnyObject>] = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [Dictionary<String, AnyObject>] { return jsonDic.map({T(dictionary: $0)}) } } return [T]() } /** Create a hashvalue for the object :param: theObject The object for what you want a hashvalue :return: the hashvalue for the object */ public class func hashValue(theObject: NSObject) -> Int { let (hasKeys, hasTypes) = toDictionary(theObject) return Int(map(hasKeys) {$1}.reduce(0) {(31 &* $0) &+ $1.hash}) } /** Get the swift Class type from a string :param: className The string representation of the class (name of the bundle dot name of the class) :return: The Class type */ public class func swiftClassTypeFromString(className: String) -> AnyClass! { if className.hasPrefix("_TtC") { return NSClassFromString(className) } var classStringName = className if className.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch) == nil { var appName = getCleanAppName() classStringName = "\(appName).\(className)" } return NSClassFromString(classStringName) } /** Get the app name from the 'Bundle name' and if that's empty, then from the 'Bundle identifier' otherwise we assume it's a EVReflection unit test and use that bundle identifier :return: A cleaned up name of the app. */ public class func getCleanAppName()-> String { var bundle = NSBundle.mainBundle() var appName = bundle.infoDictionary?["CFBundleName"] as? String ?? "" if appName == "" { if bundle.bundleIdentifier == nil { bundle = NSBundle(forClass: EVReflection().dynamicType) } appName = (split(bundle.bundleIdentifier!){$0 == "."}).last ?? "" } var cleanAppName = appName.stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) return cleanAppName } /** Get the swift Class from a string :param: className The string representation of the class (name of the bundle dot name of the class) :return: The Class type */ public class func swiftClassFromString(className: String) -> NSObject! { if className == "NSObject" { return NSObject() } let x: AnyClass! = swiftClassTypeFromString(className) if let anyobjectype : AnyObject.Type = swiftClassTypeFromString(className) { if let nsobjectype : NSObject.Type = anyobjectype as? NSObject.Type { var nsobject: NSObject = nsobjectype() return nsobject } } return nil } /** Get the class name as a string from a swift class :param: theObject An object for whitch the string representation of the class will be returned :return: The string representation of the class (name of the bundle dot name of the class) */ public class func swiftStringFromClass(theObject: NSObject) -> String! { var appName = getCleanAppName() let classStringName: String = NSStringFromClass(theObject.dynamicType) let classWithoutAppName: String = classStringName.stringByReplacingOccurrencesOfString(appName + ".", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) if classWithoutAppName.rangeOfString(".") != nil { NSLog("Warning! Your Bundle name should be the name of your target (set it to $(PRODUCT_NAME))") return (split(classWithoutAppName){$0 == "."}).last! } return classWithoutAppName } /** Encode any object :param: theObject The object that we want to encode. :param: aCoder The NSCoder that will be used for encoding the object. */ public class func encodeWithCoder(theObject: NSObject, aCoder: NSCoder) { let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { aCoder.encodeObject(value, forKey: key as! String) } } /** Decode any object :param: theObject The object that we want to decode. :param: aDecoder The NSCoder that will be used for decoding the object. */ public class func decodeObjectWithCoder(theObject: NSObject, aDecoder: NSCoder) { let (hasKeys, hasTypes) = toDictionary(theObject) for (key, value) in hasKeys { if aDecoder.containsValueForKey(key as! String) { var newValue: AnyObject? = aDecoder.decodeObjectForKey(key as! String) if !(newValue is NSNull) { if theObject.validateValue(&newValue, forKey: key as! String, error: nil) { theObject.setValue(newValue, forKey: key as! String) } } } } } /** Compare all fields of 2 objects :param: lhs The first object for the comparisson :param: rhs The second object for the comparisson :return: true if the objects are the same, otherwise false */ public class func areEqual(lhs: NSObject, rhs: NSObject) -> Bool { if swiftStringFromClass(lhs) != swiftStringFromClass(rhs) { return false; } let (lhsdict,_) = toDictionary(lhs) let (rhsdict,_) = toDictionary(rhs) for (key, value) in rhsdict { if let compareTo: AnyObject = lhsdict[key as! String] { if !compareTo.isEqual(value) { return false } } else { return false } } return true } /** Helper function to convert an Any to AnyObject :param: anyValue Something of type Any is converted to a type NSObject :return: The NSOBject that is created from the Any value plus the type of that value */ public class func valueForAny(parentObject:Any, key:String, anyValue: Any) -> (AnyObject, String) { var theValue = anyValue var valueType = "" let mi: MirrorType = reflect(theValue) if mi.disposition == .Optional { if mi.count == 0 { var subtype: String = "\(mi)" subtype = subtype.substringFromIndex((split(subtype) {$0 == "<"} [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) return (NSNull(), subtype) } theValue = mi[0].1.value valueType = "\(mi[0].1.valueType)" } else if mi.disposition == .Aggregate { //TODO: See if new Swift version can make using the EVRaw* protocols obsolete if let value = theValue as? EVRawString { return (value.rawValue, "\(mi.valueType)") } if let value = theValue as? EVRawInt { return (NSNumber(int: Int32(value.rawValue)), "\(mi.valueType)") } if let value = theValue as? EVRaw { if let returnValue = value.anyRawValue as? String { return (returnValue, "\(mi.valueType)") } } } else if mi.disposition == .IndexContainer { valueType = "\(mi.valueType)" if valueType.hasPrefix("Swift.Array<Swift.Optional<") { //TODO: See if new Swift version can make using the EVArrayConvertable protocol obsolete if let arrayConverter = parentObject as? EVArrayConvertable { let convertedValue = arrayConverter.convertArray(key, array: theValue) return (convertedValue, valueType) } else { NSLog("An object with a property of type Array with optional objects should implement the EVArrayConvertable protocol.") } } } else { valueType = "\(mi.valueType)" } switch(theValue) { case let numValue as NSNumber: return (numValue, "NSNumber") case let doubleValue as Double: return (NSNumber(double: doubleValue), "NSNumber") case let floatValue as Float: return (NSNumber(float: floatValue), "NSNumber") case let longValue as Int64: return (NSNumber(longLong: longValue), "NSNumber") case let longValue as UInt64: return (NSNumber(unsignedLongLong: longValue), "NSNumber") case let intValue as Int32: return (NSNumber(int: intValue), "NSNumber") case let intValue as UInt32: return (NSNumber(unsignedInt: intValue), "NSNumber") case let intValue as Int16: return (NSNumber(short: intValue), "NSNumber") case let intValue as UInt16: return (NSNumber(unsignedShort: intValue), "NSNumber") case let intValue as Int8: return (NSNumber(char: intValue), "NSNumber") case let intValue as UInt8: return (NSNumber(unsignedChar: intValue), "NSNumber") case let intValue as Int: return (NSNumber(integer: intValue), "NSNumber") case let intValue as UInt: return (NSNumber(unsignedLong: intValue), "NSNumber") case let stringValue as String: return (stringValue as NSString, "NSString") case let boolValue as Bool: return (NSNumber(bool: boolValue), "NSNumber") case let anyvalue as NSObject: return (anyvalue, valueType) default: NSLog("ERROR: valueForAny unkown type \(theValue), type \(valueType)") return (NSNull(), "NSObject") // Could not happen } } }
mit
8cdae533113c248f52de300c42b50634
42.121908
716
0.579793
5.097536
false
false
false
false
jay18001/brickkit-ios
Source/Behaviors/MinimumStickyLayoutBehavior.swift
2
1753
// // MinimumStickyLayoutBehavior.swift // BrickKit // // Created by Ruben Cagnie on 6/3/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // public protocol MinimumStickyLayoutBehaviorDataSource: StickyLayoutBehaviorDataSource { func stickyLayoutBehavior(_ behavior: StickyLayoutBehavior, minimumStickingHeightForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGFloat? } /// Allows the brick to stick, but will shrink to a minimum height first open class MinimumStickyLayoutBehavior: StickyLayoutBehavior { override func updateFrameForAttribute(_ attributes:inout BrickLayoutAttributes, sectionAttributes: BrickLayoutAttributes?, lastStickyFrame: CGRect, contentBounds: CGRect, collectionViewLayout: UICollectionViewLayout) -> Bool { _ = super.updateFrameForAttribute(&attributes, sectionAttributes: sectionAttributes, lastStickyFrame: lastStickyFrame, contentBounds: contentBounds, collectionViewLayout: collectionViewLayout) guard let minimumDataSource = dataSource as? MinimumStickyLayoutBehaviorDataSource else { return true } if let minStickyHeight = minimumDataSource.stickyLayoutBehavior(self, minimumStickingHeightForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { let heightLost = attributes.frame.origin.y - attributes.originalFrame.origin.y attributes.frame.size.height = max(attributes.originalFrame.height - heightLost, minStickyHeight) } else { attributes.frame.size.height = attributes.originalFrame.height } return true } }
apache-2.0
5c087d4ca3ac55f08668a3486726075e
52.090909
241
0.781393
5.475
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/Stair.swift
2
1643
// // Stair.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import SceneKit public final class Stair: Item, LocationConstructible, NodeConstructible { // MARK: Static static let template: SCNNode = { let resourcePath = "\(WorldConfiguration.resourcesDir)blocks/zon_stairs_a_half" let node = loadTemplate(named: resourcePath) node.position.y = -WorldConfiguration.levelHeight return node }() // MARK: Item public static let identifier: WorldNodeIdentifier = .stair public weak var world: GridWorld? public let node: NodeWrapper public var worldIndex = -1 public var isStackable: Bool { return true } public var verticalOffset: SCNFloat { return WorldConfiguration.levelHeight } // Only stairs which were initialized directly (not from an existing node) require geometry. let needsGeometry: Bool public init() { needsGeometry = true node = NodeWrapper(identifier: .stair) } init?(node: SCNNode) { guard node.identifier == .stair else { return nil } needsGeometry = false self.node = NodeWrapper(node) } // MARK: public func loadGeometry() { guard needsGeometry && scnNode.childNodes.isEmpty else { return } scnNode.addChildNode(Stair.template.clone()) } } import PlaygroundSupport extension Stair: MessageConstructor { // MARK: MessageConstructor var message: PlaygroundValue { return .array(baseMessage) } }
mit
31cc2c89e7495dae1645d6d184ebcc17
22.140845
96
0.62325
4.748555
false
false
false
false
naru-jpn/pencil
PencilTests/DoubleSpec.swift
1
1813
// // DoubleSpec.swift // Pencil // // Created by naru on 2016/10/17. // Copyright © 2016年 naru. All rights reserved. // import Foundation import Quick import Nimble @testable import Pencil class DoubleSpec: QuickSpec { override func spec() { describe("Double") { context("for positive") { it("can be encode/decode") { let num: Double = 5.0 let data: Data = num.data expect(Double.value(from: data)).to(equal(num)) } } context("for negative") { it("can be encode/decode") { let num: Double = -5.0 let data: Data = num.data expect(Double.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: Double = 0.0 let data: Data = num.data expect(Double.value(from: data)).to(equal(num)) } } context("for greatest finite number") { it("can be encode/decode") { let num: Double = Double.greatestFiniteMagnitude let data: Data = num.data expect(Double.value(from: data)).to(equal(num)) } } context("for least positive number") { it("can be encode/decode") { let num: Double = Double.leastNonzeroMagnitude let data: Data = num.data expect(Double.value(from: data)).to(equal(num)) } } } } }
mit
631a64e742b883c7f992bbd32debd18a
28.672131
68
0.432597
4.905149
false
false
false
false
txlong/iOS
swift/03-ControlFlow/03-ControlFlow/main.swift
1
1950
// // main.swift // 03-ControlFlow // // Created by iAnonymous on 15/7/5. // Copyright (c) 2015年 iAnonymous. All rights reserved. // let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } println(teamScore) var optionString:String? = "Hello" println(optionString == nil) //var optionName:String? = "John Appleseed" var optionName:String? = nil var greeting = "Hello!" if let name = optionName { greeting = "Hello \(name)" } else { greeting = "new string" } println(greeting) let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("papper"): let vegetableComment = "Is it a spicy \(x)" default: let vegetableComment = "Everything tastes good in soup." } // 运行switch中匹配到的字句之后,程序会推出switch,并不会继续向下运行,所以不需要在每个语句后边写break let interestingNumber = [ "Prime":[2, 3, 5, 7, 11, 13], "Fibonacci":[1, 1, 2, 3, 5, 8], "Square":[1, 4, 9, 16, 25] ] var largest = 0 var largestKind = "" for (kind, numbers) in interestingNumber { for number in numbers { if number > largest { largest = number largestKind = kind } } } println(largest) println(largestKind) var n = 2 while n < 100 { n = n * 2 } println(n) var m = 2 do { m = m * 2 } while m < 100 println(m) var firstForLoop = 0 for i in 0..<4 { firstForLoop += i } println(firstForLoop) var secondForLoop = 0 for var i = 0; i < 4; ++i { secondForLoop += i } println(secondForLoop) // 使用..<创建的范围不包括商界,如果想要包含的话需要使用...
gpl-2.0
dc246b6cbe654c899c3f2f202b8062ad
19.647727
73
0.625
3.202822
false
false
false
false
Xiomara7/cv
Xiomara-Figueroa/AboutViewController.swift
1
5567
// // AboutViewController.swift // Xiomara-Figueroa // // Created by Xiomara on 4/25/15. // Copyright (c) 2015 UPRRP. All rights reserved. // import UIKit class AboutViewController: UIViewController { init() { super.init(nibName: nil, bundle: nil) self.title = "About" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() let width = UIScreen.mainScreen().bounds.width let height = UIScreen.mainScreen().bounds.height self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.tintColor = UIColor.blackColor() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"cancel"), style:.Done, target:self, action:Selector("dismissAction:")) let topView = UIImageView(frame: CGRectMake(0.0, 0.0, width, height / 2)) let bottomView = UIImageView(frame: CGRectMake(0.0, width, width, height / 2)) let imageViewSize = UIImageView(frame: CGRectMake(0.0, 0.0, width, height / 2)) let aboutMe = UILabel(frame: CGRectZero) aboutMe.text = DataManager.shared.about aboutMe.font = UIFont.systemFontOfSize(12.0) aboutMe.tintColor = UIColor.grayColor() aboutMe.numberOfLines = 0 aboutMe.lineBreakMode = .ByTruncatingTail aboutMe.preferredMaxLayoutWidth = width - 20.0 aboutMe.textAlignment = .Center aboutMe.sizeToFit() let profileImage = UIImageView(image: UIImage(named:"button_About")) profileImage.sizeToFit() profileImage.backgroundColor = UIColor.whiteColor() let twitterLogo = customLogo(imageName: "twitter") twitterLogo.addTarget(self, action: Selector("twitterAction:"), forControlEvents: .AllTouchEvents) let githubLogo = customLogo(imageName: "github") githubLogo.addTarget(self, action: Selector("githubAction:"), forControlEvents: .AllTouchEvents) let mediumLogo = customLogo(imageName: "medium") mediumLogo.addTarget(self, action: Selector("mediumAction:"), forControlEvents: .AllTouchEvents) self.view.addSubview(profileImage) self.view.addSubview(imageViewSize) self.view.addSubview(twitterLogo) self.view.addSubview(githubLogo) self.view.addSubview(mediumLogo) self.view.addSubview(aboutMe) self.view.addSubview(topView) self.view.addSubview(bottomView) // AutoLayout profileImage.autoAlignAxis(.Horizontal, toSameAxisOfView: topView) profileImage.autoAlignAxis(.Vertical, toSameAxisOfView: topView) profileImage.autoAlignAxis(.Horizontal, toSameAxisOfView: imageViewSize) profileImage.autoAlignAxis(.Vertical, toSameAxisOfView: imageViewSize) twitterLogo.autoPinEdge(.Top, toEdge: .Bottom, ofView: profileImage, withOffset: 20.0) twitterLogo.autoPinEdgeToSuperviewEdge(.Left, withInset: 44.0) mediumLogo.autoPinEdge(.Top, toEdge: .Bottom, ofView: profileImage, withOffset: 20.0) mediumLogo.autoPinEdge(.Left, toEdge: .Right, ofView: twitterLogo, withOffset: 10.0) mediumLogo.autoAlignAxis(.Vertical, toSameAxisOfView: profileImage) githubLogo.autoPinEdge(.Top, toEdge: .Bottom, ofView: profileImage, withOffset: 20.0) githubLogo.autoPinEdge(.Left, toEdge: .Right, ofView: mediumLogo, withOffset: 20.0) aboutMe.autoPinEdge(.Top, toEdge: .Bottom, ofView: twitterLogo, withOffset: 20.0) aboutMe.autoAlignAxis(.Vertical, toSameAxisOfView: bottomView) } class customLogo: UIButton { init(imageName: String) { super.init(frame:CGRectZero) self.layer.cornerRadius = 5.0 self.layer.masksToBounds = true self.setImage(UIImage(named: imageName), forState: .Normal) self.backgroundColor = UIColor.whiteColor() self.sizeToFit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } func dismissAction(sender: AnyObject?) { self.dismissViewControllerAnimated(true, completion: nil) } func twitterAction(sender: AnyObject?) { let page = WebViewController(url: "https://twitter.com/@_xiomara7") let pageNav = UINavigationController(rootViewController: page) self.presentViewController(pageNav, animated: true, completion: nil) } func mediumAction(sender: AnyObject?) { let page = WebViewController(url: "https://medium.com/@figueroa_xio") let pageNav = UINavigationController(rootViewController: page) self.presentViewController(pageNav, animated: true, completion: nil) } func githubAction(sender: AnyObject?) { let page = WebViewController(url: "https://github.com/xiomara7") let pageNav = UINavigationController(rootViewController: page) self.presentViewController(pageNav, animated: true, completion: nil) } }
mit
458bc2f0965b6682c7cd0530cafa5e51
39.642336
106
0.637147
4.997307
false
false
false
false
adams0619/AngelHacks8-App
AngelHacksCaitlyn/AngelHacksCaitlyn/AppDelegate.swift
1
4115
/* The MIT License (MIT) Copyright (c) 2015 Adams, Jevin, Caitlyn, Sara 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. */ // // AppDelegate.swift // AngelHacksCaitlyn // // Created by Caitlyn Chen on 7/18/15. // Copyright (c) 2015 Caitlyn Chen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().barTintColor = UIColor(red: 101/255.0, green: 92/255.0, blue: 155/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().translucent = false UIToolbar.appearance().barTintColor = UIColor(red: 101/255.0, green: 92/255.0, blue: 155/255.0, alpha: 1.0) UIToolbar.appearance().tintColor = UIColor.whiteColor() UIToolbar.appearance().translucent = false UITabBar.appearance().barTintColor = UIColor(red: 101/255.0, green: 92/255.0, blue: 155/255.0, alpha: 1.0) UITabBar.appearance().tintColor = UIColor.whiteColor() UITabBar.appearance().translucent = false return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ec0c391dfccd624423fe51c1d863404c
46.848837
285
0.748481
4.957831
false
false
false
false
Estimote/iOS-Mirror-SDK
Tools/Mirrorator/ios/Mirrorator/Helpers/MirrorHelper.swift
1
2998
// // MirrorHelper.swift // Mirrorator // // Created by Mac Book on 31/07/2017. // Copyright © 2017 Facebook. All rights reserved. // import Foundation import MirrorCoreSDK @objc(MirrorHelper) class MirrorHelper: NSObject { var logger = Logger.init() var treshold: Int = 50 var mirror: EMSDeviceMirror? lazy var manager: EMSDeviceManager = { let m = EMSDeviceManager.init() m.delegate = self return m }() override init() { super.init() DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.startScan() } } @objc(sendData:) func sendData(data: NSDictionary) { var message: [String:String] = [:] _ = data.map({ let m = ($0.value as! [String:String]) message += [m["key"]! : m["value"]!] }) self.mirror?.display(message, completion: { error in guard error == nil else { self.logger.history += .failedToDisplay(error: error!) return } self.logger.history += .successDisplaying(data: message) }) } @objc(setThreshold:) func setThreshold(t: NSInteger) { self.treshold = t guard self.mirror != nil else { return } if (abs((self.mirror?.rssi.i32)!) > self.treshold) { self.mirror?.disconnect() } } @objc(sync) func sync() { self.mirror?.synchronizeSettings(completion: { error in self.logger.history += .synchronizedSettings(error: error) }) } func startScan() { self.manager.startDeviceDiscovery(with: EMSDeviceFilterMirror.init()) } } extension MirrorHelper: EMSDeviceManagerDelegate { func deviceManager(_ manager: EMSDeviceManager, didDiscoverDevices devices: [Any]) { let mirror = (devices as! [EMSDeviceConnectable]) .sorted(by: { $0.0.rssi > $0.1.rssi }) .filter({ abs($0.rssi) < treshold }) .first mirror?.delegate = self mirror?.connect() self.logger.history += .attemptingToConnect } func emsDevice(_ device: EMSDeviceConnectable, didUpdateRSSI RSSI: NSNumber, withError error: Error?) { self.logger.history += Log.rssiUpdate(RSSI: abs(RSSI.intValue)) } } extension MirrorHelper: EMSDeviceConnectableDelegate { func emsDeviceConnectionDidSucceed(_ device: EMSDeviceConnectable) { guard let mirror = device as? EMSDeviceMirror else { return } self.mirror = mirror self.manager.stopDeviceDiscovery() self.logger.history += Log.identifierMessage(device: self.mirror) } func emsDevice(_ device: EMSDeviceConnectable, didDisconnectWithError error: Error?) { print("disconnected") self.mirror = nil self.manager.startDeviceDiscovery(with: EMSDeviceFilterMirror.init()) } } extension MirrorHelper { func deviceManagerDidFailDiscovery(_ manager: EMSDeviceManager) { self.logger.history += Log.say("failed discovery") } func emsDevice(_ device: EMSDeviceConnectable, didFailConnectionWithError error: Error) { self.logger.history += Log.say("failed to connect") } }
apache-2.0
53c0de9a5e9d5a69fe4fbd0827413baf
26
105
0.664998
3.872093
false
false
false
false
yura-voevodin/SumDUBot
Sources/App/Managers/ScheduleImportManager.swift
1
1910
// // ScheduleImportManager.swift // SumDUBot // // Created by Yura Voevodin on 11.03.17. // // import Vapor import HTTP import Foundation import FluentPostgreSQL struct ScheduleImportManager { // MARK: - Types /// Import errors enum ImportError: Swift.Error { case failedGetArray case missingObjectID case missingObject } // MARK: - Methods /// Make request of schedule for object // static func makeRequestOfSchedule(for type: ObjectType, id: Int, client: ClientFactoryProtocol) throws -> Response { // var groupId = "0" // var teacherId = "0" // var auditoriumId = "0" // switch type { // case .auditorium: // auditoriumId = String(id) // case .group: // groupId = String(id) // case .teacher: // teacherId = String(id) // } // // // Time interval for request // let startDate = Date() // let oneDay: TimeInterval = 60*60*24*8 // let endDate = startDate.addingTimeInterval(oneDay) // // let baseURL = "http://schedule.sumdu.edu.ua/index/json?method=getSchedules" // let query = "&id_grp=\(groupId)&id_fio=\(teacherId)&id_aud=\(auditoriumId)&date_beg=\(startDate.serverDate)&date_end=\(endDate.serverDate)" // // return try client.get(baseURL + query) // } // static func importSchedule(for type: ObjectType, id: Int, client: ClientFactoryProtocol) throws { // // Make request and node from JSON response // let scheduleResponse = try makeRequestOfSchedule(for: type, id: id, client: client) // guard let responseArray = scheduleResponse.json?.array else { throw ImportError.failedGetArray } // for item in responseArray { // let record = try Record.row(from: item) // try record.save() // } // } }
mit
b8844fca313bb2dc676fe86186f5a45d
30.311475
149
0.597906
3.827655
false
false
false
false
ckrey/mqttswift
Sources/MqttControlPacketType.swift
1
337
enum MqttControlPacketType: UInt8 { case Reserved = 0 case CONNECT = 1 case CONNACK = 2 case PUBLISH = 3 case PUBACK = 4 case PUBREC = 5 case PUBREL = 6 case PUBCOMP = 7 case SUBSCRIBE = 8 case SUBACK = 9 case UNSUBSCRIBE = 10 case UNSUBACK = 11 case PINGREQ = 12 case PINGRESP = 13 case DISCONNECT = 14 case AUTH = 15 }
gpl-3.0
89fa2d3d638ee1c1e57b4b7ce6ab4504
17.722222
35
0.691395
2.739837
false
false
false
false
YMXian/Deliria
Deliria/Deliria/Crypto/Int+Extension.swift
1
3198
// // IntExtension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 12/08/14. // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. #if os(Linux) import Glibc #else import Darwin import Foundation #endif /* array of bits */ extension Int { init(bits: [Bit]) { self.init(bitPattern: integerFrom(bits) as UInt) } } /* array of bytes */ extension Int { /** Int with collection of bytes (little-endian) */ init<T: Collection>(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { self = bytes.toInteger() } /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = MemoryLayout<Int>.size) -> Array<UInt8> { return arrayOfBytes(value: self, length: totalBytes) } } /** Shift bits */ extension Int { /** Shift bits to the left. All bits are shifted (including sign bit) */ mutating func shiftLeft(by count: Int) { self = Deliria.shiftLeft(self, by: count) //FIXME: count: } /** Shift bits to the right. All bits are shifted (including sign bit) */ mutating func shiftRight(by count: Int) { if (self == 0) { return } let bitsCount = MemoryLayout<Int>.size * 8 if (count >= bitsCount) { return } let maxBitsForValue = Swift.Int(floor(log2(Swift.Double(self)) + 1)) let shiftCount = Swift.min(count, maxBitsForValue - 1) var shiftedValue: Int = 0 for bitIdx in 0..<bitsCount { // if bit is set then copy to result and shift left 1 let bit = 1 << bitIdx if ((self & bit) == bit) { shiftedValue = shiftedValue | (bit >> shiftCount) } } self = Swift.Int(shiftedValue) } } // Left operator /** shift left and assign with bits truncation */ func &<<= (lhs: inout Int, rhs: Int) { lhs.shiftLeft(by: rhs) } /** shift left with bits truncation */ func &<< (lhs: Int, rhs: Int) -> Int { var l = lhs l.shiftLeft(by: rhs) return l } // Right operator /** shift right and assign with bits truncation */ func &>>= (lhs: inout Int, rhs: Int) { lhs.shiftRight(by: rhs) } /** shift right and assign with bits truncation */ func &>> (lhs: Int, rhs: Int) -> Int { var l = lhs l.shiftRight(by: rhs) return l }
mit
4ee7e6fbbb859118a2845f61f7ec3340
28.601852
217
0.639349
3.951792
false
false
false
false
Jinxiaoming/ExSwift
ExSwiftTests/NSDateExtensionsTests.swift
24
9201
// // NSDateExtensionsTests.swift // ExSwift // // Created by Piergiuseppe Longo on 23/11/14. // Copyright (c) 2014 pNre. All rights reserved. // import Quick import Nimble class NSDateExtensionsSpec: QuickSpec { let dateFormatter = NSDateFormatter() var startDate: NSDate? override func spec() { beforeSuite { self.dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss" } beforeEach { self.startDate = self.dateFormatter.dateFromString("30/11/1988 00:00:00") } describe("manipulation") { it("addSeconds") { var expectedDate = self.dateFormatter.dateFromString("30/11/1988 00:00:42") expect(self.startDate?.addSeconds(42)) == expectedDate expect(self.startDate?.add(seconds: 42)) == expectedDate expectedDate = self.dateFormatter.dateFromString("29/11/1988 23:59:18") expect(self.startDate?.addSeconds(-42)) == expectedDate expect(self.startDate?.add(seconds: -42)) == expectedDate } it("addMinutes") { var expectedDate = self.dateFormatter.dateFromString("30/11/1988 00:42:00") expect(self.startDate?.addMinutes(42)) == expectedDate expect(self.startDate?.add(minutes: 42)) == expectedDate expectedDate = self.dateFormatter.dateFromString("29/11/1988 23:18:00") expect(self.startDate?.addMinutes(-42)) == expectedDate expect(self.startDate?.add(minutes: -42)) == expectedDate } it("addHours") { var expectedDate = self.dateFormatter.dateFromString("01/12/1988 18:00:00") expect(self.startDate?.addHours(42)) == expectedDate expect(self.startDate?.add(hours: 42)) == expectedDate expectedDate = self.dateFormatter.dateFromString("28/11/1988 06:00:00") expect(self.startDate?.addHours(-42)) == expectedDate expect(self.startDate?.add(hours: -42)) == expectedDate } it("addDays") { var expectedDate = self.dateFormatter.dateFromString("02/12/1988 00:00:00") expect(self.startDate?.addDays(2)) == expectedDate expect(self.startDate?.add(days: 2)) == expectedDate expectedDate = self.dateFormatter.dateFromString("19/10/1988 00:00:00") expect(self.startDate?.addDays(-42)) == expectedDate expect(self.startDate?.add(days: -42)) == expectedDate } it("addWeeks") { var expectedDate = self.dateFormatter.dateFromString("7/12/1988 00:00:00") expect(self.startDate?.addWeeks(1)) == expectedDate expect(self.startDate?.add(weeks: 1)) == expectedDate expectedDate = self.dateFormatter.dateFromString("23/11/1988 00:00:00") expect(self.startDate?.addWeeks(-1)) == expectedDate expect(self.startDate?.add(weeks: -1)) == expectedDate } it("addMonths") { var expectedDate = self.dateFormatter.dateFromString("30/12/1988 00:00:00") expect(self.startDate?.addMonths(1)) == expectedDate expect(self.startDate?.add(months: 1)) == expectedDate expectedDate = self.dateFormatter.dateFromString("30/10/1988 00:00:00") expect(self.startDate?.addMonths(-1)) == expectedDate expect(self.startDate?.add(months: -1)) == expectedDate } it("addYears") { var expectedDate = self.dateFormatter.dateFromString("30/11/1989 00:00:00") expect(self.startDate?.addYears(1)) == expectedDate expect(self.startDate?.add(years: 1)) == expectedDate expectedDate = self.dateFormatter.dateFromString("30/11/1987 00:00:00") expect(self.startDate?.addYears(-1)) == expectedDate expect(self.startDate?.add(years: -1)) == expectedDate } it("add") { var expectedDate = self.dateFormatter.dateFromString("10/01/1990 18:42:42") expect(self.startDate?.add(seconds: 42, minutes: 42, hours: 42, days: 2, weeks: 1 , months: 1, years: 1)) == expectedDate expectedDate = self.dateFormatter.dateFromString("20/10/1987 22:17:18") expect(self.startDate?.add(seconds: -42, minutes: -42, hours: -1, days: -2, weeks: -1 , months: -1, years: -1)) == expectedDate } } describe("comparison") { it("isAfter") { let date = NSDate() var futureDate = date.addSeconds(42) var pastDate = date.addSeconds(-42) expect(futureDate.isAfter(date)).to(beTrue()) expect(date.isAfter(date)).to(beFalse()) expect(pastDate.isAfter(date)).to(beFalse()) } it("isBefore") { let date = NSDate() var futureDate = date.addSeconds(42) var pastDate = date.addSeconds(-42) expect(futureDate.isBefore(date)).to(beFalse()) expect(date.isBefore(date)).to(beFalse()) expect(pastDate.isBefore(date)).to(beTrue()) } } it("components properties") { expect(self.startDate!.year) == 1988 expect(self.startDate!.month) == 11 expect(self.startDate!.days) == 30 expect(self.startDate!.hours) == 0 expect(self.startDate!.minutes) == 0 expect(self.startDate!.seconds) == 0 expect(self.startDate!.weekday) == 4 expect(self.startDate!.weekMonth) == 5 } describe("comparable") { it("sorting") { let firstDate = self.startDate!.addSeconds(0) let secondDate = self.startDate!.addSeconds(42) let thirdDate = self.startDate!.addSeconds(-42) let fourthDate = self.startDate!.addSeconds(-84) let fifthDate = self.startDate!.addSeconds(84) var dates = [thirdDate, secondDate, firstDate, fourthDate, fifthDate] let expected = [fifthDate, secondDate, firstDate, thirdDate, fourthDate] let expectedReverded = expected.reverse() for i in 0 ... 42 { dates.shuffle() dates.sort( { $0 > $1 } ) expect(dates) == expected dates.sort( { $0 < $1 } ) expect(dates) == expectedReverded } } it("comparable") { let date = self.startDate!.addSeconds(-42) let anotherDate = self.startDate!.addSeconds(42) let shouldBeTheSameDate = NSDate(timeInterval: 0, sinceDate: self.startDate!) expect(self.startDate) == shouldBeTheSameDate expect(self.startDate) > date expect(self.startDate) >= date expect(self.startDate) <= anotherDate expect(self.startDate) < anotherDate expect(date) != self.startDate expect(anotherDate) != self.startDate } } it("arithmetic") { let date = NSDate() as NSDate expect(date.timeIntervalSinceDate(date - 1.hour)) == 1.hour expect(date.timeIntervalSinceDate(date + 1.hour)) == -1.hour var otherDate = date otherDate -= 1.minute expect(otherDate) !== date expect(date.timeIntervalSinceDate(otherDate)) == 1.minute otherDate += 1.hour expect(date.timeIntervalSinceDate(otherDate)) == 1.minute - 1.hour } } }
bsd-2-clause
e276eb6cb9b67253d7c08abc3ec700b0
34.662791
143
0.476361
5.412353
false
false
false
false
kylef/CommandKit
Tests/CommanderTests/GroupSpec.swift
1
5075
import Spectre import Commander extension ExpectationType where ValueType == CommandType { func run(_ arguments: [String]) throws -> Expectation<Void> { if let command = try expression() { return expect { try command.run(arguments) } } throw failure("command was nil") } } public func testGroup() { describe("Group") { $0.it("dispatches subcommands when ran") { var didRunHelpCommand = false let group = Group() group.addCommand("help", command { didRunHelpCommand = true }) try expect(didRunHelpCommand).to.beFalse() try expect(group).run(["unknown"]).toThrow() try expect(didRunHelpCommand).to.beFalse() try group.run(["help"]) try expect(didRunHelpCommand).to.beTrue() } $0.it("catches and reraises errors with command name") { let group = Group { $0.group("subgroup") { $0.command("command") {} } } try expect(group).run(["subgroup", "yo"]).toThrow(GroupError.unknownCommand("subgroup yo")) } $0.it("throws an error when the command name is missing") { let group = Group() do { try group.run([]) throw failure("Didn't raise an error") } catch GroupError.noCommand(let path, let raisedGroup) { try expect(path).to.beNil() if raisedGroup !== group { throw failure("\(raisedGroup) is not \(group)") } } catch { throw error } } $0.it("reraises missing sub-group command name including command name") { let subgroup = Group() let group = Group { $0.addCommand("group", subgroup) } try expect(group).run(["group"]).toThrow(GroupError.noCommand("group", subgroup)) } $0.it("reraises missing sub-sub-group command name including group and command name") { let subsubgroup = Group() let subgroup = Group { $0.addCommand("g2", subsubgroup) } let group = Group { $0.addCommand("g1", subgroup) } try expect(group).run(["g1", "g2"]).toThrow(GroupError.noCommand("g1 g2", subsubgroup)) } $0.it("calls unknownCommand property when present") { let group = Group { $0.unknownCommand = { (_, _) in throw GroupError.unknownCommand("gotcha!") } } try expect(group).run(["yo"]).toThrow(GroupError.unknownCommand("gotcha!")) } $0.it("calls noCommand property when present") { let subgroup = Group() let group = Group { $0.addCommand("g1", subgroup) $0.noCommand = { (_, group, _) in throw GroupError.noCommand("gotcha!", group) } } try expect(group).run([]).toThrow(GroupError.noCommand("gotcha!", group)) try expect(group).run(["g1"]).toThrow(GroupError.noCommand("gotcha!", subgroup)) } $0.it("calls noCommand property when present") { let group = Group() group.noCommand = { _, _, _ in throw GroupError.noCommand("gotcha!", group) } try expect(group).run([]).toThrow(GroupError.noCommand("gotcha!", group)) } $0.describe("extensions") { $0.it("has a convinience initialiser calling a builder closure") { var didRunHelpCommand = false let group = Group { $0.addCommand("help", command { didRunHelpCommand = true }) } try expect(group).run(["unknown"]).toThrow() try expect(didRunHelpCommand).to.beFalse() try group.run(["help"]) try expect(didRunHelpCommand).to.beTrue() } $0.it("has a convinience sub-group function") { var didRun = false try Group { $0.group("group") { $0.command("test") { didRun = true } } }.run(["group", "test"]) try expect(didRun).to.beTrue() } $0.it("has a convinience sub-command function") { var didRun = false try Group { $0.command("test") { didRun = true } }.run(["test"]) try expect(didRun).to.beTrue() } $0.it("has a convinience sub-command function with arguments") { var givenName:String? = nil try Group { $0.command("test") { (name:String) in givenName = name } }.run(["test", "kyle"]) try expect(givenName) == "kyle" } } } describe("Group") { let group = Group { $0.command("create") {} $0.command("lint") {} } $0.describe("error description") { $0.it("unknown command") { let error = GroupError.unknownCommand("pod spec create") try expect(error.description) == "Unknown command: `pod spec create`" } $0.it("no command") { let error = GroupError.noCommand("pod lib", group) try expect(error.description) == "Usage: pod lib COMMAND\n\nCommands: create, lint" } $0.it("no command without path") { let error = GroupError.noCommand(nil, group) try expect(error.description) == "Commands: create, lint" } } } }
bsd-3-clause
b8c2c125ddc6f4bd03928216b4c3af7d
26.73224
97
0.570837
3.971049
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Me/Me Main/MeViewController.swift
1
21856
import UIKit import CocoaLumberjack import WordPressShared import Gridicons import WordPressAuthenticator import AutomatticAbout class MeViewController: UITableViewController { var handler: ImmuTableViewHandler! // MARK: - Table View Controller override init(style: UITableView.Style) { super.init(style: style) navigationItem.title = NSLocalizedString("Me", comment: "Me page title") MeViewController.configureRestoration(on: self) clearsSelectionOnViewWillAppear = false } required convenience init() { self.init(style: .grouped) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationReceivedNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationClearedNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Preventing MultiTouch Scenarios view.isExclusiveTouch = true ImmuTable.registerRows([ NavigationItemRow.self, IndicatorNavigationItemRow.self, ButtonRow.self, DestructiveButtonRow.self ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) WPStyleGuide.configureAutomaticHeightRows(for: tableView) NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.accountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.accessibilityIdentifier = "Me Table" reloadViewModel() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.layoutHeaderView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshAccountDetails() if splitViewControllerIsHorizontallyCompact { animateDeselectionInteractively() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) registerUserActivity() } @objc fileprivate func accountDidChange() { reloadViewModel() } @objc fileprivate func reloadViewModel() { let account = defaultAccount() let loggedIn = account != nil // Warning: If you set the header view after the table model, the // table's top margin will be wrong. // // My guess is the table view adjusts the height of the first section // based on if there's a header or not. tableView.tableHeaderView = account.map { headerViewForAccount($0) } // Then we'll reload the table view model (prompting a table reload) handler.viewModel = tableViewModel(loggedIn) } fileprivate func headerViewForAccount(_ account: WPAccount) -> MeHeaderView { headerView.displayName = account.displayName headerView.username = account.username headerView.gravatarEmail = account.email return headerView } private var appSettingsRow: NavigationItemRow { let accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator return NavigationItemRow( title: RowTitles.appSettings, icon: .gridicon(.phone), accessoryType: accessoryType, action: pushAppSettings(), accessibilityIdentifier: "appSettings") } fileprivate func tableViewModel(_ loggedIn: Bool) -> ImmuTable { let accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator let myProfile = NavigationItemRow( title: RowTitles.myProfile, icon: .gridicon(.user), accessoryType: accessoryType, action: pushMyProfile(), accessibilityIdentifier: "myProfile") let qrLogin = NavigationItemRow( title: RowTitles.qrLogin, icon: .gridicon(.camera), accessoryType: accessoryType, action: presentQRLogin(), accessibilityIdentifier: "qrLogin") let accountSettings = NavigationItemRow( title: RowTitles.accountSettings, icon: .gridicon(.cog), accessoryType: accessoryType, action: pushAccountSettings(), accessibilityIdentifier: "accountSettings") let helpAndSupportIndicator = IndicatorNavigationItemRow( title: RowTitles.support, icon: .gridicon(.help), showIndicator: ZendeskUtils.showSupportNotificationIndicator, accessoryType: accessoryType, action: pushHelp()) let logIn = ButtonRow( title: RowTitles.logIn, action: presentLogin()) let logOut = DestructiveButtonRow( title: RowTitles.logOut, action: logoutRowWasPressed(), accessibilityIdentifier: "logOutFromWPcomButton") let wordPressComAccount = HeaderTitles.wpAccount return ImmuTable(sections: [ // first section .init(rows: { var rows: [ImmuTableRow] = [appSettingsRow] if loggedIn { var loggedInRows = [myProfile, accountSettings] if AppConfiguration.qrLoginEnabled && FeatureFlag.qrLogin.enabled { loggedInRows.append(qrLogin) } rows = loggedInRows + rows } return rows }()), // middle section .init(rows: { var rows: [ImmuTableRow] = [helpAndSupportIndicator] rows.append(NavigationItemRow(title: ShareAppContentPresenter.RowConstants.buttonTitle, icon: ShareAppContentPresenter.RowConstants.buttonIconImage, accessoryType: accessoryType, action: displayShareFlow(), loading: sharePresenter.isLoading)) rows.append(NavigationItemRow(title: RowTitles.about, icon: UIImage.gridicon(AppConfiguration.isJetpack ? .plans : .mySites), accessoryType: .disclosureIndicator, action: pushAbout(), accessibilityIdentifier: "About")) return rows }()), // last section .init(headerText: wordPressComAccount, rows: { return [loggedIn ? logOut : logIn] }()) ]) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let isNewSelection = (indexPath != tableView.indexPathForSelectedRow) if isNewSelection { return indexPath } else { return nil } } // MARK: - Actions fileprivate var myProfileViewController: UIViewController? { guard let account = self.defaultAccount() else { let error = "Tried to push My Profile without a default account. This shouldn't happen" assertionFailure(error) DDLogError(error) return nil } return MyProfileViewController(account: account) } fileprivate func pushMyProfile() -> ImmuTableAction { return { [unowned self] row in if let myProfileViewController = self.myProfileViewController { WPAppAnalytics.track(.openedMyProfile) self.navigationController?.pushViewController(myProfileViewController, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } } fileprivate func pushAccountSettings() -> ImmuTableAction { return { [unowned self] row in if let account = self.defaultAccount() { WPAppAnalytics.track(.openedAccountSettings) guard let controller = AccountSettingsViewController(account: account) else { return } self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } } private func presentQRLogin() -> ImmuTableAction { return { [weak self] row in guard let self = self else { return } self.tableView.deselectSelectedRowWithAnimation(true) QRLoginCoordinator.present(from: self, origin: .menu) } } func pushAppSettings() -> ImmuTableAction { return { [unowned self] row in WPAppAnalytics.track(.openedAppSettings) let controller = AppSettingsViewController() self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } func pushHelp() -> ImmuTableAction { return { [unowned self] row in let controller = SupportTableViewController(style: .insetGrouped) self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } private func pushAbout() -> ImmuTableAction { return { [unowned self] _ in let configuration = AppAboutScreenConfiguration(sharePresenter: self.sharePresenter) let controller = AutomatticAboutScreen.controller(appInfo: AppAboutScreenConfiguration.appInfo, configuration: configuration, fonts: AppAboutScreenConfiguration.fonts) self.present(controller, animated: true) { self.tableView.deselectSelectedRowWithAnimation(true) } } } func displayShareFlow() -> ImmuTableAction { return { [unowned self] row in defer { self.tableView.deselectSelectedRowWithAnimation(true) } guard let selectedIndexPath = self.tableView.indexPathForSelectedRow, let selectedCell = self.tableView.cellForRow(at: selectedIndexPath) else { return } self.sharePresenter.present(for: AppConstants.shareAppName, in: self, source: .me, sourceView: selectedCell) } } fileprivate func presentLogin() -> ImmuTableAction { return { [unowned self] row in self.tableView.deselectSelectedRowWithAnimation(true) self.promptForLoginOrSignup() } } fileprivate func logoutRowWasPressed() -> ImmuTableAction { return { [unowned self] row in self.tableView.deselectSelectedRowWithAnimation(true) self.displayLogOutAlert() } } /// Selects the My Profile row and pushes the Support view controller /// @objc public func navigateToMyProfile() { navigateToTarget(for: RowTitles.myProfile) } /// Selects the Account Settings row and pushes the Account Settings view controller /// @objc public func navigateToAccountSettings() { navigateToTarget(for: RowTitles.accountSettings) } /// Selects the App Settings row and pushes the App Settings view controller /// @objc public func navigateToAppSettings() { navigateToTarget(for: appSettingsRow.title) } /// Selects the Help & Support row and pushes the Support view controller /// @objc public func navigateToHelpAndSupport() { navigateToTarget(for: RowTitles.support) } fileprivate func navigateToTarget(for rowTitle: String) { let matchRow: ((ImmuTableRow) -> Bool) = { row in if let row = row as? NavigationItemRow { return row.title == rowTitle } else if let row = row as? IndicatorNavigationItemRow { return row.title == rowTitle } return false } if let sections = handler?.viewModel.sections, let section = sections.firstIndex(where: { $0.rows.contains(where: matchRow) }), let row = sections[section].rows.firstIndex(where: matchRow) { let indexPath = IndexPath(row: row, section: section) tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle) handler.tableView(self.tableView, didSelectRowAt: indexPath) } } // MARK: - Helpers // FIXME: (@koke 2015-12-17) Not cool. Let's stop passing managed objects // and initializing stuff with safer values like userID fileprivate func defaultAccount() -> WPAccount? { return try? WPAccount.lookupDefaultWordPressComAccount(in: ContextManager.shared.mainContext) } fileprivate func refreshAccountDetails() { guard let account = defaultAccount() else { reloadViewModel() return } let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) service.updateUserDetails(for: account, success: { [weak self] in self?.reloadViewModel() }, failure: { error in DDLogError(error.localizedDescription) }) } // MARK: - LogOut private func displayLogOutAlert() { let alert = UIAlertController(title: logOutAlertTitle, message: nil, preferredStyle: .alert) alert.addActionWithTitle(LogoutAlert.cancelAction, style: .cancel) alert.addActionWithTitle(LogoutAlert.logoutAction, style: .destructive) { [weak self] _ in self?.dismiss(animated: true) { AccountHelper.logOutDefaultWordPressComAccount() } } present(alert, animated: true) } private var logOutAlertTitle: String { let context = ContextManager.sharedInstance().mainContext let count = AbstractPost.countLocalPosts(in: context) guard count > 0 else { return LogoutAlert.defaultTitle } let format = count > 1 ? LogoutAlert.unsavedTitlePlural : LogoutAlert.unsavedTitleSingular return String(format: format, count) } // MARK: - Private Properties fileprivate lazy var headerView: MeHeaderView = { let headerView = MeHeaderView() headerView.onGravatarPress = { [weak self] in guard let strongSelf = self else { return } strongSelf.presentGravatarPicker(from: strongSelf) } headerView.onDroppedImage = { [weak self] image in let imageCropViewController = ImageCropViewController(image: image) imageCropViewController.maskShape = .square imageCropViewController.shouldShowCancelButton = true imageCropViewController.onCancel = { [weak self] in self?.dismiss(animated: true) self?.updateGravatarStatus(.idle) } imageCropViewController.onCompletion = { [weak self] image, _ in self?.dismiss(animated: true) self?.uploadGravatarImage(image) } let navController = UINavigationController(rootViewController: imageCropViewController) navController.modalPresentationStyle = .formSheet self?.present(navController, animated: true) } return headerView }() /// Shows an actionsheet with options to Log In or Create a WordPress site. /// This is a temporary stop-gap measure to preserve for users only logged /// into a self-hosted site the ability to create a WordPress.com account. /// fileprivate func promptForLoginOrSignup() { WordPressAuthenticator.showLogin(from: self, animated: true, showCancel: true, restrictToWPCom: true) } private lazy var sharePresenter: ShareAppContentPresenter = { let presenter = ShareAppContentPresenter(account: defaultAccount()) presenter.delegate = self return presenter }() } // MARK: - SearchableActivity Conformance extension MeViewController: SearchableActivityConvertable { var activityType: String { return WPActivityType.me.rawValue } var activityTitle: String { return NSLocalizedString("Me", comment: "Title of the 'Me' tab - used for spotlight indexing on iOS.") } var activityKeywords: Set<String>? { let keyWordString = NSLocalizedString("wordpress, me, settings, account, notification log out, logout, log in, login, help, support", comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Me' tab.") let keywordArray = keyWordString.arrayOfTags() guard !keywordArray.isEmpty else { return nil } return Set(keywordArray) } } // MARK: - Gravatar uploading // extension MeViewController: GravatarUploader { /// Update the UI based on the status of the gravatar upload func updateGravatarStatus(_ status: GravatarUploaderStatus) { switch status { case .uploading(image: let newGravatarImage): headerView.showsActivityIndicator = true headerView.isUserInteractionEnabled = false headerView.overrideGravatarImage(newGravatarImage) case .finished: reloadViewModel() fallthrough default: headerView.showsActivityIndicator = false headerView.isUserInteractionEnabled = true } } } // MARK: - Constants private extension MeViewController { enum RowTitles { static let appSettings = NSLocalizedString("App Settings", comment: "Link to App Settings section") static let myProfile = NSLocalizedString("My Profile", comment: "Link to My Profile section") static let accountSettings = NSLocalizedString("Account Settings", comment: "Link to Account Settings section") static let qrLogin = NSLocalizedString("Scan Login Code", comment: "Link to opening the QR login scanner") static let support = NSLocalizedString("Help & Support", comment: "Link to Help section") static let logIn = NSLocalizedString("Log In", comment: "Label for logging in to WordPress.com account") static let logOut = NSLocalizedString("Log Out", comment: "Label for logging out from WordPress.com account") static let about = AppConstants.Settings.aboutTitle } enum HeaderTitles { static let wpAccount = NSLocalizedString("WordPress.com Account", comment: "WordPress.com sign-in/sign-out section header title") } enum LogoutAlert { static let defaultTitle = AppConstants.Logout.alertTitle static let unsavedTitleSingular = NSLocalizedString("You have changes to %d post that hasn't been uploaded to your site. Logging out now will delete those changes. Log out anyway?", comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (SINGULAR!)") static let unsavedTitlePlural = NSLocalizedString("You have changes to %d posts that haven’t been uploaded to your site. Logging out now will delete those changes. Log out anyway?", comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (PLURAL!)") static let cancelAction = NSLocalizedString("Cancel", comment: "Verb. A button title. Tapping cancels an action.") static let logoutAction = NSLocalizedString("Log Out", comment: "Button for confirming logging out from WordPress.com account") } } // MARK: - Private Extension for Notification handling private extension MeViewController { @objc func refreshModelWithNotification(_ notification: Foundation.Notification) { reloadViewModel() } } // MARK: - ShareAppContentPresenterDelegate extension MeViewController: ShareAppContentPresenterDelegate { func didUpdateLoadingState(_ loading: Bool) { reloadViewModel() } } // MARK: - Jetpack powered badge extension MeViewController { override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard section == handler.viewModel.sections.count - 1, JetpackBrandingVisibility.all.enabled else { return nil } return JetpackButton.makeBadgeView(target: self, selector: #selector(jetpackButtonTapped)) } @objc private func jetpackButtonTapped() { JetpackBrandingCoordinator.presentOverlay(from: self) JetpackBrandingAnalyticsHelper.trackJetpackPoweredBadgeTapped(screen: .me) } }
gpl-2.0
def41c318639c5f32f638454d2957d0c
37.886121
191
0.624874
5.717949
false
false
false
false
cheyongzi/MGTV-Swift
MGTV-Swift/Search/Controller/SearchViewController.swift
1
4263
// // SearchViewController.swift // MGTV-Swift // // Created by Che Yongzi on 2016/12/12. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit class SearchViewController: UIViewController { var hasStartSearch = false let searchBar: CustomSearchBar = { let searchBar = CustomSearchBar.init(frame: CGRect(x: 0, y: 0, width: HNTVDeviceWidth, height: 30)) return searchBar }() var placeholder: String? { didSet { searchBar.placeholder = placeholder ?? "" } } let homeViewSource = SearchHomeViewSource() lazy var suggestViewSource: SearchSuggestViewSource = SearchSuggestViewSource() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.navigationItem.leftBarButtonItem = self.barItem(title: "", frame: CGRect(x: 0, y: 0, width: 0, height: 0), selector: nil) self.navigationItem.rightBarButtonItems = [self.barItem(-10), self.barItem(title: "取消", frame: CGRect(x: 0, y: 0, width: 40, height: 44), selector: #selector(cancelSearch))] // Do any additional setup after loading the view. SearchRecommendDataSource.fetchSearchRecommend(nil, complete: { [weak self] (response, error) in guard let recommendData = response as? SearchRecommendResponse else { return } guard let datas = recommendData.data else { return } if let strongSelf = self { strongSelf.homeViewSource.recommendDatas = datas } }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) searchBar.delegate = self navigationItem.titleView = searchBar let _ = searchBar.becomeFirstResponder() homeViewSource.searchViewModel.delegate = self view.addSubview(homeViewSource.collectionView) view.addSubview(suggestViewSource.tableView) suggestViewSource.tableView.isHidden = true } //MARK: - cancel action func cancelSearch() { searchBar.endEditing(true) let _ = self.navigationController?.popViewController(animated: true) } func searchAction(text: String) { SearchHistoryManager.saveHistory(text) hasStartSearch = true // SearchResultDataSource.fetchSearch(["name" : text]) { [weak self] (response, error) in // // } } //MARK: - MemoryWarning override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SearchViewController: SearchViewSourceDelegate { func endEdit() { searchBar.endEditing(true) } func startSearch(_ text: String) { searchAction(text: text) } } extension SearchViewController: CustomSearchBarDelegate { func search(text: String?) { guard let searchText = text else { return } searchAction(text: searchText) } func auto(text: String?) { if !hasStartSearch { guard let suggestText = text else { return } guard !suggestText.isEmpty else { suggestViewSource.tableView.isHidden = true return } if suggestViewSource.tableView.isHidden { suggestViewSource.tableView.isHidden = false } SearchSuggestDataSource.fetchSuggest(["name" : suggestText], complete: { [weak self] (response, error) in guard let suggestResponse = response as? SearchSuggestResponse else { return } guard let datas = suggestResponse.data else { return } if let strongSelf = self { strongSelf.suggestViewSource.suggestDatas = datas } }) } } func clear() { hasStartSearch = false suggestViewSource.tableView.isHidden = true } func beginEdit() { } }
mit
2cd06923ccc259928228b75cf8f6591a
29.184397
181
0.590695
5.066667
false
false
false
false
jellybeansoup/ios-melissa
Shared/Extensions/UIImage.swift
2
8032
import UIKit extension UIImage { /// Generate a vertical gradient based on a single colour. /// @param color The (roughly) mid-point to use for the gradient. /// @return A 900px square image with a vertical, linear gradient based on the given colour. class func imageWithGradient(_ color: UIColor) -> UIImage { let size = CGSize(width: 20, height: 100) return self.imageWithGradient(color, size: size) } /// Generate a vertical gradient based on a single colour. /// @param color The (roughly) mid-point to use for the gradient. /// @return A 900px square image with a vertical, linear gradient based on the given colour. class func imageWithGradient(_ color: UIColor, height: CGFloat) -> UIImage { let size = CGSize(width: 20, height: height) return self.imageWithGradient(color, size: size) } /// Generate a vertical gradient based on a single colour. /// @param color The (roughly) mid-point to use for the gradient. /// @return A 900px square image with a vertical, linear gradient based on the given colour. class func imageWithGradient(_ color: UIColor, size: CGSize) -> UIImage { return self.imageWithGradient(color, size: size, top: 0, bottom: 1) } /// Generate a vertical gradient based on a single colour. /// @param color The (roughly) mid-point to use for the gradient. /// @return A 900px square image with a vertical, linear gradient based on the given colour. class func imageWithGradient(_ color: UIColor, size: CGSize, top: CGFloat, bottom: CGFloat) -> UIImage { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 1 color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) let topHue = hue + 0.01 + ( -0.01 * top ) let topSaturation = saturation + 0.04 + ( -0.09 * top ) let topBrightness = brightness - 0.095 + ( 0.145 * top ) let topColor = UIColor(hue: topHue, saturation: topSaturation, brightness: topBrightness, alpha: alpha) let bottomHue = hue + 0.01 + ( -0.01 * bottom ) let bottomSaturation = saturation + 0.04 + ( -0.09 * bottom ) let bottomBrightness = brightness - 0.095 + ( 0.145 * bottom ) let bottomColor = UIColor(hue: bottomHue, saturation: bottomSaturation, brightness: bottomBrightness, alpha: alpha) let scale = UIScreen.main.scale let pixelSize = CGSize(width: size.width * scale, height: size.height * scale) UIGraphicsBeginImageContext(pixelSize) let context = UIGraphicsGetCurrentContext() let colorSpace = CGColorSpaceCreateDeviceRGB() let locations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: [topColor.cgColor, bottomColor.cgColor] as CFArray, locations: locations) let startPoint = CGPoint(x: pixelSize.width / 2, y: 0) let endPoint = CGPoint(x: pixelSize.width / 2, y: pixelSize.height) context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]) let image = context!.makeImage() UIGraphicsEndImageContext() return UIImage(cgImage: image!, scale: scale, orientation: .up).stretchableImage(withLeftCapWidth: 0, topCapHeight: 0) } /// Create a new image which is resized and masked as a circle, with an optional white stroke. /// @param diameter The diameter to use for the circle. The given image will be resized to fill this space. /// @param stroke Line width to use for the stroke, defaults to 0 (which does not render a stroke). /// @return A circular image matching the given parameters. public func circularImage(_ diameter: CGFloat, stroke: CGFloat = 0) -> UIImage? { if diameter == 0 { return nil } let scale = UIScreen.main.scale let scaledSize = diameter * scale let source = self.cgImage let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(scaledSize), height: Int(scaledSize), bitsPerComponent: source!.bitsPerComponent, bytesPerRow: 0, space: source!.colorSpace!, bitmapInfo: bitmapInfo.rawValue) let percent = scaledSize / min(self.size.width * self.scale, self.size.height * self.scale) let rectSize = CGSize(width: self.size.width * self.scale * percent, height: self.size.height * self.scale * percent) let rectOrigin = CGPoint(x: ((rectSize.width - scaledSize) / 2), y: ((rectSize.height - scaledSize) / 2) ) var rect = CGRect(origin: rectOrigin, size: rectSize) if( stroke >= 1 ) { context!.addEllipse(in: rect) context!.setFillColor(UIColor.white.cgColor) context!.drawPath(using: .fill) rect = rect.insetBy(dx: stroke * scale, dy: stroke * scale) } context!.addEllipse(in: rect) context!.clip() context!.draw(source!, in: rect) guard let imageRef = context!.makeImage() else { return nil } return UIImage(cgImage: imageRef, scale: scale, orientation: self.imageOrientation) } /// Creates a new image in which the given image is "padded" based on the given `edgeInsets`. /// This allows manual adjustments to an image's apparent position without needing to adjust the image view. /// @param edgeInsets The padding to use for each of the four sides. /// @return A new image which has (transparent) padding added based on the given `edgeInsets`. public func paddedImage(_ edgeInsets: UIEdgeInsets) -> UIImage? { if edgeInsets == UIEdgeInsets.zero { return self } let scale = UIScreen.main.scale let source = self.cgImage let contextSize = CGSize(width: (self.size.width + edgeInsets.left + edgeInsets.right) * scale, height: (self.size.height + edgeInsets.top + edgeInsets.bottom) * scale) let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(contextSize.width), height: Int(contextSize.height), bitsPerComponent: source!.bitsPerComponent, bytesPerRow: 0, space: source!.colorSpace!, bitmapInfo: bitmapInfo.rawValue) let rect = CGRect(x: edgeInsets.left * scale, y: edgeInsets.bottom * scale, width: self.size.width * scale, height: self.size.height * scale) context!.draw(source!, in: rect) guard let imageRef = context!.makeImage() else { return nil } return UIImage(cgImage: imageRef, scale: scale, orientation: self.imageOrientation) } public func overlay(_ icon: UIImage?, color: UIColor) -> UIImage? { guard let icon = icon else { return self } let size = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale) let rect = CGRect(origin: CGPoint.zero, size: size) let source = self.cgImage let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: source!.bitsPerComponent, bytesPerRow: 0, space: source!.colorSpace!, bitmapInfo: bitmapInfo.rawValue) context!.draw(source!, in: rect) let iconSize = CGSize(width: icon.size.width * icon.scale, height: icon.size.height * icon.scale) let iconOrigin = CGPoint(x: (size.width - iconSize.width) / 2, y: (size.height - iconSize.height) / 2) let iconRect = CGRect(origin: iconOrigin, size: iconSize) context!.clip(to: iconRect, mask: icon.cgImage!) context!.setFillColor(color.cgColor) context!.fill(iconRect) guard let imageRef = context!.makeImage() else { return nil } return UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation) } }
bsd-2-clause
b5ab174ea13873318c78a0171561a313
48.276074
227
0.673058
4.320602
false
false
false
false
Transparentmask/MVTheme
MVThemeTool/MVThemeTool/Document.swift
1
2233
// // Document.swift // MVThemeTool // // Created by Martin Yin on 7/10/2015. // Copyright (c) 2015 Marchell. All rights reserved. // import Cocoa class Document: NSDocument { override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) // Add any code here that needs to be executed once the windowController has loaded the document's window. } override class func autosavesInPlace() -> Bool { return true } override func makeWindowControllers() { // Returns the Storyboard that contains your Document window. let storyboard = NSStoryboard(name: "Main", bundle: nil)! let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController self.addWindowController(windowController) } override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } }
mit
ca62bdaeb65644557ebec51babab8459
42.784314
186
0.720107
4.907692
false
false
false
false
son11592/STNavigationViewController
Example/STNavigationViewController/HideNavigationBarAnimator.swift
1
4545
// // CusViewController.swift // STNavigationViewController // // Created by Sơn Thái on 7/17/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import STNavigationViewController class HideNavigationBarPushAnimator: PushAnimator { override func attackSubviews(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.attackSubviews(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } context.containerView.addSubview(fromVC.navigationBar) context.containerView.addSubview(toVC.navigationBar) } override func prepareForTransition(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.prepareForTransition(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } toVC.navigationBar.alpha = 0.0 toVC.navigationBar.backgroundView.alpha = 1.0 fromVC.navigationBar.alpha = 1.0 fromVC.navigationBar.backgroundView.alpha = 1.0 } override func animatedTransition(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.animatedTransition(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } fromVC.navigationBar.backgroundView.alpha = 0 toVC.navigationBar.alpha = 1.0 } override func completion(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.completion(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } fromVC.contentView.addSubview(fromVC.navigationBar) toVC.contentView.addSubview(toVC.navigationBar) } } class HideNavigationBarPopAnimator: PopAnimator { override func attackSubviews(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.attackSubviews(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } context.containerView.addSubview(toVC.navigationBar) context.containerView.addSubview(fromVC.navigationBar) } override func prepareForTransition(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.prepareForTransition(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } toVC.navigationBar.alpha = 1.0 toVC.navigationBar.backgroundView.alpha = 0.0 fromVC.navigationBar.alpha = 1.0 fromVC.navigationBar.backgroundView.alpha = 1.0 } override func animatedTransition(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.animatedTransition(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } toVC.navigationBar.backgroundView.alpha = 1.0 fromVC.navigationBar.alpha = 0.0 } override func completion(from fromVC: STViewController, to toVC: STViewController, withContext context: UIViewControllerContextTransitioning) { super.completion(from: fromVC, to: toVC, withContext: context) guard let fromVC = fromVC as? ViewController, let toVC = toVC as? ViewController else { return } toVC.contentView.addSubview(toVC.navigationBar) fromVC.contentView.addSubview(fromVC.navigationBar) } }
mit
7df9be3076c194e958937f230996fff0
34.209302
97
0.67151
5.343529
false
false
false
false
22377832/ccyswift
SegmentControl/SegmentControl/ViewController.swift
1
1258
// // ViewController.swift // SegmentControl // // Created by sks on 17/1/24. // Copyright © 2017年 chen. All rights reserved. // import UIKit class ViewController: UIViewController { var segmentedControl: UISegmentedControl! func segmentedControlValueChanged(sender: UISegmentedControl){ let selectedSegmentIndex = sender.selectedSegmentIndex let selectedSegmentText = sender.titleForSegment(at: selectedSegmentIndex) print("segment \(selectedSegmentIndex) with text" + "of \(selectedSegmentText!) is selected") } override func viewDidLoad() { super.viewDidLoad() let segments = ["死神", "火影忍者", "海贼王"] segmentedControl = UISegmentedControl(items: segments) segmentedControl.center = view.center segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged), for: .valueChanged) segmentedControl.isMomentary = true view.addSubview(segmentedControl) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
14a1d9efac0d0aa9f88dc3b62e87df9d
29.170732
109
0.69038
5.154167
false
false
false
false
olegnaumenko/BRYXBanner
Example/BRYXBanner/BorderedButton.swift
9
2363
// // BorderedButton.swift // // // Created by Adam Binsz on 7/26/15. // // import UIKit @IBDesignable class BorderedButton: UIButton { @IBInspectable var borderRadius: CGFloat = 13 { didSet { self.layer.cornerRadius = borderRadius } } @IBInspectable var borderWidth: CGFloat = 1.0 { didSet { self.layer.borderWidth = borderWidth } } private var selectionBackgroundColor: UIColor? { didSet { self.setTitleColor(selectionBackgroundColor, forState: .Highlighted) } } override var backgroundColor: UIColor? { get { return super.backgroundColor } set { self.selectionBackgroundColor = newValue } } override var tintColor: UIColor? { didSet { self.setTitleColor(tintColor, forState: .Normal) self.layer.borderColor = tintColor?.CGColor } } init() { super.init(frame: CGRectZero) loadView() } override init(frame: CGRect) { super.init(frame: frame) loadView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadView() } convenience init(title: String, tintColor: UIColor? = UIColor.lightGrayColor(), backgroundColor: UIColor? = UIColor.whiteColor()) { self.init(frame: CGRectZero) self.setTitle(title, forState: .Normal) ({ self.tintColor = tintColor }()) ({ self.backgroundColor = backgroundColor }()) } private func loadView() { super.backgroundColor = UIColor.clearColor() self.titleLabel?.font = UIFont.boldSystemFontOfSize(15.0) self.borderWidth = 1.0 self.layer.cornerRadius = borderRadius if let tint = self.tintColor { self.layer.borderColor = tint.CGColor } self.layer.masksToBounds = false self.clipsToBounds = false } override var highlighted: Bool { didSet { if oldValue == self.highlighted { return } let background = self.backgroundColor let tint = self.tintColor super.backgroundColor = tint self.tintColor = background } } }
mit
9e0f2d42671d1382215963a2a1ab32fb
23.614583
135
0.565806
5.125813
false
false
false
false
blinkinput/blinkinput-ios
Samples/DocumentCapture-sample-Swift/DocumentCapture-sample-Swift/DocumentCaptureTableViewController.swift
2
2901
// // DocumentCaptureTableViewController.swift // DocumentCapture-sample-Swift // // Created by Jura Skrlec on 04/02/2020. // Copyright © 2020 Jura Skrlec. All rights reserved. // import UIKit struct ScannedDocument { var scannedDocumentImage: UIImage? var highResolutionDocumentImage: UIImage? init(scannedDocumentImage: UIImage?, highResolutionDocumentImage: UIImage?) { self.scannedDocumentImage = scannedDocumentImage self.highResolutionDocumentImage = highResolutionDocumentImage } } class DocumentCaptureTableViewController: UITableViewController { var scannedDocument: ScannedDocument? override func viewDidLoad() { super.viewDidLoad() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return "Document Capture Recognizer Result" } else if (section == 1) { return "High resolution image" } return nil; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath.section == 0) { let cell = tableView.dequeueReusableCell(withIdentifier: DocumentCaptureTableViewCell.cellIdentifier, for: indexPath) as! DocumentCaptureTableViewCell cell.documentImage = scannedDocument?.scannedDocumentImage return cell } else if (indexPath.section == 1) { let cell = tableView.dequeueReusableCell(withIdentifier: DocumentCaptureTableViewCell.cellIdentifier, for: indexPath) as! DocumentCaptureTableViewCell cell.documentImage = scannedDocument?.highResolutionDocumentImage return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: ConfirmResultTableViewCell.cellIdentifier, for: indexPath) as! ConfirmResultTableViewCell cell.delegate = self return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath.section == 0 || indexPath.section == 1) { return 300 } else { return 80 } } } extension DocumentCaptureTableViewController: ConfirmResultTableViewCellDelegate { func didTapOk() { self.dismiss(animated: true, completion: nil) } }
apache-2.0
f8afc16521fd8e3cf4ccba3d08dfc328
31.222222
162
0.664138
5.350554
false
false
false
false
andreamazz/FDWaveformView
Example/FDWaveformView/ViewController.swift
1
5222
// // ViewController.swift // FDWaveformView // // Created by William Entriken on 2/4/16. // Copyright © 2016 William Entriken. All rights reserved. // import Foundation import UIKit class ViewController: UIViewController { @IBOutlet weak var waveform: FDWaveformView! @IBOutlet var playButton: UIView! private var startRendering = NSDate() private var endRendering = NSDate() private var startLoading = NSDate() private var endLoading = NSDate() private var profilingAlert: UIAlertView? = nil private var profileResult = "" @IBAction func doAnimation() { UIView.animateWithDuration(0.3, animations: { let randomNumber = Int(arc4random()) % self.waveform.totalSamples self.waveform.progressSamples = randomNumber }) } @IBAction func doZoomIn() { self.waveform.zoomStartSamples = 0 self.waveform.zoomEndSamples = self.waveform.totalSamples / 4 } @IBAction func doZoomOut() { self.waveform.zoomStartSamples = 0 self.waveform.zoomEndSamples = self.waveform.totalSamples } @IBAction func doRunPerformanceProfile() { NSLog("RUNNING PERFORMANCE PROFILE") let alert = UIAlertView(title: "PROFILING BEGIN", message: "Profiling will begin, please don't touch anything. This will take less than 30 seconds", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "") alert.show() self.profilingAlert = alert self.profileResult = "" // Delay execution of my block for 1 seconds. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { self.profileResult.appendContentsOf("AAC:") self.doLoadAAC() }) // Delay execution of my block for 5 seconds. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5) * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { self.profileResult.appendContentsOf(" MP3:") self.doLoadMP3() }) // Delay execution of my block for 9 seconds. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(9) * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { self.profileResult.appendContentsOf(" OGG:") self.doLoadOGG() }) // Delay execution of my block for 14 seconds. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(14) * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { self.profilingAlert?.dismissWithClickedButtonIndex(-1, animated: false) let alert = UIAlertView(title: "PLEASE POST TO github.com/fulldecent/FDWaveformView/wiki", message: self.profileResult, delegate: nil, cancelButtonTitle: "Done", otherButtonTitles: "") alert.show() self.profilingAlert = alert }) } @IBAction func doLoadAAC() { let thisBundle = NSBundle(forClass: self.dynamicType) let url = thisBundle.URLForResource("TchaikovskyExample2", withExtension: "m4a") self.waveform.audioURL = url } @IBAction func doLoadMP3() { let thisBundle = NSBundle(forClass: self.dynamicType) let url = thisBundle.URLForResource("TchaikovskyExample2", withExtension: "mp3") self.waveform.audioURL = url } @IBAction func doLoadOGG() { let thisBundle = NSBundle(forClass: self.dynamicType) let url = thisBundle.URLForResource("TchaikovskyExample2", withExtension: "ogg") self.waveform.audioURL = url } override func viewDidLoad() { super.viewDidLoad() let thisBundle = NSBundle(forClass: self.dynamicType) let url = thisBundle.URLForResource("Submarine", withExtension: "aiff") // Animate the waveforme view in when it is rendered self.waveform.delegate = self self.waveform.alpha = 0.0 self.waveform.audioURL = url self.waveform.progressSamples = 10000 self.waveform.doesAllowScrubbing = true self.waveform.doesAllowStretch = true self.waveform.doesAllowScroll = true } } extension ViewController: FDWaveformViewDelegate { func waveformViewWillRender(waveformView: FDWaveformView) { self.startRendering = NSDate() } func waveformViewDidRender(waveformView: FDWaveformView) { self.endRendering = NSDate() NSLog("FDWaveformView rendering done, took %f seconds", self.endRendering.timeIntervalSinceDate(self.startRendering)) self.profileResult.appendContentsOf(" render \(self.endRendering.timeIntervalSinceDate(self.startRendering))") UIView.animateWithDuration(0.25, animations: {() -> Void in waveformView.alpha = 1.0 }) } func waveformViewWillLoad(waveformView: FDWaveformView) { self.startLoading = NSDate() } func waveformViewDidLoad(waveformView: FDWaveformView) { self.endLoading = NSDate() NSLog("FDWaveformView loading done, took %f seconds", self.endLoading.timeIntervalSinceDate(self.startLoading)) self.profileResult.appendContentsOf(" load \(self.endLoading.timeIntervalSinceDate(self.startLoading))") } }
mit
09b1340cb3335cac174071e30bc13a83
40.110236
218
0.668263
4.424576
false
false
false
false
zjjzmw1/SwiftCodeFragments
SwiftCodeFragments/CodeFragments/Category/UIKitCategory/UIColor/UIColor+JCColor.swift
1
13723
// // UIColor+JCColor.swift // JCSwiftKitDemo // // Created by molin.JC on 2017/1/1. // Copyright © 2017年 molin. All rights reserved. // import UIKit extension UIColor { /// 十六进制 class func colorRGB16(value: __uint32_t) -> UIColor { return UIColor.colorRGB16(value: value, alphe: 1.0); } /// 十六进制 class func colorRGB16(value: __uint32_t, alphe: CGFloat) -> UIColor { return UIColor.init(red: CGFloat((value & 0xFF0000) >> 16) / 255.0, green: CGFloat((value & 0xFF00) >> 8) / 255.0, blue: CGFloat((value & 0xFF)) / 255.0, alpha: alphe); } func RGB_red() -> CGFloat { let r = self.cgColor.components return r![0]; } func RGB_green() -> CGFloat { let g = self.cgColor.components; if (self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome) { return g![0]; } return g![1]; } func RGB_blue() -> CGFloat { let b = self.cgColor.components; if (self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome) { return b![0]; } return b![2]; } func alpha() -> CGFloat { return self.cgColor.alpha; } /// 将颜色转换成16进制的字符串 func stringForRGB16() -> String { let r = Int(self.RGB_red() * 255); let g = Int(self.RGB_green() * 255); let b = Int(self.RGB_blue() * 255); let stringColor = String.init(format: "#%02X%02X%02X", r, g, b); return stringColor; } /// 随机颜色,透明度默认1 class func randomColor() -> UIColor { return UIColor.randomColor(alpha: 1.0); } /// 随机颜色 class func randomColor(alpha: CGFloat) -> UIColor { let redValue = arc4random() % 255; let greenValue = arc4random() % 255; let blueValue = arc4random() % 255; return UIColor.init(red: CGFloat(redValue) / 255.0, green: CGFloat(greenValue) / 255.0, blue: CGFloat(blueValue) / 255.0, alpha: alpha); } } // MARK: - 色系 extension UIColor { /// 薄雾玫瑰 class func mistyRose() -> UIColor { return UIColor.colorRGB16(value: 0xFFE4E1); } /// 浅鲑鱼色 class func lightSalmon() -> UIColor { return UIColor.colorRGB16(value: 0xFFA07A); } /// 淡珊瑚色 class func lightCoral() -> UIColor { return UIColor.colorRGB16(value: 0xF08080); } /// 鲑鱼色 class func salmonColor() -> UIColor { return UIColor.colorRGB16(value: 0xFA8072); } /// 珊瑚色 class func coralColor() -> UIColor { return UIColor.colorRGB16(value: 0xFF7F50); } /// 番茄 class func tomatoColor() -> UIColor { return UIColor.colorRGB16(value: 0xFF6347); } /// 橙红色 class func orangeRed() -> UIColor { return UIColor.colorRGB16(value: 0xFF4500); } /// 印度红 class func indianRed() -> UIColor { return UIColor.colorRGB16(value: 0xCD5C5C); } /// 猩红 class func crimsonColor() -> UIColor { return UIColor.colorRGB16(value: 0xDC143C); } /// 耐火砖 class func fireBrick() -> UIColor { return UIColor.colorRGB16(value: 0xB22222); } /// 玉米色 class func cornColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFF8DC); } /// 柠檬薄纱 class func LemonChiffon() -> UIColor { return UIColor.colorRGB16(value: 0xFFFACD); } /// 苍金麒麟 class func paleGodenrod() -> UIColor { return UIColor.colorRGB16(value: 0xEEE8AA); } /// 卡其色 class func khakiColor() -> UIColor { return UIColor.colorRGB16(value: 0xF0E68C); } /// 金色 class func goldColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFD700); } /// 雌黄 class func orpimentColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFC64B); } /// 藤黄 class func gambogeColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFB61E); } /// 雄黄 class func realgarColor() -> UIColor { return UIColor.colorRGB16(value: 0xE9BB1D); } /// 金麒麟色 class func goldenrod() -> UIColor { return UIColor.colorRGB16(value: 0xDAA520); } /// 乌金 class func darkGold() -> UIColor { return UIColor.colorRGB16(value: 0xA78E44); } /// 苍绿 class func paleGreen() -> UIColor { return UIColor.colorRGB16(value: 0x98FB98); } /// 淡绿色 class func lightGreen() -> UIColor { return UIColor.colorRGB16(value: 0x90EE90); } /// 春绿 class func springGreen() -> UIColor { return UIColor.colorRGB16(value: 0x2AFD84); } /// 草坪绿 class func lawnGreen() -> UIColor { return UIColor.colorRGB16(value: 0x7CFC00); } /// 酸橙绿 class func limeColor() -> UIColor { return UIColor.colorRGB16(value: 0x00FF00); } /// 森林绿 class func forestGreen() -> UIColor { return UIColor.colorRGB16(value: 0x228B22); } /// 海洋绿 class func seaGreen() -> UIColor { return UIColor.colorRGB16(value: 0x2E8B57); } /// 深绿 class func darkGreen() -> UIColor { return UIColor.colorRGB16(value: 0x006400); } /// 橄榄(墨绿) class func olive() -> UIColor { return UIColor.colorRGB16(value: 0xE1FFFF); } /// 苍白绿松石 class func paleTurquoise() -> UIColor { return UIColor.colorRGB16(value: 0xAFEEEE); } /// 绿碧 class func aquamarine() -> UIColor { return UIColor.colorRGB16(value: 0x7FFFD4); } /// 绿松石 class func turquoise() -> UIColor { return UIColor.colorRGB16(value: 0x40E0D0); } /// 适中绿松石 class func mediumTurquoise() -> UIColor { return UIColor.colorRGB16(value: 0x48D1CC); } /// 美团色 class func meituanColor() -> UIColor { return UIColor.colorRGB16(value: 0x2BB8AA); } /// 浅海洋绿 class func lightSeaGreen() -> UIColor { return UIColor.colorRGB16(value: 0x20B2AA); } /// 深青色 class func darkCyan() -> UIColor { return UIColor.colorRGB16(value: 0x008B8B); } /// 水鸭色 class func tealColor() -> UIColor { return UIColor.colorRGB16(value: 0x008080); } /// 深石板灰 class func darkSlateGray() -> UIColor { return UIColor.colorRGB16(value: 0x2F4F4F); } /// 天蓝色 class func skyBlue() -> UIColor { return UIColor.colorRGB16(value: 0xE1FFFF); } /// 淡蓝 class func lightBLue() -> UIColor { return UIColor.colorRGB16(value: 0xADD8E6); } /// 深天蓝 class func deepSkyBlue() -> UIColor { return UIColor.colorRGB16(value: 0x00BFFF); } /// 道奇蓝 class func doderBlue() -> UIColor { return UIColor.colorRGB16(value: 0x1E90FF); } /// 矢车菊 class func cornflowerBlue() -> UIColor { return UIColor.colorRGB16(value: 0x6495ED); } /// 皇家蓝 class func royalBlue() -> UIColor { return UIColor.colorRGB16(value: 0x4169E1); } /// 适中的蓝色 class func mediumBlue() -> UIColor { return UIColor.colorRGB16(value: 0x0000CD); } /// 深蓝 class func darkBlue() -> UIColor { return UIColor.colorRGB16(value: 0x00008B); } /// 海军蓝 class func navyColor() -> UIColor { return UIColor.colorRGB16(value: 0x000080); } /// 午夜蓝 class func midnightBlue() -> UIColor { return UIColor.colorRGB16(value: 0x191970); } /// 薰衣草 class func lavender() -> UIColor { return UIColor.colorRGB16(value: 0xE6E6FA); } /// 蓟 class func thistleColor() -> UIColor { return UIColor.colorRGB16(value: 0xD8BFD8); } /// 李子 class func plumColor() -> UIColor { return UIColor.colorRGB16(value: 0xDDA0DD); } /// 紫罗兰 class func violetColor() -> UIColor { return UIColor.colorRGB16(value: 0xEE82EE); } /// 适中的兰花紫 class func mediumOrchid() -> UIColor { return UIColor.colorRGB16(value: 0xBA55D3); } /// 深兰花紫 class func darkOrchid() -> UIColor { return UIColor.colorRGB16(value: 0x9932CC); } /// 深紫罗兰色 class func darkVoilet() -> UIColor { return UIColor.colorRGB16(value: 0x9400D3); } /// 泛蓝紫罗兰 class func blueViolet() -> UIColor { return UIColor.colorRGB16(value: 0x8A2BE2); } /// 深洋红色 class func darkMagenta() -> UIColor { return UIColor.colorRGB16(value: 0x8B008B); } /// 靛青 class func indigoColor() -> UIColor { return UIColor.colorRGB16(value: 0x4B0082); } /// 白烟 class func whiteSmoke() -> UIColor { return UIColor.colorRGB16(value: 0xF5F5F5); } /// 鸭蛋 class func duckEgg() -> UIColor { return UIColor.colorRGB16(value: 0xE0EEE8); } /// 亮灰 class func gainsboroColor() -> UIColor { return UIColor.colorRGB16(value: 0xDCDCDC); } /// 蟹壳青 class func carapaceColor() -> UIColor { return UIColor.colorRGB16(value: 0xBBCDC5); } /// 银白色 class func silverColor() -> UIColor { return UIColor.colorRGB16(value: 0xC0C0C0); } /// 暗淡的灰色 class func dimGray() -> UIColor { return UIColor.colorRGB16(value: 0x696969); } /// 海贝壳 class func seaShell() -> UIColor { return UIColor.colorRGB16(value: 0xFFF5EE); } /// 雪 class func snowColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFFAFA); } /// 亚麻色 class func linenColor() -> UIColor { return UIColor.colorRGB16(value: 0xFAF0E6); } /// 花之白 class func floralWhite() -> UIColor { return UIColor.colorRGB16(value: 0xFFFAF0); } /// 老饰带 class func oldLace() -> UIColor { return UIColor.colorRGB16(value: 0xFDF5E6); } /// 象牙白 class func ivoryColor() -> UIColor { return UIColor.colorRGB16(value: 0xFFFFF0); } /// 蜂蜜露 class func honeydew() -> UIColor { return UIColor.colorRGB16(value: 0xF0FFF0); } /// 薄荷奶油 class func mintCream() -> UIColor { return UIColor.colorRGB16(value: 0xF5FFFA); } /// 蔚蓝色 class func azureColor() -> UIColor { return UIColor.colorRGB16(value: 0xF0FFFF); } /// 爱丽丝蓝 class func aliceBlue() -> UIColor { return UIColor.colorRGB16(value: 0xF0F8FF); } /// 幽灵白 class func ghostWhite() -> UIColor { return UIColor.colorRGB16(value: 0xF8F8FF); } /// 淡紫红 class func lavenderBlush() -> UIColor { return UIColor.colorRGB16(value: 0xFFF0F5); } /// 米色 class func beigeColor() -> UIColor { return UIColor.colorRGB16(value: 0xF5F5DD); } /// 黄褐色 class func tanColor() -> UIColor { return UIColor.colorRGB16(value: 0xD2B48C); } /// 玫瑰棕色 class func rosyBrown() -> UIColor { return UIColor.colorRGB16(value: 0xBC8F8F); } /// 秘鲁 class func peruColor() -> UIColor { return UIColor.colorRGB16(value: 0xCD853F); } /// 巧克力 class func chocolateColor() -> UIColor { return UIColor.colorRGB16(value: 0xD2691E); } /// 古铜色 class func bronzeColor() -> UIColor { return UIColor.colorRGB16(value: 0xB87333); } /// 黄土赭色 class func siennaColor() -> UIColor { return UIColor.colorRGB16(value: 0xA0522D); } /// 马鞍棕色 class func saddleBrown() -> UIColor { return UIColor.colorRGB16(value: 0x8B4513); } /// 土棕 class func soilColor() -> UIColor { return UIColor.colorRGB16(value: 0x734A12); } /// 栗色 class func maroonColor() -> UIColor { return UIColor.colorRGB16(value: 0x800000); } /// 乌贼墨棕 class func inkfishBrown() -> UIColor { return UIColor.colorRGB16(value: 0x5E2612); } /// 水粉 class func waterPink() -> UIColor { return UIColor.colorRGB16(value: 0xF3D3E7); } /// 藕色 class func lotusRoot() -> UIColor { return UIColor.colorRGB16(value: 0xEDD1D8); } /// 浅粉红 class func lightPink() -> UIColor { return UIColor.colorRGB16(value: 0xFFB6C1); } /// 适中的粉红 class func mediumPink() -> UIColor { return UIColor.colorRGB16(value: 0xFFC0CB); } /// 桃红 class func peachRed() -> UIColor { return UIColor.colorRGB16(value: 0xF47983); } /// 苍白的紫罗兰红色 class func paleVioletRed() -> UIColor { return UIColor.colorRGB16(value: 0xDB7093); } /// 深粉色 class func deepPink() -> UIColor { return UIColor.colorRGB16(value: 0xFF1493); } }
mit
3984662315ea173b7ff2719a2344f4eb
22.795993
144
0.557027
3.508056
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/ExSwift/ExSwift/ExSwift.swift
1
7712
// // ExSwift.swift // ExSwift // // Created by pNre on 07/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation infix operator =~ {} infix operator |~ {} infix operator .. {} public typealias Ex = ExSwift public class ExSwift { /** Creates a wrapper that, executes function only after being called n times. :param: n No. of times the wrapper has to be called before function is invoked :param: function Function to wrap :returns: Wrapper function */ public class func after <P, T> (n: Int, function: (P...) -> T) -> ((P...) -> T?) { typealias Function = [P] -> T var times = n return { (params: P...) -> T? in // Workaround for the now illegal (T...) type. let adaptedFunction = unsafeBitCast(function, Function.self) if times-- <= 0 { return adaptedFunction(params) } return nil } } /** Creates a wrapper that, executes function only after being called n times :param: n No. of times the wrapper has to be called before function is invoked :param: function Function to wrap :returns: Wrapper function */ public class func after <T> (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { return function() } let f = ExSwift.after(n, function: callAfter) return { f([nil])? } } /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. :param: function Function to wrap :returns: Wrapper function */ public class func once <P, T> (function: (P...) -> T) -> ((P...) -> T) { typealias Function = [P] -> T var returnValue: T? = nil return { (params: P...) -> T in if returnValue != nil { return returnValue! } let adaptedFunction = unsafeBitCast(function, Function.self) returnValue = adaptedFunction(params) return returnValue! } } /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. :param: function Function to wrap :returns: Wrapper function */ public class func once <T> (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { (params: Any?...) -> T in return function() } return { f([nil]) } } /** Creates a wrapper that, when called, invokes function with any additional partial arguments prepended to those provided to the new function. :param: function Function to wrap :param: parameters Arguments to prepend :returns: Wrapper function */ public class func partial <P, T> (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T) { typealias Function = [P] -> T return { (params: P...) -> T in let adaptedFunction = unsafeBitCast(function, Function.self) return adaptedFunction(parameters + params) } } /** Creates a wrapper (without any parameter) that, when called, invokes function automatically passing parameters as arguments. :param: function Function to wrap :param: parameters Arguments to pass to function :returns: Wrapper function */ public class func bind <P, T> (function: (P...) -> T, _ parameters: P...) -> (Void -> T) { typealias Function = [P] -> T return { Void -> T in let adaptedFunction = unsafeBitCast(function, Function.self) return adaptedFunction(parameters) } } /** Creates a wrapper for function that caches the result of function's invocations. :param: function Function to cache :param: hash Parameters based hashing function that computes the key used to store each result in the cache :returns: Wrapper function */ public class func cached <P: Hashable, R> (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R) { typealias Function = [P] -> R typealias Hash = [P] -> P var cache = [P:R]() return { (params: P...) -> R in let adaptedFunction = unsafeBitCast(function, Function.self) let adaptedHash = unsafeBitCast(hash, Hash.self) let key = adaptedHash(params) if let cachedValue = cache[key] { return cachedValue } cache[key] = adaptedFunction(params) return cache[key]! } } /** Creates a wrapper for function that caches the result of function's invocations. :param: function Function to cache :returns: Wrapper function */ public class func cached <P: Hashable, R> (function: (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) } /** Utility method to return an NSRegularExpression object given a pattern. :param: pattern Regex pattern :param: ignoreCase If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag :returns: NSRegularExpression object */ internal class func regex (pattern: String, ignoreCase: Bool = false) -> NSRegularExpression? { var options = NSRegularExpressionOptions.DotMatchesLineSeparators.toRaw() if ignoreCase { options = NSRegularExpressionOptions.CaseInsensitive.toRaw() | options } var error: NSError? = nil let regex = NSRegularExpression.regularExpressionWithPattern(pattern, options: NSRegularExpressionOptions.fromRaw(options)!, error: &error) return (error == nil) ? regex : nil } } /** * Internal methods */ extension ExSwift { /** * Converts, if possible, and flattens an object from its Objective-C * representation to the Swift one. * @param object Object to convert * @returns Flattenend array of converted values */ internal class func bridgeObjCObject <T, S> (object: S) -> [T] { var result = [T]() let reflection = reflect(object) // object has an Objective-C type if let obj = object as? T { // object has type T result.append(obj) } else if reflection.disposition == .ObjCObject { var bridgedValue: T!? // If it is an NSArray, flattening will produce the expected result if let array = object as? NSArray { result += array.flatten() } else if let bridged = reflection.value as? T { result.append(bridged) } } else if reflection.disposition == .IndexContainer { // object is a native Swift array // recursively convert each item (0..<reflection.count).each { let ref = reflection[$0].1 result += Ex.bridgeObjCObject(ref.value) } } return result } }
gpl-3.0
0bab63c70a0d689d83614672a444dd40
29.848
147
0.545384
4.946761
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/Menu/MenuModel.swift
2
9411
// // MenuModel.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 06/11/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kMenuModelMenuItemMapKey = "MenuItemHome" let kMenuModelMenuItemSettingsKey = "MenuItemSettings" let kMenuModelMenuItemTermsConditionsKey = "MenuItemTermsConditions" let kMenuModelMenuItemPrivacyPolicyKey = "MenuItemPrivacyPolicy" let kMenuModelMenuItemLoginKey = "MenuItemLogin" let kMenuModelMenuItemLogoutKey = "MenuItemLogout" let kMenuModelMenuItemLogoutConfirmationMessageKey = "MenuItemLogoutConfirmationMessage" let kMenuModelMenuItemTableViewExampleKey = "MenuItemTableViewExample" let kMenuModelMenuItemTableViewWithSearchKey = "MenuItemTableViewWithSearch" let kMenuModelMenuItemMapWithSearchKey = "MenuItemMapWithSearch" class MenuModel: BaseModel { var menuItemList: Array<MenuEntityProtocol>! var viewControllerFactory: ViewControllerFactoryProtocol! var isUserLoggedIn: Bool { get { return self.userManager.isUserLoggedIn() } } deinit { self.userManager.removeServiceObserver(observer: self) } override func commonInit() { super.commonInit() self.userManager.addServiceObserver(observer: self, notificationType: UserManagerNotificationType.didLogin, callback: { [weak self] (success, result, context, error) in self?.menuItemList = self?.menuItemsForLoggedInUserState() // Notify view controler // Adding protection because was crashing upon opening app with 401 if let callback = self?._loadModelCallback { callback(true, self?.menuItemList, nil, nil); } }, context: nil) self.userManager.addServiceObserver(observer: self, notificationType: UserManagerNotificationType.didSignUp, callback: { [weak self] (success, result, context, error) in self?.menuItemList = self?.menuItemsForLoggedInUserState() // Notify view controler // Adding protection because was crashing upon opening app with 401 if let callback = self?._loadModelCallback { callback(true, self?.menuItemList, nil, nil); } }, context: nil) } func logoutUser() { self.userManager.logout { [weak self] (success, result, context, error) in self?.menuItemList = self?.menuItemsForNotLoggedInUserState() // Notify view controler // Adding protection because was crashing upon opening app with 401 if let callback = self?._loadModelCallback { callback(true, self?.menuItemList, nil, nil); } } } override func willStartModelLoading(callback: @escaping Callback) { // Save for login/signup/logout callbacks later self._loadModelCallback = callback var menuItemList: Array<MenuEntityProtocol>? if (self.userManager.isUserLoggedIn()) { menuItemList = self.menuItemsForLoggedInUserState() } else { menuItemList = self.menuItemsForNotLoggedInUserState() } // Done callback(true, menuItemList, nil, nil) } override func didFinishModelLoading(data: Any?, error: ErrorEntity?) { // Store menu items self.menuItemList = data as! Array<MenuEntityProtocol>! } // MARK: // MARK: Internal // MARK: internal var _loadModelCallback: Callback? internal func menuItemsForNotLoggedInUserState() -> Array<MenuEntityProtocol> { // Create menu items var itemList: Array<MenuEntityProtocol> = Array() // Create menu items // Settings var item: MenuEntityProtocol = MenuEntity(title: localizedString(key: kMenuModelMenuItemSettingsKey), viewController: self.viewControllerFactory.settingsViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // User login item = MenuEntity(title: localizedString(key: kMenuModelMenuItemLoginKey), viewController: self.viewControllerFactory.userContainerViewController(context: nil), isModal: true) as MenuEntityProtocol itemList.append(item) // TermsConditions item = MenuEntity(title: localizedString(key: kMenuModelMenuItemTermsConditionsKey), viewController: self.viewControllerFactory.termsConditionsViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // Privacy policy item = MenuEntity(title: localizedString(key: kMenuModelMenuItemPrivacyPolicyKey), viewController: self.viewControllerFactory.privacyPolicyViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // TableViewExample /*item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewExampleKey); item.viewController = (BaseViewController *) [viewControllerFactory tableViewExampleViewControllerWithContext:nil]; [itemList addObject:item]; // TableView with search item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewWithSearchKey); item.viewController = (BaseViewController *) [viewControllerFactory tableWithSearchViewControllerWithContext:nil]; [itemList addObject:item]; // Map item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapWithSearchKey); item.viewController = (BaseViewController *) [viewControllerFactory mapsViewControllerWithContext:nil]; [itemList addObject:item];*/ // Return return itemList } func menuItemsForLoggedInUserState() -> Array<MenuEntityProtocol> { // Create menu items var itemList: Array<MenuEntityProtocol> = Array() // Create menu items // Settings var item: MenuEntityProtocol = MenuEntity(title: localizedString(key: kMenuModelMenuItemSettingsKey), viewController: self.viewControllerFactory.settingsViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // TermsConditions item = MenuEntity(title: localizedString(key: kMenuModelMenuItemTermsConditionsKey), viewController: self.viewControllerFactory.termsConditionsViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // Privacy policy item = MenuEntity(title: localizedString(key: kMenuModelMenuItemPrivacyPolicyKey), viewController: self.viewControllerFactory.privacyPolicyViewController(context: nil), isModal: false) as MenuEntityProtocol itemList.append(item) // TableViewExample /*item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewExampleKey); item.viewController = (BaseViewController *) [viewControllerFactory tableViewExampleViewControllerWithContext:nil]; [itemList addObject:item]; // TableView with search item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemTableViewWithSearchKey); item.viewController = (BaseViewController *) [viewControllerFactory tableWithSearchViewControllerWithContext:nil]; [itemList addObject:item]; // Map item = [[MenuItemObject alloc] init]; item.menuTitle = GMLocalizedString(kMenuModelMenuItemMapWithSearchKey); item.viewController = (BaseViewController *) [viewControllerFactory mapsViewControllerWithContext:nil]; [itemList addObject:item];*/ // Return return itemList } }
mit
9309ed3a432b2031be1e00f82d531ce9
41.574661
228
0.678499
5.277061
false
false
false
false
SpriteKitAlliance/SKATiledMap
SKATiledMap/SKATiledMap.swift
1
30026
// // SKATiledMap.swift // // Created by Skyler Lauren on 10/5/15. // Copyright © 2015 Sprite Kit Alliance. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import Foundation import SpriteKit /** Enum used to define collision for auto generated physics feature */ enum SKAColliderType: UInt32 { case Player = 1 case Floor = 2 case Wall = 4 } class SKATiledMap : SKNode{ //MARK: - Public Properties /** Number of columns for the map */ var mapWidth : Int /** Number of rows for the map */ var mapHeight : Int /** Width of a single tile */ var tileWidth : Int /** Height of a single tile */ var tileHeight : Int /** returns an array of SKASpriteLayers */ var spriteLayers = [SKASpriteLayer]() /** returns an array of SKAObjectLayers */ var objectLayers = [SKAObjectLayer]() /** Additional properties found on the map */ var mapProperties = [String : AnyObject]() /** Used for moving the map based on the position of a child node */ var autoFollowNode : SKNode? //MARK: - Private Properties /** Culling logic */ private var culledBefore = false private var visibleArray = [SKASprite]() private var lastY = 0 private var lastX = 0 private var lastWidth = 0 private var lastHeight = 0 var tmxParser : SKATMXParser? //MARK: - Initializers /** Designated Initializer @param mapName name of the map you want. No need for file extension */ init(mapName: String){ mapWidth = 0 mapHeight = 0 tileWidth = 0 tileHeight = 0 super.init() loadFile(mapName) } //MARK: - Public Functions /** Looks for tmx or json file based on a map name and loads map data @param fileName the name of the map without a file extension */ func loadFile(fileName: String) { //checks for tmx first then trys json if a tmx file can not be found if let filePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "tmx"){ tmxParser = SKATMXParser(filePath:filePath) loadMap((tmxParser?.mapDictionary)!) } else { //looks for tmx file if let filePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "json"){ mapDictionaryForJSONFile(filePath) } } } /** Used to update map position if autoFollowNode is set */ func update(){ if (autoFollowNode != nil && scene?.view != nil) { position = CGPointMake( -autoFollowNode!.position.x + scene!.size.width / 2, -autoFollowNode!.position.y + scene!.size.height / 2); //check position of the minimap and stop it from going off screen var tempPosition = position; if(tempPosition.x > 0) { tempPosition.x = 0; } if(tempPosition.y > 0) { tempPosition.y = 0; } if(tempPosition.y < -CGFloat(mapHeight * tileHeight) + scene!.size.height){ tempPosition.y = -CGFloat(mapHeight * tileHeight) + scene!.size.height } if(tempPosition.x < -CGFloat(mapWidth * tileWidth) + scene!.size.width){ tempPosition.x = -CGFloat(mapWidth * tileWidth) + scene!.size.width } //shound round to whole numbers position = tempPosition } } /** Culling "hiding" nodes that do not need to be rendered greatly improves performace and frame rate. This method is optimized to be called every update loop @param x the center x index you wish to cull around @param y the center y index you wish to cull around @param width the number of tiles wide you would like to keep @param height the number of tiles high you would like to keep */ func cullAround(x : Int, y : Int, width : Int, height : Int){ if(!culledBefore) { for var layerIndex = 0; layerIndex < spriteLayers.count; ++layerIndex{ for var xIndex = 0; xIndex < mapWidth; ++xIndex{ for var yIndex = 0; yIndex < mapHeight; ++yIndex{ let sprite = spriteFor(layerIndex, x: xIndex, y: yIndex) sprite.hidden = true } } } } if(lastX != x || lastY != y || lastWidth != width || lastHeight != height){ for vSprite in visibleArray{ vSprite.hidden = true } // calculate what to make visiable visibleArray = [SKASprite]() var startingX = x - width / 2 var startingY = y - height / 2 var endingX = startingX + width var endingY = startingY + height //preventing trying to unhide sprites off map if(startingX < 0){ startingX = 0 endingX = width } if(startingY < 0){ startingY = 0 endingY = height } if(endingX >= mapWidth){ endingX = mapWidth startingX = endingX - width } if (endingY >= mapHeight){ endingY = mapHeight startingY = endingY - height } if(startingX < 0){ startingX = 0 } if(startingY < 0){ startingY = 0 } if(endingX < 0){ endingX = 0 } if(endingY < 0){ endingY = 0 } //un hiding sprites that need to be rendered for var layerIndex = 0; layerIndex < spriteLayers.count; ++layerIndex{ for var xIndex = startingX; xIndex < endingX; ++xIndex{ for var yIndex = startingY; yIndex < endingY; ++yIndex{ let sprite = spriteFor(layerIndex, x: xIndex, y: yIndex) sprite.hidden = false visibleArray.append(sprite) } } } //storing values to optimize culling during update lastX = x lastY = y lastWidth = width lastHeight = height culledBefore = true } } /** Returns a CGPoint that can be used as an x and y index @param point the point in which to calculate the index */ func index(point : CGPoint) -> CGPoint{ let x = Int(point.x)/tileWidth let y = Int(point.y)/tileHeight return CGPointMake(CGFloat(x), CGFloat(y)); } /** This method is used to get custom named objects that you may have made in Tiled for spawning enemies, player start positions, or any other custom game logic you made a object for. */ func objectsOn(layerNumber: Int, name: String) -> [SKAObject]?{ let objects = objectLayers[layerNumber].objects return objects.filter({$0.name == name}) } /** Returns all the tiles around a specific index for a specific point. Very useful if you need to know about tiles around a specific index. @param index the CGPoint that will be used as a x and y index @param layerNumber the layer in which you would like your tiles */ func tilesAround(index : CGPoint, layerNumber : Int)-> [SKASprite?]{ let x = Int(index.x) let y = Int(index.y) var tiles = [SKASprite]() let layer = spriteLayers[layerNumber] //grabbring sprites but checking to make sure it isn't trying to grab outside map bounds if (x - 1 > 0){ tiles.append(layer.sprites[x-1][y]) if(y - 1 >= 0){ tiles.append(layer.sprites[x-1][y-1]) } if(y + 1 < self.mapHeight){ tiles.append(layer.sprites[x-1][y+1]) } } if (x + 1 < self.mapWidth){ tiles.append(layer.sprites[x+1][y]) if(y + 1 < self.mapHeight){ tiles.append(layer.sprites[x+1][y+1]) } if(y - 1 >= 0){ tiles.append(layer.sprites[x+1][y-1]) } } if (y - 1 >= 0) { tiles.append(layer.sprites[x][y-1]) } if (y + 1 < mapHeight){ tiles.append(layer.sprites[x][y+1]) } return tiles } /** Convientent method to quickly get a specific tile for a specific layer on the map @param layerNumber the layer in which you would like to use @param x the x index to use @param y the y index to use */ func spriteFor(layerNumber : Int, x : Int, y : Int) -> SKASprite{ let layer = spriteLayers[layerNumber] let sprite = layer.sprites[x][y] return sprite } // MARK: - Private Class Functions /** Creates the key value pair needed for map creation based on json file @param filePath the path to the JSON file */ func mapDictionaryForJSONFile(filePath : String){ //attemps to return convert json file over to a key value pairs do{ let JSONData = try NSData(contentsOfFile: filePath, options: .DataReadingMappedIfSafe) if (JSONData.length > 0) { do{ let mapDictionary = try NSJSONSerialization.JSONObjectWithData(JSONData, options:.AllowFragments) as! [String:AnyObject] loadMap(mapDictionary) } catch { print("Unable to convert \(filePath) to a key value object") } } } catch { print("Unable to load \(filePath) as NSData") } } /** Generates a map based on pre determined keys and values @param mapDictionary the key value set that originated from a tmx or json file */ private func loadMap(mapDictionary : [String : AnyObject]){ //getting additional user generated properties for map guard let _ = mapDictionary["properties"] as? [String : AnyObject] else { fatalError("Error: Map is missing properties values") } mapProperties = mapDictionary["properties"] as! [String : AnyObject] //getting value that determines how many tiles wide the map is guard let _ = mapDictionary["width"] as? Int else { fatalError("Error: Map is missing width value") } mapWidth = mapDictionary["width"] as! Int //getting value that determines how many tiles tall a map is guard let _ = mapDictionary["height"] as? Int else { fatalError("Error: Map is missing height value") } mapHeight = mapDictionary["height"] as! Int //getting value that determines the width of a tile guard let _ = mapDictionary["tilewidth"] as? Int else { fatalError("Error: Map is missing width value") } tileWidth = mapDictionary["tilewidth"] as! Int //getting value that determines the height of a tile guard let _ = mapDictionary["tileheight"] as? Int else { fatalError("Error: Map is missing width value") } tileHeight = mapDictionary["tileheight"] as! Int var mapTiles = [String : SKAMapTile]() guard let tileSets = mapDictionary["tilesets"] as? [AnyObject] else{ fatalError("Map is missing tile sets to generate map") } //setting up all tile set layers for (_, element) in tileSets.enumerate() { guard let tileSet = element as? [String : AnyObject] else{ fatalError("Error: tile sets are not properly formatted") } let tilesetProperties = tileSet["tileproperties"] as? [String: AnyObject] guard let tileWidth = tileSet["tilewidth"] as? Int else{ fatalError("Error: tile width for tile set isn't set propertly") } guard let tileHeight = tileSet["tileheight"] as? Int else{ fatalError("Error: tile width for tile set isn't set propertly") } //determining if we have a sprite sheet if let path = tileSet["image"] as? NSString{ //parsing out the image name let component = path.lastPathComponent as NSString let imageName = component.stringByDeletingPathExtension let imageExtension = component.pathExtension var textureImage : UIImage? //first trying to get the image without absolute path if let image = UIImage(named: imageName){ textureImage = image } else { //resorting to absolute path if reference folders are used if let filePath = NSBundle.mainBundle().pathForResource(imageName, ofType: imageExtension){ textureImage = UIImage(contentsOfFile: filePath) }else{ print("Error: missing image: \(imageName)") } } //creating smaller textures from big texture if (textureImage != nil) { let mainTexture = SKTexture(image: textureImage!) mainTexture.filteringMode = .Nearest //geting sprite sheet information guard let imageWidth = tileSet["imagewidth"] as? Int else { fatalError("Error: Image width is not set properly on tile sheet") } guard let imageHeight = tileSet["imageheight"] as? Int else{ fatalError("Error: Image height is not set properly on tile sheet") } guard let spacing = tileSet["spacing"] as? Int else{ fatalError("Error: Image spacing is not set properly on tile sheet") } guard let margin = tileSet["margin"] as? Int else{ fatalError("Error: Image margin is not set properly on tile sheet") } guard let firstIndex = tileSet["firstgid"] as? Int else{ fatalError("Error: Image firstgid is not set properly on tile sheet") } let width = imageWidth - (margin * 2) let height = imageHeight - (margin * 2) let tileColumns : Int = Int(ceil(Float(width) / Float(tileWidth + spacing))) let tileRows : Int = Int(ceil(Float(height) / Float(tileHeight + spacing))) let spacingPercentWidth : Float = Float(spacing)/Float(imageWidth) let spacingPercentHeight : Float = Float(spacing)/Float(imageHeight) let marginPercentWidth : Float = Float(margin) / Float(tileWidth) let marginPercentHeight : Float = Float(margin) / Float(tileHeight) let tileWidthPercent : Float = Float (tileWidth) / Float(imageWidth) let tileHeightPercent : Float = Float (tileHeight) / Float(imageHeight) var index = firstIndex let tilesetProperties = tileSet["tileproperties"] as? [String: AnyObject] for var rowID = 0; rowID < tileRows; ++rowID{ for var columnID = 0; columnID < tileColumns; ++columnID{ // advance based on column let x = CGFloat(marginPercentWidth + Float(columnID) * Float(tileWidthPercent + spacingPercentWidth)); //advance based on row let yOffset = Float(marginPercentHeight + tileHeightPercent) let yTileHeight = Float(tileHeightPercent + spacingPercentHeight) let y = CGFloat(1.0 - (yOffset + (Float(rowID) * yTileHeight))) let texture = SKTexture(rect: CGRectMake(x, y, CGFloat(tileWidthPercent), CGFloat(tileHeightPercent)), inTexture: mainTexture) texture.filteringMode = .Nearest //creating mapTile object to store texture and sprite properties let mapTile = SKAMapTile(texture: texture) let propertiesKey = String(index-firstIndex) if (tilesetProperties != nil && tilesetProperties?.count > 0) { if let tileProperties = tilesetProperties![propertiesKey] as? [String : AnyObject]{ mapTile.properties = tileProperties } } mapTiles[String(index)] = mapTile index++; } } } else { print("It appears Image:\(component) is missing") return; } } //determining if we are working with image collection if let collectionTiles = tileSet["tiles"] as? [String : AnyObject] { guard let firstIndex = tileSet["firstgid"] as? Int else{ fatalError("Error: Image firstgid is not set properly on tile sheet") } for (key, spriteDict) in collectionTiles{ if let dict = spriteDict as? [String : AnyObject]{ //getting image name to be used in texture var imageName : NSString? if let imagePath = dict["image"] as? NSString{ imageName = imagePath.lastPathComponent } if let imagePath = dict["source"] as? NSString{ imageName = imagePath.lastPathComponent } if (imageName != nil) { //creating mapTile object to store texture and sprite properties let texture = SKTexture(imageNamed: (imageName!.stringByDeletingPathExtension)) texture.filteringMode = .Nearest let index = Int(key)! + firstIndex let mapTile = SKAMapTile(texture: texture) mapTile.properties = dict if (tilesetProperties != nil && tilesetProperties?.count > 0) { if let tileProperties = tilesetProperties![key] as? [String : AnyObject]{ mapTile.properties = tileProperties } } mapTiles[String(index)] = mapTile } } } } } var layerNumber = 0 //generating layers if let layers = mapDictionary["layers"] as? [AnyObject]{ for layer in layers { if let layerDictionary = layer as? [String : AnyObject] { //determining if we are working with a sprite layer if let tileIDs = layerDictionary["data"] as? [Int]{ //creating a sprite layer to hold all sprites for that layer let spriteLayer = SKASpriteLayer(properties: layerDictionary) //sorting tile ids in the correct order var rowArray = [[Int]]() var rangeStart = 0 let rangeLength = mapWidth-1 for var index = 0; index < mapHeight; ++index{ rangeStart = tileIDs.count - ((index + 1) * mapWidth ) let row : [Int] = Array(tileIDs[rangeStart...rangeStart+rangeLength]) rowArray.append(row) } //creating a 2d array to make it easy to locate sprites by index var sprites = Array(count: mapWidth, repeatedValue:Array(count: mapHeight, repeatedValue: SKASprite())) //adding sprites for (rowIndex, row) in rowArray.enumerate(){ for (columnIndex, number) in row.enumerate(){ let key = String(number) if let mapTile = mapTiles[key]{ let sprite = SKASprite(texture: mapTile.texture) //positioning let xOffset = Int(tileWidth / 2) let yOffset = Int(tileHeight / 2) let x = (Int(sprite.size.width / 2) - xOffset) + xOffset + columnIndex * tileWidth let y = (Int(sprite.size.height / 2) - yOffset) + yOffset + rowIndex * tileHeight sprite.position = CGPointMake(CGFloat(x), CGFloat(y)) sprite.properties = mapTile.properties //creating collision body if special SKACollision type is set if let properties = sprite.properties{ if let collisionType = properties["SKACollisionType"] as? String{ if collisionType == "SKACollisionTypeRect"{ sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size) sprite.physicsBody!.dynamic = false sprite.physicsBody!.categoryBitMask = SKAColliderType.Floor.rawValue; sprite.physicsBody!.contactTestBitMask = SKAColliderType.Player.rawValue; sprite.zPosition = 20; } } } spriteLayer.addChild(sprite) sprites[columnIndex][rowIndex] = sprite } } } spriteLayer.sprites = sprites spriteLayer.zPosition = CGFloat(layerNumber) addChild(spriteLayer) spriteLayers.append(spriteLayer) layerNumber++ } //determining if we are working with an object layer if let objectsArray = layerDictionary["objects"] as? [AnyObject]{ //creating an object layer to hold object layer info let objectLayer = SKAObjectLayer(properties: layerDictionary) var collisionSprites = [SKASprite]() var objects = [SKAObject]() for objectDictionary in objectsArray{ if let properties = objectDictionary as? [String : AnyObject]{ let object = SKAObject(properties: properties) //getting origin in the correct position based on draw order if(objectLayer.drawOrder == "topdown") { object.y = (mapHeight * tileHeight) - object.y - object.height; } //creating collision body if special SKACollision type is set if let objectProperties = object.properties{ if let collisionType = objectProperties["SKACollisionType"] as? String{ if collisionType == "SKACollisionTypeRect"{ let floorSprite = SKASprite(color: SKColor.clearColor(), size: CGSizeMake(CGFloat(object.width), CGFloat(object.height))) floorSprite.zPosition = CGFloat(layerNumber) let centerX = CGFloat(object.x+object.width/2) let centerY = CGFloat(object.y+object.height/2) floorSprite.position = CGPointMake(centerX, centerY) floorSprite.physicsBody = SKPhysicsBody(rectangleOfSize: floorSprite.size) floorSprite.physicsBody?.dynamic = false floorSprite.physicsBody!.categoryBitMask = SKAColliderType.Floor.rawValue; floorSprite.physicsBody!.contactTestBitMask = SKAColliderType.Player.rawValue; addChild(floorSprite) collisionSprites.append(floorSprite) } } } objects.append(object) } } objectLayer.collisionSprites = collisionSprites; objectLayer.objects = objects; objectLayers.append(objectLayer) layerNumber++; } } } } } /** Lame required function for subclassing */ required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7a376f4c08d757787d939b89b33a92e3
39.466307
165
0.470575
5.818798
false
false
false
false
JetBrains/kotlin-native
performance/KotlinVsSwift/ring/src/LambdaBenchmark.swift
4
2212
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Foundation class LambdaBenchmark { @inlinable public func runLambda<T>(_ x: () -> T) -> T { return x() } private func runLambdaNoInline<T>(_ x: () -> T) -> T { return x() } init() { Constants.globalAddendum = Int.random(in: 0 ..< 20) } func noncapturingLambda() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambda { Constants.globalAddendum } } return x } func noncapturingLambdaNoInline() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambdaNoInline { Constants.globalAddendum } } return x } func capturingLambda() -> Int { let addendum = Constants.globalAddendum + 1 var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambda { addendum } } return x } func capturingLambdaNoInline() -> Int { let addendum = Constants.globalAddendum + 1 var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambdaNoInline { addendum } } return x } func mutatingLambda() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { runLambda { x += Constants.globalAddendum } } return x } func mutatingLambdaNoInline() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { runLambdaNoInline { x += Constants.globalAddendum } } return x } func methodReference() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambda(referenced) } return x } func methodReferenceNoInline() -> Int { var x: Int = 0 for _ in 0...Constants.BENCHMARK_SIZE { x += runLambdaNoInline(referenced) } return x } } private func referenced() -> Int { return Constants.globalAddendum }
apache-2.0
ed72c0d2feae2bac8cbb20afb46430b7
23.307692
101
0.534358
3.894366
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Authentication/PinFlow/PinScreen/TooManyAttemptsAlertView.swift
1
1875
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Localization import SwiftUI import UIComponentsKit import UIKit class TooManyAttemptsAlertViewController: UIViewController { private let contentView = UIHostingController(rootView: TooManyAttemptsAlertView()) override func viewDidLoad() { super.viewDidLoad() view.addSubview(contentView.view) addChild(contentView) setupConstraints() contentView.rootView.okPressed = { [weak self] in self?.dismiss(animated: true, completion: nil) } } private func setupConstraints() { contentView.view.translatesAutoresizingMaskIntoConstraints = false contentView.view.heightAnchor.constraint(equalToConstant: 280).isActive = true contentView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true contentView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true contentView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true } } private struct TooManyAttemptsAlertView: View { var okPressed: (() -> Void)? var body: some View { VStack(alignment: .center) { Text(LocalizationConstants.Pin.tooManyAttemptsTitle) .textStyle(.title) .padding(.bottom, 10) Text(LocalizationConstants.Pin.tooManyAttemptsWarningMessage) Spacer() PrimaryButton(title: LocalizationConstants.okString) { okPressed?() } .padding(.bottom, 5) } .padding(EdgeInsets(top: 34, leading: 24, bottom: 0, trailing: 24)) } } private struct TooManyAttemptsAlertView_Previews: PreviewProvider { static var previews: some View { TooManyAttemptsAlertView() } }
lgpl-3.0
780c8a6d6d9bf774e4385687f04bff33
33.072727
96
0.685165
5.2493
false
false
false
false
toadzky/SLF4Swift
Backend/Loggerithm/Loggerithm.swift
1
4469
// // Loggerithm.swift // SLF4Swift /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) 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 #if EXTERNAL import SLF4Swift #endif import Loggerithm public class LoggerithmSLF: LoggerType { public class var instance : LoggerithmSLF { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : LoggerithmSLF? } dispatch_once(&Static.onceToken) { Static.instance = LoggerithmSLF(logger: Loggerithm.defaultLogger, name: "default") } return Static.instance! } public var level: SLFLogLevel { get { return LoggerithmSLF.toLevel(self.logger.logLevel) } set { self.logger.logLevel = LoggerithmSLF.fromLevel(newValue) } } public var name: LoggerKeyType public var logger: Loggerithm public init(logger: Loggerithm, name: LoggerKeyType) { self.logger = logger self.name = name } public func info(message: LogMessageType) { self.logger.info(message) } public func error(message: LogMessageType) { self.logger.error(message) } public func severe(message: LogMessageType) { self.logger.error(message) } public func warn(message: LogMessageType) { self.logger.warning(message) } public func debug(message: LogMessageType) { self.logger.debug(message) } public func verbose(message: LogMessageType) { self.logger.verbose(message) } public func log(level: SLFLogLevel,_ message: LogMessageType) { self.logger.logWithLevel(LoggerithmSLF.fromLevel(level), message) } public func isLoggable(level: SLFLogLevel) -> Bool { return level <= self.level } public static func toLevel(level: LogLevel) -> SLFLogLevel { switch(level){ case .Off: return SLFLogLevel.Off case .Error: return SLFLogLevel.Error case .Warning: return SLFLogLevel.Warn case .Info: return SLFLogLevel.Info case .Debug: return SLFLogLevel.Debug case .Verbose: return SLFLogLevel.Verbose case .All: return SLFLogLevel.All } } public static func fromLevel(level:SLFLogLevel) -> LogLevel { switch(level){ case .Off: return LogLevel.Off case .Severe: return LogLevel.Error case .Error: return LogLevel.Error case .Warn: return LogLevel.Warning case .Info: return LogLevel.Info case .Debug: return LogLevel.Debug case .Verbose: return LogLevel.Verbose case .All: return LogLevel.All } } } public class LoggerithmSLFFactory: SLFLoggerFactory { public class var instance : LoggerithmSLFFactory { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : LoggerithmSLFFactory? } dispatch_once(&Static.onceToken) { let factory = LoggerithmSLFFactory() Static.instance = factory factory.addLogger(LoggerithmSLF.instance) } return Static.instance! } public override init(){ super.init() } public override func doCreateLogger(name: LoggerKeyType) -> LoggerType { let logger = Loggerithm() return LoggerithmSLF(logger: logger, name: name) } }
mit
0488bd72b6b3223ff9f3a629d344175e
30.041667
94
0.666816
4.305395
false
false
false
false
ibari/ios-tips
tips/SettingsViewController.swift
1
1791
// // SettingsViewController.swift // tips // // Created by Ian on 4/1/15. // Copyright (c) 2015 ibari. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) var defaults = NSUserDefaults.standardUserDefaults() if (defaults.objectForKey("tip_percentage_index") != nil) { tipControl.selectedSegmentIndex = defaults.integerForKey("tip_percentage_index") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEditingChanged(sender: AnyObject) { //var tipPercentages = [0.18, 0.2, 0.22] //var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] var defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(tipControl.selectedSegmentIndex, forKey: "tip_percentage_index") defaults.synchronize() } @IBAction func onTouchDown(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c63608f166697207193dc66ef5c47249
29.355932
106
0.666108
5.191304
false
false
false
false
AmitaiB/AmazingAgeTrick
AmazingAgeTrick/LogFunc.swift
1
674
// // LogFunc.swift // AmazingAgeTrick // // Created by Amitai Blickstein on 1/3/16. // Copyright © 2016 Amitai Blickstein, LLC. All rights reserved. // import Foundation public func EVLog<T>(object: T, filename: String = __FILE__, line: Int = __LINE__, funcname: String = __FUNCTION__) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss:SSS" let process = NSProcessInfo.processInfo() let threadId = "?" print("\(dateFormatter.stringFromDate(NSDate())) \(process.processName))[\(process.processIdentifier):\(threadId)] \(NSURL.init(string:filename)?.lastPathComponent)(\(line)) \(funcname):\r\t\(object)\n") }
mit
cff1514c5f05b8e4e0276feeff11b2f6
38.588235
207
0.686478
3.738889
false
false
false
false
FindGF/_BiliBili
WTBilibili/Other-其他/Login-登陆/Controller/WTLoginViewController.swift
1
4455
// // WTLoginViewController.swift // WTBilibili // // Created by 无头骑士 GJ on 16/5/30. // Copyright © 2016年 无头骑士 GJ. All rights reserved. // 登陆控制器 import UIKit class WTLoginViewController: UIViewController { // MARK: - 拖线的属性 @IBOutlet weak var loginHeaderImageV: UIImageView! /// 手机或邮箱 @IBOutlet weak var phoneTextF: UITextField! /// 密码 @IBOutlet weak var passwordTextF: UITextField! /// 注册按钮 @IBOutlet weak var registerBtn: UIButton! /// 登陆按钮 @IBOutlet weak var loginBtn: UIButton! // MARK: - 懒加载 /// 手机或邮箱左侧的View lazy var phoneLeftView: UIImageView = { let phoneLeftView = UIImageView() phoneLeftView.image = UIImage(named: "ictab_me") phoneLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45) phoneLeftView.contentMode = .Center return phoneLeftView }() /// 密码左侧的View lazy var passwordLeftView: UIImageView = { let passwordLeftView = UIImageView() passwordLeftView.image = UIImage(named: "pws_icon") passwordLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45) passwordLeftView.contentMode = .Center return passwordLeftView }() // MARK: - 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI setupUI() } } // MARK: - 自定义函数 extension WTLoginViewController { // MARK: 设置UI private func setupUI() { // 0、设置导航栏 setupNav() // 1、手机或邮箱 setupCommonTextField(phoneTextF, leftView: phoneLeftView) // 2、密码 setupCommonTextField(passwordTextF, leftView: passwordLeftView) // 3、注册按钮 self.registerBtn.layer.cornerRadius = 3 self.registerBtn.layer.borderColor = WTColor(r: 231, g: 231, b: 231).CGColor self.registerBtn.layer.borderWidth = 1 // 4、登陆按钮 self.loginBtn.layer.cornerRadius = 3 } // MARK: 设置导航栏 private func setupNav() { title = "登录" // 关闭按钮 navigationItem.leftBarButtonItem = UIBarButtonItem.createCloseItem(self, action: #selector(closeBtnClick)) // 忘记密码 let forgetPasswordBtn = UIButton(type: .Custom) forgetPasswordBtn.titleLabel?.font = UIFont.setQIHeiFontWithSize(14) forgetPasswordBtn.setTitle("忘记密码", forState: .Normal) forgetPasswordBtn.addTarget(self, action: #selector(forgetPasswordBtnClick), forControlEvents: .TouchUpInside) forgetPasswordBtn.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: forgetPasswordBtn) } // MARK: 设置textField公共属性 private func setupCommonTextField(textField: UITextField, leftView: UIImageView) { textField.tintColor = WTMainColor textField.leftView = leftView textField.leftViewMode = .Always } } // MARK: - 事件 extension WTLoginViewController { // MARK: 关闭按钮 func closeBtnClick() { dismissViewControllerAnimated(true, completion: nil) } // MARK: 忘记密码 func forgetPasswordBtnClick() { } // MARK: 注册按钮 @IBAction func registerBtnClick() { } // MARK: 登陆按钮 @IBAction func loginBtnClick() { } } // MARK: - UITextFieldDelegate extension WTLoginViewController: UITextFieldDelegate { func textFieldDidBeginEditing(textField: UITextField) { if textField.tag == 1 { self.phoneLeftView.image = UIImage(named: "ictab_me_selected") } else if textField.tag == 2 { self.loginHeaderImageV.image = UIImage(named: "login_header_cover_eyes") self.passwordLeftView.image = UIImage(named: "pws_icon_hover") } } func textFieldDidEndEditing(textField: UITextField) { if textField.tag == 1 { self.phoneLeftView.image = UIImage(named: "ictab_me") } else if textField.tag == 2 { self.loginHeaderImageV.image = UIImage(named: "login_header") self.passwordLeftView.image = UIImage(named: "pws_icon") } } }
apache-2.0
19e9330e5776ae5a8d1f13a3299b2adb
25.175
118
0.614136
4.299795
false
false
false
false
jovito-royeca/Decktracker
ios/Pods/Eureka/Source/Core/BaseRow.swift
5
9193
// BaseRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public class BaseRow : BaseRowType { var callbackOnChange: (()->Void)? var callbackCellUpdate: (()->Void)? var callbackCellSetup: Any? var callbackCellOnSelection: (()->Void)? var callbackOnCellHighlight: (()->Void)? var callbackOnCellUnHighlight: (()->Void)? var callbackOnExpandInlineRow: Any? var callbackOnCollapseInlineRow: Any? var _inlineRow: BaseRow? /// The title will be displayed in the textLabel of the row. public var title: String? /// Parameter used when creating the cell for this row. public var cellStyle = UITableViewCellStyle.Value1 /// String that uniquely identifies a row. Must be unique among rows and sections. public var tag: String? /// The untyped cell associated to this row. public var baseCell: BaseCell! { return nil } /// The untyped value of this row. public var baseValue: Any? { set {} get { return nil } } public static var estimatedRowHeight: CGFloat = 44.0 /// Condition that determines if the row should be disabled or not. public var disabled : Condition? { willSet { removeFromDisabledRowObservers() } didSet { addToDisabledRowObservers() } } /// Condition that determines if the row should be hidden or not. public var hidden : Condition? { willSet { removeFromHiddenRowObservers() } didSet { addToHiddenRowObservers() } } /// Returns if this row is currently disabled or not public var isDisabled : Bool { return disabledCache } /// Returns if this row is currently hidden or not public var isHidden : Bool { return hiddenCache } /// The section to which this row belongs. public weak var section: Section? public required init(tag: String? = nil){ self.tag = tag } /** Method that reloads the cell */ public func updateCell() {} /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ public func didSelect() {} /** Method that is responsible for highlighting the cell. */ public func highlightCell() {} @available(*, unavailable, message="Deprecated. Use 'highlightCell' instead.") public func hightlightCell() { highlightCell() } /** Method that is responsible for unhighlighting the cell. */ public func unhighlightCell() {} public func prepareForSegue(segue: UIStoryboardSegue) {} /** Returns the NSIndexPath where this row is in the current form. */ public final func indexPath() -> NSIndexPath? { guard let sectionIndex = section?.index, let rowIndex = section?.indexOf(self) else { return nil } return NSIndexPath(forRow: rowIndex, inSection: sectionIndex) } private var hiddenCache = false private var disabledCache = false { willSet { if newValue == true && disabledCache == false { baseCell.cellResignFirstResponder() } } } } extension BaseRow { /** Evaluates if the row should be hidden or not and updates the form accordingly */ public final func evaluateHidden() { guard let h = hidden, let form = section?.form else { return } switch h { case .Function(_ , let callback): hiddenCache = callback(form) case .Predicate(let predicate): hiddenCache = predicate.evaluateWithObject(self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } if hiddenCache { section?.hideRow(self) } else{ section?.showRow(self) } } /** Evaluates if the row should be disabled or not and updates it accordingly */ public final func evaluateDisabled() { guard let d = disabled, form = section?.form else { return } switch d { case .Function(_ , let callback): disabledCache = callback(form) case .Predicate(let predicate): disabledCache = predicate.evaluateWithObject(self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } updateCell() } final func wasAddedToFormInSection(section: Section) { self.section = section if let t = tag { assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)") self.section?.form?.rowsByTag[t] = self self.section?.form?.tagToValues[t] = baseValue as? AnyObject ?? NSNull() } addToRowObservers() evaluateHidden() evaluateDisabled() } final func addToHiddenRowObservers() { guard let h = hidden else { return } switch h { case .Function(let tags, _): section?.form?.addRowObservers(self, rowTags: tags, type: .Hidden) case .Predicate(let predicate): section?.form?.addRowObservers(self, rowTags: predicate.predicateVars, type: .Hidden) } } final func addToDisabledRowObservers() { guard let d = disabled else { return } switch d { case .Function(let tags, _): section?.form?.addRowObservers(self, rowTags: tags, type: .Disabled) case .Predicate(let predicate): section?.form?.addRowObservers(self, rowTags: predicate.predicateVars, type: .Disabled) } } final func addToRowObservers(){ addToHiddenRowObservers() addToDisabledRowObservers() } final func willBeRemovedFromForm(){ (self as? BaseInlineRowType)?.collapseInlineRow() if let t = tag { section?.form?.rowsByTag[t] = nil section?.form?.tagToValues[t] = nil } removeFromRowObservers() } final func removeFromHiddenRowObservers() { guard let h = hidden else { return } switch h { case .Function(let tags, _): section?.form?.removeRowObservers(self, rows: tags, type: .Hidden) case .Predicate(let predicate): section?.form?.removeRowObservers(self, rows: predicate.predicateVars, type: .Hidden) } } final func removeFromDisabledRowObservers() { guard let d = disabled else { return } switch d { case .Function(let tags, _): section?.form?.removeRowObservers(self, rows: tags, type: .Disabled) case .Predicate(let predicate): section?.form?.removeRowObservers(self, rows: predicate.predicateVars, type: .Disabled) } } final func removeFromRowObservers(){ removeFromHiddenRowObservers() removeFromDisabledRowObservers() } } extension BaseRow: Equatable, Hidable, Disableable {} extension BaseRow { public func reload(rowAnimation: UITableViewRowAnimation = .None) { guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, indexPath = indexPath() else { return } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: rowAnimation) } public func deselect(animated: Bool = true) { guard let indexPath = indexPath(), tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.deselectRowAtIndexPath(indexPath, animated: animated) } public func select(animated: Bool = false) { guard let indexPath = indexPath(), tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.selectRowAtIndexPath(indexPath, animated: animated, scrollPosition: .None) } } public func ==(lhs: BaseRow, rhs: BaseRow) -> Bool{ return lhs === rhs }
apache-2.0
97258d7e96b24cba4f3a8ec0f3e3c557
34.631783
176
0.645926
5.164607
false
false
false
false
ngquerol/Diurna
App/Sources/Parsing/MarkupParser.swift
1
6808
// // MarkupParser.swift // Diurna // // Created by Nicolas Gaulard-Querol on 12/02/2016. // Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved. // import AppKit extension Character { fileprivate func isMemberOf(_ set: CharacterSet) -> Bool { let bridgedCharacter = String(self).unicodeScalars.first! return set.contains(bridgedCharacter) } } private struct Parser { private var pos: String.Index private let input: String init(inputString: String) { input = inputString pos = input.startIndex } func nextCharacter() -> Character { return input[pos] } func startsWith(_ s: String) -> Bool { return input[pos...].hasPrefix(s) } func eof() -> Bool { return pos >= input.endIndex } @discardableResult mutating func consumeCharacter() -> Character { let char = input[pos] pos = input.index(after: pos) return char } @discardableResult mutating func consumeWhile(_ predicate: (Character) -> Bool) -> String { var result = String() while !eof(), predicate(nextCharacter()) { result.append(consumeCharacter()) } return result } mutating func consumeWhitespace() { consumeWhile { $0.isMemberOf(CharacterSet.whitespaces) } } } private struct Tag { let name: String let attributes: [String: String] } struct MarkupParser { private let leadingSpaceRegex: NSRegularExpression = { try! NSRegularExpression( pattern: "^(\\s{2,4})(\\S.*)$", options: .anchorsMatchLines ) }() private let codeParagraphStyle: NSParagraphStyle = { let codeParagraphStyle = NSMutableParagraphStyle() codeParagraphStyle.lineBreakMode = .byCharWrapping codeParagraphStyle.headIndent = 10.0 codeParagraphStyle.firstLineHeadIndent = 10.0 codeParagraphStyle.tailIndent = -10.0 codeParagraphStyle.paragraphSpacing = 5.0 codeParagraphStyle.paragraphSpacingBefore = 5.0 return codeParagraphStyle }() private var parser: Parser init(input: String) { parser = Parser(inputString: input) } private mutating func parseTagName() -> String { var tagCharacterSet = CharacterSet(charactersIn: "/") tagCharacterSet.formUnion(CharacterSet.alphanumerics) return parser.consumeWhile { $0.isMemberOf(tagCharacterSet) } } private mutating func parseText() -> String { return CFXMLCreateStringByUnescapingEntities( nil, parser.consumeWhile { $0 != "<" } as CFString, nil ) as String } private mutating func parseAttribute() -> (String, String) { let name = parseTagName() parser.consumeCharacter() let value = parseAttributeValue() return (name, value) } private mutating func parseAttributeValue() -> String { let openQuote = parser.consumeCharacter() let unescapedValue = parser.consumeWhile { $0 != openQuote } let value = CFXMLCreateStringByUnescapingEntities( nil, unescapedValue as CFString, nil ) as String parser.consumeCharacter() return value } private mutating func parseAttributes() -> [String: String] { var attributes: [String: String] = [:] while parser.nextCharacter() != ">" { parser.consumeWhitespace() let (name, value) = parseAttribute() attributes[name] = value } return attributes } private mutating func parseTag() -> Tag { parser.consumeCharacter() let name = parseTagName() let attributes = parseAttributes() parser.consumeCharacter() return Tag( name: name, attributes: attributes ) } private func getFormattingAttributes(for tag: Tag?) -> [NSAttributedString.Key: Any] { let defaultFormattingAttributes: [NSAttributedString.Key: Any] = [ .font: NSFont.systemFont(ofSize: 12), .foregroundColor: NSColor.textColor, ] switch tag?.name { case "a": guard let urlString = tag?.attributes["href"], let url = URL(string: urlString) else { return defaultFormattingAttributes } return defaultFormattingAttributes.merging( [ .link: url, .foregroundColor: NSColor.linkColor, .underlineStyle: NSUnderlineStyle.single.rawValue, ], uniquingKeysWith: { $1 } ) case "i": return defaultFormattingAttributes.merging( [ .font: NSFontManager.shared.convert( NSFont.systemFont(ofSize: 12), toHaveTrait: .italicFontMask ) ], uniquingKeysWith: { $1 } ) case "code": return defaultFormattingAttributes.merging( [ .font: NSFont.userFixedPitchFont(ofSize: 11)!, .codeBlock: NSColor.lightGray, .paragraphStyle: codeParagraphStyle, ], uniquingKeysWith: { $1 } ) case _: return defaultFormattingAttributes } } private mutating func handleTag(_ result: NSMutableAttributedString) -> Tag { let tag = parseTag() if tag.name == "p" { result.append(NSAttributedString(string: "\n\n")) } return tag } private mutating func handleText(for tag: Tag?) -> NSAttributedString { let formattingAttributes = getFormattingAttributes(for: tag) var text = parseText() if tag?.name == "code" { let wholeTextRange = NSRange(0..<text.count) text = leadingSpaceRegex.stringByReplacingMatches( in: text, options: [], range: wholeTextRange, withTemplate: "$2" ) } return NSAttributedString( string: text, attributes: formattingAttributes ) } mutating func toAttributedString() -> NSAttributedString { let result = NSMutableAttributedString() var currentTag: Tag? result.beginEditing() while !parser.eof() { switch parser.nextCharacter() { case "<": currentTag = handleTag(result) case _: result.append(handleText(for: currentTag)) } } result.endEditing() return result } }
mit
d7abb07bf34707f28fbb590f4dd82b1d
26.897541
90
0.571911
5.252315
false
false
false
false
philackm/ScrollableGraphView
GraphView/GraphViewCode/ViewController.swift
2
8757
// // Simple example usage of ScrollableGraphView.swift // ################################################# // import UIKit class ViewController: UIViewController { // MARK: Properties var examples: Examples! var graphView: ScrollableGraphView! var currentGraphType = GraphType.multiOne var graphConstraints = [NSLayoutConstraint]() var label = UILabel() var reloadLabel = UILabel() override var prefersStatusBarHidden : Bool { return true } // MARK: Init override func viewDidLoad() { super.viewDidLoad() examples = Examples() graphView = examples.createMultiPlotGraphOne(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "MULTI 1") self.view.insertSubview(graphView, belowSubview: reloadLabel) setupConstraints() } // MARK: Constraints private func setupConstraints() { self.graphView.translatesAutoresizingMaskIntoConstraints = false graphConstraints.removeAll() let topConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutConstraint.Attribute.right, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.right, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutConstraint.Attribute.left, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.left, multiplier: 1, constant: 0) //let heightConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0) graphConstraints.append(topConstraint) graphConstraints.append(bottomConstraint) graphConstraints.append(leftConstraint) graphConstraints.append(rightConstraint) //graphConstraints.append(heightConstraint) self.view.addConstraints(graphConstraints) } // Adding and updating the graph switching label in the top right corner of the screen. private func addLabel(withText text: String) { label.removeFromSuperview() label = createLabel(withText: text) label.isUserInteractionEnabled = true let rightConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.right, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.right, multiplier: 1, constant: -20) let topConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 20) let heightConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40) let widthConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: label.frame.width * 1.5) let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(didTap)) label.addGestureRecognizer(tapGestureRecogniser) self.view.insertSubview(label, aboveSubview: reloadLabel) self.view.addConstraints([rightConstraint, topConstraint, heightConstraint, widthConstraint]) } private func addReloadLabel(withText text: String) { reloadLabel.removeFromSuperview() reloadLabel = createLabel(withText: text) reloadLabel.isUserInteractionEnabled = true let leftConstraint = NSLayoutConstraint(item: reloadLabel, attribute: NSLayoutConstraint.Attribute.left, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.left, multiplier: 1, constant: 20) let topConstraint = NSLayoutConstraint(item: reloadLabel, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 20) let heightConstraint = NSLayoutConstraint(item: reloadLabel, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40) let widthConstraint = NSLayoutConstraint(item: reloadLabel, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: reloadLabel.frame.width * 1.5) let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(reloadDidTap)) reloadLabel.addGestureRecognizer(tapGestureRecogniser) self.view.insertSubview(reloadLabel, aboveSubview: graphView) self.view.addConstraints([leftConstraint, topConstraint, heightConstraint, widthConstraint]) } private func createLabel(withText text: String) -> UILabel { let label = UILabel() label.backgroundColor = UIColor.black.withAlphaComponent(0.5) label.text = text label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.font = UIFont.boldSystemFont(ofSize: 14) label.layer.cornerRadius = 2 label.clipsToBounds = true label.translatesAutoresizingMaskIntoConstraints = false label.sizeToFit() return label } // MARK: Button Taps @objc func didTap(_ gesture: UITapGestureRecognizer) { currentGraphType.next() self.view.removeConstraints(graphConstraints) graphView.removeFromSuperview() switch(currentGraphType) { case .simple: // Show simple graph, no adapting, single line. graphView = examples.createSimpleGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "SIMPLE") case .multiOne: // Show graph with multiple plots, with adapting and using dot plots to decorate the line graphView = examples.createMultiPlotGraphOne(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "MULTI 1") case .multiTwo: graphView = examples.createMultiPlotGraphTwo(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "MULTI 2") case .dark: graphView = examples.createDarkGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "DARK") case .dot: graphView = examples.createDotGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "DOT") case .bar: graphView = examples.createBarGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "BAR") case .pink: graphView = examples.createPinkGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "PINK") case .blueOrange: graphView = examples.createBlueOrangeGraph(self.view.frame) addReloadLabel(withText: "RELOAD") addLabel(withText: "BLUE ORANGE") } self.view.insertSubview(graphView, belowSubview: reloadLabel) setupConstraints() } @objc func reloadDidTap(_ gesture: UITapGestureRecognizer) { examples.reload() graphView.reload() } }
mit
5198d3376ee9fd881f5747583b6d53f7
47.921788
285
0.69236
5.33313
false
false
false
false
wangCanHui/weiboSwift
weiboSwift/Classes/Lib/Emoticon/CZEmoticonViewController.swift
1
11211
// // CZEmoticonViewController.swift // 表情键盘 // // Created by 王灿辉 on 15/11/5. // Copyright © 2015年 王灿辉. All rights reserved. // import UIKit class CZEmoticonViewController: UIViewController { // MARK: - 属性 private let collectionViewCellIdentifier = "collectionViewCellIdentifier" /// 记录当前选中高亮的按钮 private var selectedButton: UIButton? /// textView weak var textView: UITextView? override func viewDidLoad() { super.viewDidLoad() // view.backgroundColor = UIColor.redColor() prepareUI() // print("viewDidLoad view.frame:\(view.frame)") } // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // // print("viewWillAppear view.frame:\(view.frame)") // } // // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // // viewDidAppear view.frame:(0.0, 0.0, 375.0, 216.0) // print("viewDidAppear view.frame:\(view.frame)") // } // MARK: - 准备UI private func prepareUI() { // 添加子控件 view.addSubview(collectionView) view.addSubview(toolBar) // 设置约束 collectionView.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false let views = ["cv" : collectionView, "tb" : toolBar] // VFL // collectionView水平方向 view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) // toolBar水平方向 view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) // 垂直方向 view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) setupToolBar() setupCollectionView() } /// 设置toolBar private func setupToolBar() { var items = [UIBarButtonItem]() // 记录 item 的位置 var index = 0 for packge in packages { let name = packge.group_name_cn let button = UIButton() // 设置标题 button.setTitle(name, forState: UIControlState.Normal) // 设置颜色 button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected) // 设置大小,不然不会显示 button.sizeToFit() // 设置tag button.tag = index // 添加单击事件 button.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside) // 让最近表情包默认选中高亮 if index == 0 { switchSelectedButton(button) } // 创建 barbuttomitem let item = UIBarButtonItem(customView: button) items.append(item) // 添加弹簧 items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)) index++ // index和++之间不能空格 } // 移除最后一个多有的弹簧 items.removeLast() toolBar.items = items } // 处理toolBar点击事件 func itemClick(button: UIButton) { // scction 0 - 3 let indexPath = NSIndexPath(forItem: 0, inSection: button.tag) // 让collectionView滚动到对应位置 // indexPath: 要显示的cell的indexPath // animated: 是否动画 // scrollPosition: 滚动位置 collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true) switchSelectedButton(button) } /** 使按钮高亮 - parameter button: 要高亮的按钮 */ private func switchSelectedButton(button: UIButton) { // 取消之前选中的 selectedButton?.selected = false // 让点击的按钮选中 button.selected = true // 将点击的按钮赋值给选中的按钮 selectedButton = button } /// 设置collectioView private func setupCollectionView() { // 设置背景颜色 collectionView.backgroundColor = UIColor(white: 0.85, alpha: 1) // 设置数据 collectionView.dataSource = self // 设置代理 collectionView.delegate = self // 注册cell collectionView.registerClass(CZEmotionCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier) } // MARK: - 懒加载 /// collectionView private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CZCollectionViewFlowLayout()) /// toolBar private lazy var toolBar = UIToolbar() /// 表情包模型 private lazy var packages = CZEmoticonPackage.packages } // MARK: - 扩展 CZEmoticonViewController 实现 协议 UICollectionViewDataSource extension CZEmoticonViewController: UICollectionViewDataSource , UICollectionViewDelegate{ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return packages.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return packages[section].emoticons?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 获取对应的表情模型 let emoticon = packages[indexPath.section].emoticons?[indexPath.item] let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! CZEmotionCell cell.emoticon = emoticon return cell } // 监听scrollView滚动,当停下来的时候判断显示的是哪个section func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // 获取到正在显示的section -> indexPath // 获取到collectionView正在显示的cell的IndexPath if let indexPath = collectionView.indexPathsForVisibleItems().first { let section = indexPath.section var buttonArr = [UIButton]() for item in toolBar.subviews { if item.isKindOfClass(UIButton) { let button = item as! UIButton buttonArr.append(button) } } let button = buttonArr[section] switchSelectedButton(button) } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 添加表情到textView // 获取到表情 let emoticon = packages[indexPath.section].emoticons![indexPath.item] textView?.insertEmoticon(emoticon) // 当点击最近里面的表情,发现点击的和添加到textView上面的不是同一个,原因是数据发生改变,显示没有变化 // 1.刷新数据 // collectionView.reloadSections(NSIndexSet(index: indexPath.section)) // 2.当点击的是最近表情包得表情,不添加到最近表情包和排序 if indexPath.item != 0 { // 添加 表情模型 到 最近表情包 CZEmoticonPackage.addFavourite(emoticon) } } } // MARK: - 自定义表情cell class CZEmotionCell: UICollectionViewCell { // MARK: - 属性 /// 表情模型 var emoticon: CZEmoticon? { didSet{ // 设置内容 // 1 .设置显示图片表情 // print("emoticon.png\(emoticon?.pngPath)") if let pngPath = emoticon?.pngPath { emoticonButton.setImage(UIImage(contentsOfFile: pngPath), forState: UIControlState.Normal) } else { // 防止cell复用 emoticonButton.setImage(nil, forState: UIControlState.Normal) } // 2. 设置显示emoji表情 emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal) // if let emoji = emoticon?.emoji { // emoticonButton.setTitle(emoji, forState: UIControlState.Normal) // } else { // emoticonButton.setTitle(nil, forState: UIControlState.Normal) // } // 3. 判断是否是删除按钮模型,是的话,显示删除按钮 if emoticon!.removeEmoticon { // 是删除按钮 emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal) } } } // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) // print("frame:\(frame)") prepareUI() } // MARK: - 准备UI private func prepareUI() { // 添加子控件 contentView.addSubview(emoticonButton) // 设置frame emoticonButton.frame = CGRectInset(bounds, 4, 4) // 此处必须使用bounds,因为emotionButton相对于当前contentView的内部偏移 // 设置title大小,为了使emoji表情,和图片表情一样大,emoji本身是文字 emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32) // 32是图片表情的大小 // 禁止按钮可以点击 emoticonButton.userInteractionEnabled = false } // MARK: - 懒加载 /// 表情按钮 private lazy var emoticonButton: UIButton = UIButton() } // MARK: - 继承流水布局 /// 在collectionView布局之前设置layout的参数 class CZCollectionViewFlowLayout: UICollectionViewFlowLayout { // 重写 prepareLayout override func prepareLayout() { super.prepareLayout() // item 宽度 let width = collectionView!.bounds.width / 7.0 // item 高度 let height = collectionView!.bounds.height / 3.0 // 设置layout 的 itemSize itemSize = CGSize(width: width, height: height) // 滚动方向 scrollDirection = UICollectionViewScrollDirection.Horizontal // 间距 minimumInteritemSpacing = 0 minimumLineSpacing = 0 // 取消弹簧效果 collectionView?.bounces = false // 取消滚动指示器 collectionView?.showsHorizontalScrollIndicator = false // 分页显示 collectionView?.pagingEnabled = true } }
apache-2.0
f811c711cc07517c466aec2836f19b28
34.426573
175
0.616561
5.053367
false
false
false
false
ZhiQiang-Yang/pppt
v2exProject 2/Pods/Alamofire/Source/ServerTrustPolicy.swift
239
13428
// ServerTrustPolicy.swift // // Copyright (c) 2014–2015 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 /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. - parameter policies: A dictionary of all policies mapped to a particular host. - returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. By default, this method will return the policy that perfectly matches the given host. Subclasses could override this method and implement more complex mapping implementations such as wildcards. - parameter host: The host to use when searching for a matching policy. - returns: The server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. Applications are encouraged to always validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. By validating both the certificate chain and host, certificate pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. By validating both the certificate chain and host, public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `.cer` files. - returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] for path in bundle.pathsForResourcesOfType(".cer", inDirectory: nil) { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `*.cer` files. - returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. - parameter serverTrust: The server trust to evaluate. - parameter host: The host of the challenge protection space. - returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) //====================================================================================================== // The following `[] +` is a temporary workaround for a Swift 2.0 compiler error. This workaround should // be removed once the following radar has been resolved: // - http://openradar.appspot.com/radar?id=6082025006039040 //====================================================================================================== let pinnedCertificatesDataArray = certificateDataForCertificates([] + pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, [policy]) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType(kSecTrustResultInvalid) let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType(kSecTrustResultUnspecified) let proceed = SecTrustResultType(kSecTrustResultProceed) isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0) as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
apache-2.0
3bb83010963d6a9e1ec57c0f53928c58
43.019672
121
0.650231
6.172874
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/ActiveStateComputation.swift
1
3923
/// # Backgrounding and ML /// Our ML algorithms use the GPU and can cause crashes when we run them in the background. Thus, we track the app's /// backgrounding state and stop any tasks before the app reaches the background. /// /// # Correctness criteria /// We have three different functions: `async`, `willResignActive`, and `didBecomeActive` that all run on the main dispatch /// queue. In terms of ordering constraints: /// - The system enforces state transitions such that each time you resign active it'll be paired with a `didBecomeActive` call /// and vice versa. /// /// Given this constraint, you can expect a few different interleavings /// - async, resign, become /// - async, become, resign /// - become, async, resign /// - become, resign, async /// - resign, async, become /// - resign, become, async /// /// In general, we maintain two states: the system's notion of our app's application state and our own notion of active that is a /// subset of the more general active system state. In other words, if our app is inactive then our own internal `isActive` is /// always false, but if the app is active our internal `isActive` may be false or it may be true. However, if it is `false` /// we know that we'll get a become event soon. /// /// Our correctness criterai is that our work items run iff the app is in the active state and each of them runs to completion /// in the same order that they were posted (same semantics as a serial dispatch queue). /// /// The only time that computation can run is in between calls to `become` and `resign` because of our internal `isActive` variable. /// After the system calls resign, then all work items are added to the `pendingComputations` list in order, which are then posted to the `queue` in order on the `become` call before releasing the main queue. Subsequent calls to `async` will post to the `queue` but /// because the posting happens in the main queue, we can ensure correct execution ordering. import Foundation import UIKit class ActiveStateComputation { let queue: DispatchQueue var pendingComputations: [() -> Void] = [] var isActive = false init( label: String ) { self.queue = DispatchQueue(label: "ActiveStateComputation \(label)") DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.isActive = UIApplication.shared.applicationState == .active // We don't need to unregister these functions because the system will clean // them up for us NotificationCenter.default.addObserver( self, selector: #selector(self.willResignActive), name: UIApplication.willResignActiveNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil ) } } func async(execute work: @escaping () -> Void) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } let state = UIApplication.shared.applicationState guard state == .active, self.isActive else { self.pendingComputations.append(work) return } self.queue.async { work() } } } @objc func willResignActive() { assert(UIApplication.shared.applicationState == .active) assert(Thread.isMainThread) isActive = false queue.sync {} } @objc func didBecomeActive() { assert(UIApplication.shared.applicationState == .active) assert(Thread.isMainThread) isActive = true for work in pendingComputations { queue.async { work() } } } }
mit
ac8da140bfef30ab938124780b3d744d
42.10989
265
0.654091
4.755152
false
false
false
false
Dan2552/Luncheon
Example/Tests/LocalTests.swift
1
1460
// // Local.swift // Luncheon // // Created by Dan on 01/08/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Quick import Nimble import Luncheon class LocalSpec: QuickSpec { override func spec() { let subject = TestSubject() let local = subject.local describe("attributes") { it("contains properties defined in the model") { expect(local.attributes().keys).to(contain("stringProperty")) expect(local.attributes().keys).to(contain("numberProperty")) } it("has the values of the properties") { subject.stringProperty = "string property value" let attributes = local.attributes() let stringPropertyValue = attributes["stringProperty"] as! String expect(stringPropertyValue).to(equal("string property value")) } it("should not contain changedAttributes") { expect(local.attributes().keys).toNot(contain("changedAttributes")) } } describe("assignAttributes") { it("sets many property values using a dictionary") { let newValues = [ "string_property": "a1", "number_property": 5 ] as [String : Any] local.assignAttributes(newValues) expect(subject.stringProperty).to(equal("a1")) expect(subject.numberProperty).to(equal(5)) } } }}
mit
9c154aed6fc71eabe202228e5e6a3196
30.042553
79
0.587389
4.602524
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/Views/ZSMyCell.swift
1
6221
// // ZSMyCell.swift // zhuishushenqi // // Created by yung on 2018/10/20. // Copyright © 2018年 QS. All rights reserved. // import UIKit class ZSRLMyCell: UITableViewCell { var customView:UIView? { didSet { layoutSubviews() } } var rightLabel:UILabel! var rightTitle:String = "" { didSet { rightLabel.text = rightTitle let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightLabel.frame = CGRect(x: self.bounds.width - width - 40, y: self.bounds.height/2 - 15 , width: width, height: 30) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) rightLabel = UILabel(frame: CGRect.zero) rightLabel.font = UIFont.systemFont(ofSize: 13) rightLabel.textColor = UIColor.red rightLabel.textAlignment = .center self.accessoryType = .disclosureIndicator contentView.addSubview(self.rightLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 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 } override func layoutSubviews() { super.layoutSubviews() if let customView = self.customView { rightLabel.isHidden = true customView.frame = CGRect(x: self.bounds.width - customView.bounds.width - 40, y: self.bounds.height/2 - customView.bounds.height/2, width: customView.bounds.width, height: customView.bounds.height) if let _ = customView.superview { customView.removeFromSuperview() } contentView.addSubview(customView) } else { let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightLabel.frame = CGRect(x: self.bounds.width - width - 40, y: self.bounds.height/2 - 15 , width: width, height: 30) rightLabel.isHidden = false } } } class ZSRTMyCell: UITableViewCell { lazy var rightButton:UIButton = { let button = UIButton(type: .custom) button.layer.borderColor = UIColor.red.cgColor button.layer.borderWidth = 1 button.setTitleColor(UIColor.red, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 13) return button }() var rightTitle:String = "" { didSet { rightButton.setTitle(rightTitle, for: .normal) let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightButton.frame = CGRect(x: self.bounds.width - width - 40, y: self.bounds.height/2 - 15 , width: width, height: 30) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.accessoryType = .disclosureIndicator contentView.addSubview(self.rightButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func layoutSubviews() { super.layoutSubviews() let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightButton.frame = CGRect(x: self.bounds.width - width - 20 - 40, y: self.bounds.height/2 - 13 , width: width + 20, height: 26) rightButton.layer.cornerRadius = 5 } } class ZSRLTMyCell: ZSRTMyCell { private var rightLabel:UILabel! var rightLabelTitle:String = "" { didSet { rightLabel.text = self.rightLabelTitle let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightLabel.frame = CGRect(x: self.bounds.width - width - 40, y: self.bounds.height/2 - 15 , width: width, height: 30) } } override var rightTitle:String { didSet { rightButton.setTitle(rightTitle, for: .normal) let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightButton.frame = CGRect(x: self.bounds.width - width - 20, y: self.bounds.height/2 - 15 , width: width, height: 30) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) rightLabel = UILabel(frame: CGRect.zero) rightLabel.font = UIFont.systemFont(ofSize: 13) rightLabel.textColor = UIColor.gray rightLabel.textAlignment = .center self.accessoryType = .none contentView.addSubview(self.rightLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func layoutSubviews() { super.layoutSubviews() let width = rightTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightButton.frame = CGRect(x: self.bounds.width - width - 20 - 20, y: self.bounds.height/2 - 13 , width: width + 20, height: 26) rightButton.layer.cornerRadius = 5 let labelWidth = rightLabelTitle.qs_width(UIFont.systemFont(ofSize: 13), height: 30) rightLabel.frame = CGRect(x: rightButton.frame.minX - labelWidth - 10, y: self.bounds.height/2 - 15 , width: labelWidth, height: 30) } }
mit
fd7b7ae042f173d0c10b4fe97c0e660a
33.932584
210
0.620296
4.528769
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Model/WBReceipt+Query.swift
1
1500
// // WBReceipt+Query.swift // SmartReceipts // // Created by Jaanus Siim on 01/06/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation extension WBReceipt { class func selectAllQueryForTrip(_ trip: WBTrip?) -> DatabaseQueryBuilder { return self.selectAllQueryForTrip(trip, isAscending: false) } class func selectAllQueryForTrip(_ trip: WBTrip?, isAscending: Bool) -> DatabaseQueryBuilder { let receiptIdFullName = "\(ReceiptsTable.Name).\(ReceiptsTable.Column.Id)" let receiptIdAsName = "\(ReceiptsTable.Name)_\(ReceiptsTable.Column.Id)" let paymentMethodIdFullName = "\(PaymentMethodsTable.Name).\(PaymentMethodsTable.Column.Id)" let paymentMethodIdAsName = "\(PaymentMethodsTable.Name)_\(PaymentMethodsTable.Column.Id)" let selectAll = DatabaseQueryBuilder.selectAllStatement(forTable: ReceiptsTable.Name) if let trip = trip { selectAll?.`where`(ReceiptsTable.Column.Parent, value: trip.name as NSObject!) } selectAll?.select(receiptIdFullName, as: receiptIdAsName) selectAll?.select(paymentMethodIdFullName, as: paymentMethodIdAsName) selectAll?.leftJoin(PaymentMethodsTable.Name, on: ReceiptsTable.Column.PaymentMethodId as NSObject!, equalTo: PaymentMethodsTable.Column.Id as NSObject!) selectAll?.order(by: ReceiptsTable.Column.Date, ascending: isAscending) return selectAll! } }
agpl-3.0
e34606bc9341cc360f17a7d8a6606c00
39.513514
161
0.699133
4.584098
false
false
false
false
coodly/SlimTimerAPI
Sources/NetworkRequest.swift
1
5797
/* * Copyright 2017 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import SWXMLHash internal enum Method: String { case POST case GET case PUT case DELETE } public enum SlimTimerError: Error { case noData case network(Error) case server(String) case unknown } private let ServerErrorRange = IndexSet(integersIn: 500..<600) internal struct NetworkResult<T: RemoteModel> { var value: T? let statusCode: Int let error: SlimTimerError? } private extension DateFormatter { static let paramDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() } private let ServerAPIURLString = "http://slimtimer.com" private typealias Dependencies = FetchConsumer & AccessTokenConsumer & APIKeyConsumer internal class NetworkRequest<Model: RemoteModel>: Dependencies { var fetch: NetworkFetch! var apiKey: String! var accessToken: String! final func execute() { performRequest() } func GET(_ path: String, params: [String: AnyObject]? = nil) { executeMethod(.GET, path: path, body: nil, params: params) } func POST(_ path: String, body: RequestBody) { executeMethod(.POST, path: path, body: body) } func PUT(_ path: String, body: RequestBody) { executeMethod(.PUT, path: path, body: body) } func DELETE(_ path: String) { executeMethod(.DELETE, path: path, body: nil) } internal func executeMethod(_ method: Method, path: String, body: RequestBody?, params: [String: AnyObject]? = nil) { if var consumer = body as? APIKeyConsumer { consumer.apiKey = apiKey } var components = URLComponents(url: URL(string: ServerAPIURLString)!, resolvingAgainstBaseURL: true)! components.path = components.path + path var queryItems = [URLQueryItem]() if self is AuthenticatedRequest { queryItems.append(URLQueryItem(name: "api_key", value: apiKey)) queryItems.append(URLQueryItem(name: "access_token", value: accessToken)) } for (key, value) in params ?? [:] { if let number = value as? Int { let used = String(describing: number) queryItems.append(URLQueryItem(name: key, value: used)) } else if let date = value as? Date { let dateString = DateFormatter.paramDateFormatter.string(from: date) queryItems.append(URLQueryItem(name: key, value: dateString)) } else if let string = value as? String { queryItems.append(URLQueryItem(name: key, value: string)) } } components.queryItems = queryItems let requestURL = components.url! let request = NSMutableURLRequest(url: requestURL) request.httpShouldHandleCookies = false request.httpMethod = method.rawValue Logging.log("\(method) to \(requestURL.absoluteString)") request.addValue("application/xml", forHTTPHeaderField: "Accept") if let string = body?.generate(), let data = string.data(using: .utf8) { request.httpBody = data request.addValue("application/xml", forHTTPHeaderField: "Content-Type") Logging.log("Body\n\(string)") } fetch.fetch(request: request as URLRequest) { data, response, networkError in let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1 Logging.log("Status code: \(statusCode)") if let data = data, let string = String(data: data, encoding: .utf8) { Logging.log("Response:\n\(string)") } var value: Model? var error: SlimTimerError? defer { self.handle(result: NetworkResult(value: value, statusCode: statusCode, error: error)) } if let remoteError = networkError { error = .network(remoteError) return } if Model.self is EmptySuccessResponse.Type, statusCode == 200 { value = EmptySuccessResponse() as? Model return } guard let data = data else { error = .noData return } let xml = SWXMLHash.parse(data) if let errorMessage = xml.errorMessage { error = .server(errorMessage) return } if ServerErrorRange.contains(statusCode) { error = .server("Status code \(statusCode)") return } if let model = Model(xml: xml) { value = model } else { error = .noData } } } func handle(result: NetworkResult<Model>) { Logging.log("Handle \(result)") } func performRequest() { fatalError("Override \(#function)") } }
apache-2.0
444738ef9547734b577de2036a1a0dec
30.335135
121
0.57961
4.937819
false
false
false
false
dunkelstern/unchained
Unchained/responseClasses/template_response.swift
1
1902
// // template_response.swift // unchained // // Created by Johannes Schriewer on 13/12/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // import TwoHundred import Stencil import PathKit /// Template response, fills a Stencil template with content public class TemplateResponse: HTTPResponseBase { /// Init with template and context /// /// - parameter template: relative path to template from configured template base dir /// - parameter context: template context to render /// - parameter request: HTTPRequest for which to render the response /// - parameter statusCode: (optional) HTTP Status code to send (defaults to `200 Ok`) /// - parameter headers: (optional) additional headers to send /// - parameter contentType: (optional) content type to send (defaults to `text/html`) public init(_ template: String, context: [String:Any], request: HTTPRequest, statusCode: HTTPStatusCode = .Ok, headers: [HTTPHeader]? = nil, contentType: String = "text/html") { super.init() self.statusCode = statusCode if let headers = headers { self.headers.appendContentsOf(headers) } self.headers.append(HTTPHeader("Content-Type", contentType)) let templatePath = request.config.templateDirectory + "/\(template)" do { let t = try Template(path: Path(templatePath)) do { let body = try t.render(Context(dictionary: context), namespace: nil) self.body.append(.StringData(body)) } catch let error as TemplateSyntaxError { self.statusCode = .InternalServerError self.body = [.StringData(error.description)] } } catch { self.statusCode = .InternalServerError self.body = [.StringData("Template not found")] } } }
bsd-3-clause
be367e3f2a92c8fe07254a6b76db701a
37.816327
181
0.638085
4.824873
false
false
false
false
sdgandhi/AudioPlayer
AudioPlayer/AudioPlayer/AudioPlayer.swift
1
34272
// // AudioPlayer.swift // AudioPlayer // // Created by Kevin DELANNOY on 26/04/15. // Copyright (c) 2015 Kevin Delannoy. All rights reserved. // import UIKit import MediaPlayer import AVFoundation private class ClosureContainer: NSObject { let closure: (sender: AnyObject) -> () init(closure: (sender: AnyObject) -> ()) { self.closure = closure } @objc func callSelectorOnTarget(sender: AnyObject) { closure(sender: sender) } } // MARK: - AudioPlayerState /** `AudioPlayerState` defines 4 state an `AudioPlayer` instance can be in. - `Buffering`: Represents that the player is buffering data before playing them. - `Playing`: Represents that the player is playing. - `Paused`: Represents that the player is paused. - `Stopped`: Represents that the player is stopped. - `WaitingForConnection`: Represents the state where the player is waiting for internet connection. */ public enum AudioPlayerState { case Buffering case Playing case Paused case Stopped case WaitingForConnection } // MARK: - AudioPlayerMode public struct AudioPlayerModeMask: OptionSetType { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static var Shuffle: AudioPlayerModeMask { return self.init(rawValue: 0b001) } public static var Repeat: AudioPlayerModeMask { return self.init(rawValue: 0b010) } public static var RepeatAll: AudioPlayerModeMask { return self.init(rawValue: 0b100) } } // MARK: - AVPlayer+KVO private extension AVPlayer { static var ap_KVOItems: [String] { return [ "currentItem.playbackBufferEmpty", "currentItem.playbackLikelyToKeepUp", "currentItem.duration" ] } } // MARK: - NSObject+Observation private extension NSObject { func observe(name: String, selector: Selector, object: AnyObject? = nil) { NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: object) } func unobserve(name: String, object: AnyObject? = nil) { NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: object) } } // MARK: - Array+Shuffe private extension Array { func shuffled() -> [Element] { return sort { e1, e2 in random() % 2 == 0 } } } // MARK: - AudioPlayerDelegate public protocol AudioPlayerDelegate: NSObjectProtocol { func audioPlayer(audioPlayer: AudioPlayer, didChangeStateFrom from: AudioPlayerState, toState to: AudioPlayerState) func audioPlayer(audioPlayer: AudioPlayer, willStartPlayingItem item: AudioItem) func audioPlayer(audioPlayer: AudioPlayer, didUpdateProgressionToTime time: NSTimeInterval, percentageRead: Float) func audioPlayer(audioPlayer: AudioPlayer, didFindDuration duration: NSTimeInterval, forItem item: AudioItem) } // MARK: - AudioPlayer /** An `AudioPlayer` instance is used to play `AudioPlayerItem`. It's an easy to use AVPlayer with simple methods to handle the whole playing audio process. You can get events (such as state change or time observation) by registering a delegate. */ public class AudioPlayer: NSObject { // MARK: Initialization public override init() { state = .Buffering super.init() observe(ReachabilityChangedNotification, selector: "reachabilityStatusChanged:", object: reachability) reachability.startNotifier() } deinit { reachability.stopNotifier() unobserve(ReachabilityChangedNotification, object: reachability) qualityAdjustmentTimer?.invalidate() qualityAdjustmentTimer = nil retryTimer?.invalidate() retryTimer = nil stop() endBackgroundTask() } // MARK: Private properties /// The audio player. private var player: AVPlayer? { didSet { //Gotta unobserver & observe if necessary for keyPath in AVPlayer.ap_KVOItems { oldValue?.removeObserver(self, forKeyPath: keyPath) player?.addObserver(self, forKeyPath: keyPath, options: .New, context: nil) } if let oldValue = oldValue { qualityAdjustmentTimer?.invalidate() qualityAdjustmentTimer = nil if let timeObserver = timeObserver { oldValue.removeTimeObserver(timeObserver) } timeObserver = nil unobserve(AVAudioSessionInterruptionNotification) unobserve(AVAudioSessionRouteChangeNotification) unobserve(AVAudioSessionMediaServicesWereLostNotification) unobserve(AVAudioSessionMediaServicesWereResetNotification) unobserve(AVPlayerItemDidPlayToEndTimeNotification) } if let player = player { //Creating the qualityAdjustment timer let target = ClosureContainer(closure: { [weak self] sender in self?.adjustQualityIfNecessary() }) let timer = NSTimer(timeInterval: adjustQualityTimeInternal, target: target, selector: "callSelectorOnTarget:", userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) qualityAdjustmentTimer = timer timeObserver = player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 2), queue: dispatch_get_main_queue(), usingBlock: {[weak self] time in self?.currentProgressionUpdated(time) }) observe(AVAudioSessionInterruptionNotification, selector: "audioSessionGotInterrupted:") observe(AVAudioSessionRouteChangeNotification, selector: "audioSessionRouteChanged:") observe(AVAudioSessionMediaServicesWereLostNotification, selector: "audioSessionMessedUp:") observe(AVAudioSessionMediaServicesWereResetNotification, selector: "audioSessionMessedUp:") observe(AVPlayerItemDidPlayToEndTimeNotification, selector: "playerItemDidEnd:") } } } private typealias AudioQueueItem = (position: Int, item: AudioItem) /// The queue containing items to play. private var enqueuedItems: [AudioQueueItem]? /// A boolean value indicating whether the player has been paused because of a system interruption. private var pausedForInterruption = false /// The time observer private var timeObserver: AnyObject? /// The number of interruption since last quality adjustment/begin playing private var interruptionCount = 0 { didSet { if adjustQualityAutomatically && interruptionCount > adjustQualityAfterInterruptionCount { adjustQualityIfNecessary() } } } /// A boolean value indicating if quality is being changed. It's necessary for the interruption count to not be incremented while new quality is buffering. private var qualityIsBeingChanged = false /// The current number of retry we already tried private var retryCount = 0 /// The timer used to cancel a retry and make a new one private var retryTimer: NSTimer? /// The timer used to adjust quality private var qualityAdjustmentTimer: NSTimer? /// The state of the player when the connection was lost private var stateWhenConnectionLost: AudioPlayerState? /// The date of the connection loss private var connectionLossDate: NSDate? /// The index of the current item in the queue private var currentItemIndexInQueue: Int? /// Reachability for network connection private let reachability = Reachability.reachabilityForInternetConnection() // MARK: Readonly properties /// The current state of the player. public private(set) var state: AudioPlayerState { didSet { if state != oldValue { delegate?.audioPlayer(self, didChangeStateFrom: oldValue, toState: state) } } } /// The current item being played. public private(set) var currentItem: AudioItem? { didSet { for keyPath in AudioItem.ap_KVOItems { oldValue?.removeObserver(self, forKeyPath: keyPath) currentItem?.addObserver(self, forKeyPath: keyPath, options: .New, context: nil) } if let currentItem = currentItem { do { try AVAudioSession.sharedInstance().setActive(true) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch { } player?.pause() player = nil state = .Stopped let URLInfo: AudioItemURL = { switch (self.currentQuality ?? self.defaultQuality) { case .High: return currentItem.highestQualityURL case .Medium: return currentItem.mediumQualityURL default: return currentItem.lowestQualityURL } }() if reachability.isReachable() || URLInfo.URL.fileURL { state = .Buffering } else { connectionLossDate = nil stateWhenConnectionLost = .Buffering state = .WaitingForConnection return } state = .Buffering player = AVPlayer(URL: URLInfo.URL) player?.rate = rate player?.volume = volume currentQuality = URLInfo.quality player?.play() updateNowPlayingInfoCenter() if oldValue != currentItem { delegate?.audioPlayer(self, willStartPlayingItem: currentItem) } } else { if let _ = oldValue { stop() } } } } /// The current item duration or nil if no item or unknown duration. public var currentItemDuration: NSTimeInterval? { if let currentItem = player?.currentItem { let seconds = CMTimeGetSeconds(currentItem.duration) if !isnan(seconds) { return NSTimeInterval(seconds) } } return nil } /// The current item progression or nil if no item. public var currentItemProgression: NSTimeInterval? { if let currentItem = player?.currentItem { let seconds = CMTimeGetSeconds(currentItem.currentTime()) if !isnan(seconds) { return NSTimeInterval(seconds) } } return nil } /// The current quality being played. public private(set) var currentQuality: AudioQuality? /// MARK: Public properties /// The maximum number of interruption before putting the player to Stopped mode. Default value is 10. public var maximumRetryCount = 10 /// The delay to wait before cancelling last retry and retrying. Default value is 10seconds. public var retryTimeout = NSTimeInterval(10) /// Defines whether the player should resume after a system interruption or not. Default value is `true`. public var resumeAfterInterruption = true /// Defines whether the player should resume after a connection loss or not. Default value is `true`. public var resumeAfterConnectionLoss = true /// Defines the maximum to wait after a connection loss before putting the player to Stopped mode and cancelling the resume. Default value is 60seconds. public var maximumConnectionLossTime = NSTimeInterval(60) /// Defines whether the player should automatically adjust sound quality based on the number of interruption before a delay and the maximum number of interruption whithin this delay. Default value is `true`. public var adjustQualityAutomatically = true /// Defines the default quality used to play. Default value is `.Medium` public var defaultQuality = AudioQuality.Medium /// Defines the delay within which the player wait for an interruption before upgrading the quality. Default value is 10minutes. public var adjustQualityTimeInternal = NSTimeInterval(10 * 60) /// Defines the maximum number of interruption to have within the `adjustQualityTimeInterval` delay before downgrading the quality. Default value is 3. public var adjustQualityAfterInterruptionCount = 3 /// Defines the mode of the player. Default is `.Normal`. public var mode: AudioPlayerModeMask = [] { didSet { adaptQueueToPlayerMode() } } /// Defines the rate of the player. Default value is 1. public var rate = Float(1) { didSet { player?.rate = rate updateNowPlayingInfoCenter() } } /// Defines the volume of the player. `1.0` means 100% and `0.0` is 0%. public var volume = Float(1) { didSet { player?.volume = volume } } /// Defines the rate multiplier of the player when the backward/forward buttons are pressed. Default value is 2. public var rateMultiplerOnSeeking = Float(2) /// The delegate that will be called upon special events public weak var delegate: AudioPlayerDelegate? /// MARK: Public handy functions /** Play an item. - parameter item: The item to play. */ public func playItem(item: AudioItem) { playItems([item]) } /** Plays the first item in `items` and enqueud the rest. - parameter items: The items to play. */ public func playItems(items: [AudioItem], startAtIndex index: Int = 0) { if items.count > 0 { var idx = 0 enqueuedItems = items.map { (position: idx++, item: $0) } adaptQueueToPlayerMode() let startIndex: Int = { (index >= items.count || index < 0) ? 0 : index }() currentItem = enqueuedItems?[startIndex].item currentItemIndexInQueue = startIndex } else { stop() enqueuedItems = nil currentItemIndexInQueue = nil } } /** Adds an item at the end of the queue. If queue is empty and player isn't playing, the behaviour will be similar to `playItem(item: item)`. - parameter item: The item to add. */ public func addItemToQueue(item: AudioItem) { addItemsToQueue([item]) } /** Adds items at the end of the queue. If the queue is empty and player isn't playing, the behaviour will be similar to `playItems(items: items)`. - parameter items: The items to add. */ public func addItemsToQueue(items: [AudioItem]) { if currentItem != nil { var idx = 0 enqueuedItems = (enqueuedItems ?? []) + items.map { (position: idx++, item: $0) } adaptQueueToPlayerMode() } else { playItems(items) } } public func removeItemAtIndex(index: Int) { assert(enqueuedItems != nil, "cannot remove an item when queue is nil") assert(index >= 0, "cannot remove an item at negative index") assert(index < enqueuedItems?.count, "cannot remove an item at an index > queue.count") if let enqueuedItems = enqueuedItems { if index >= 0 && index < enqueuedItems.count { self.enqueuedItems?.removeAtIndex(index) } } } /** Resume the player. */ public func resume() { player?.play() state = .Playing } /** Pauses the player. */ public func pause() { player?.pause() state = .Paused } /** Stops the player and clear the queue. */ public func stop() { //Stopping player immediately player?.pause() state = .Stopped enqueuedItems = nil currentItem = nil player = nil } /** Plays next item in the queue. */ public func next() { if let currentItemIndexInQueue = currentItemIndexInQueue where hasNext() { //The background task will end when the player will have enough data to play beginBackgroundTask() pause() let newIndex = currentItemIndexInQueue + 1 if newIndex < enqueuedItems?.count { self.currentItemIndexInQueue = newIndex currentItem = enqueuedItems?[newIndex].item } else if mode.intersect(.RepeatAll) != [] { self.currentItemIndexInQueue = 0 currentItem = enqueuedItems?.first?.item } } } /** Returns whether there is a next item in the queue or not. - returns: A boolean value indicating whether there is a next item to play or not. */ public func hasNext() -> Bool { if let enqueuedItems = enqueuedItems, currentItemIndexInQueue = currentItemIndexInQueue { if currentItemIndexInQueue + 1 < enqueuedItems.count || mode.intersect(.RepeatAll) != [] { return true } } return false } /** Plays previous item in the queue. */ public func previous() { if let currentItemIndexInQueue = currentItemIndexInQueue, enqueuedItems = enqueuedItems { let newIndex = currentItemIndexInQueue - 1 if newIndex >= 0 { self.currentItemIndexInQueue = newIndex currentItem = enqueuedItems[newIndex].item } else if mode.intersect(.RepeatAll) != [] { self.currentItemIndexInQueue = enqueuedItems.count - 1 currentItem = enqueuedItems.last?.item } } } /** Seeks to a specific time. - parameter time: The time to seek to. */ public func seekToTime(time: NSTimeInterval) { player?.seekToTime(CMTimeMake(Int64(time), 1)) updateNowPlayingInfoCenter() } /** Handle events received from Control Center/Lock screen/Other in UIApplicationDelegate. - parameter event: The event received. */ public func remoteControlReceivedWithEvent(event: UIEvent) { if event.type == .RemoteControl { //ControlCenter Or Lock screen switch event.subtype { case .RemoteControlBeginSeekingBackward: rate = -(rate * rateMultiplerOnSeeking) case .RemoteControlBeginSeekingForward: rate = rate * rateMultiplerOnSeeking case .RemoteControlEndSeekingBackward: rate = -(rate / rateMultiplerOnSeeking) case .RemoteControlEndSeekingForward: rate = rate / rateMultiplerOnSeeking case .RemoteControlNextTrack: next() case .RemoteControlPause: pause() case .RemoteControlPlay: resume() case .RemoteControlPreviousTrack: previous() case .RemoteControlStop: stop() case .RemoteControlTogglePlayPause: if state == .Playing { pause() } else { resume() } default: break } } } // MARK: MPNowPlayingInfoCenter /** Updates the MPNowPlayingInfoCenter with current item's info. */ private func updateNowPlayingInfoCenter() { if let currentItem = currentItem { var info = [String: AnyObject]() if let title = currentItem.title { info[MPMediaItemPropertyTitle] = title } if let artist = currentItem.artist { info[MPMediaItemPropertyArtist] = artist } if let album = currentItem.album { info[MPMediaItemPropertyAlbumTitle] = album } if let trackCount = currentItem.trackCount { info[MPMediaItemPropertyAlbumTrackCount] = trackCount } if let trackNumber = currentItem.trackNumber { info[MPMediaItemPropertyAlbumTrackNumber] = trackNumber } if let artwork = currentItem.artworkImage { info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: artwork) } if let duration = currentItemDuration { info[MPMediaItemPropertyPlaybackDuration] = duration } if let progression = currentItemProgression { info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = progression } info[MPNowPlayingInfoPropertyPlaybackRate] = rate MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = info } else { MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = nil } } // MARK: Events public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let keyPath = keyPath, object = object as? NSObject { if let player = player where object == player { switch keyPath { case "currentItem.duration": //Duration is available updateNowPlayingInfoCenter() if let currentItem = currentItem, currentItemDuration = currentItemDuration where currentItemDuration > 0 { delegate?.audioPlayer(self, didFindDuration: currentItemDuration, forItem: currentItem) } case "currentItem.playbackBufferEmpty": //The buffer is empty and player is loading if state == .Playing && !qualityIsBeingChanged { interruptionCount++ } state = .Buffering beginBackgroundTask() case "currentItem.playbackLikelyToKeepUp": if let playbackLikelyToKeepUp = player.currentItem?.playbackLikelyToKeepUp where playbackLikelyToKeepUp { //There is enough data in the buffer if !pausedForInterruption && state != .Paused && (stateWhenConnectionLost == nil || stateWhenConnectionLost != .Paused) { state = .Playing player.play() } else { state = .Paused } retryCount = 0 //We cancel the retry we might have asked for retryTimer?.invalidate() retryTimer = nil endBackgroundTask() } default: break } } else if let currentItem = currentItem where object == currentItem { updateNowPlayingInfoCenter() } } } /** Audio session got interrupted by the system (call, Siri, ...). If interruption begins, we should ensure the audio pauses and if it ends, we should restart playing if state was `.Playing` before. - parameter note: The notification information. */ @objc private func audioSessionGotInterrupted(note: NSNotification) { if let typeInt = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, type = AVAudioSessionInterruptionType(rawValue: typeInt) { if type == .Began && (state == .Playing || state == .Buffering) { //We pause the player when an interruption is detected pausedForInterruption = true pause() } else { //We resume the player when the interruption is ended and we paused it in this interruption if let optionInt = note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt { let options = AVAudioSessionInterruptionOptions(rawValue: optionInt) if (options.intersect(.ShouldResume)) != [] && pausedForInterruption { if resumeAfterInterruption { resume() } pausedForInterruption = false } } } } } /** Audio session route changed (ex: earbuds plugged in/out). This can change the player state, so we just adapt it. - parameter note: The notification information. */ @objc private func audioSessionRouteChanged(note: NSNotification) { if let player = player where player.rate == 0 { state = .Paused } } /** Audio session got messed up (media services lost or reset). We gotta reactive the audio session and reset player. - parameter note: The notification information. */ @objc private func audioSessionMessedUp(note: NSNotification) { //We reenable the audio session directly in case we're in background do { try AVAudioSession.sharedInstance().setActive(true) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch {} //Aaaaand we: restart playing/go to next state = .Stopped interruptionCount++ retryOrPlayNext() } /** Playing item did end. We can play next or stop the player if queue is empty. - parameter note: The notification information. */ @objc private func playerItemDidEnd(note: NSNotification) { if let sender = note.object as? AVPlayerItem, currentItem = player?.currentItem where sender == currentItem { nextOrStop() } } @objc private func reachabilityStatusChanged(note: NSNotification) { if state == .WaitingForConnection { if let connectionLossDate = connectionLossDate where reachability.isReachable() { if let stateWhenConnectionLost = stateWhenConnectionLost where stateWhenConnectionLost != .Stopped { if fabs(connectionLossDate.timeIntervalSinceNow) < maximumConnectionLossTime { retryOrPlayNext() } } self.connectionLossDate = nil } } else if state != .Stopped && state != .Paused { if reachability.isReachable() { retryOrPlayNext() connectionLossDate = nil stateWhenConnectionLost = nil } else { connectionLossDate = NSDate() stateWhenConnectionLost = state state = .WaitingForConnection } } } /** The current progression was updated. When playing, this method gets called very often so we should consider doing as little work as possible in here. - parameter time: The current time. */ private func currentProgressionUpdated(time: CMTime) { if let currentItemProgression = currentItemProgression, currentItemDuration = currentItemDuration where currentItemDuration > 0 { //If the current progression is updated, it means we are playing. This fixes the behavior where sometimes //the `playbackLikelyToKeepUp` isn't changed even though it's playing (the first play). if state != .Playing { if !pausedForInterruption && state != .Paused && (stateWhenConnectionLost == nil || stateWhenConnectionLost != .Paused) { state = .Playing player?.play() } else { state = .Paused } endBackgroundTask() } //Then we can call the didUpdateProgressionToTime: delegate method let percentage = Float(currentItemProgression / currentItemDuration) * 100 delegate?.audioPlayer(self, didUpdateProgressionToTime: currentItemProgression, percentageRead: percentage) } } // MARK: Retrying /** This will retry to play current item and seek back at the correct position if possible (or enabled). If not, it'll just play the next item in queue. */ private func retryOrPlayNext() { if state == .Playing { return } if maximumRetryCount > 0 { if retryCount < maximumRetryCount { //We can retry let cip = currentItemProgression let ci = currentItem currentItem = ci if let cip = cip { seekToTime(cip) } retryCount++ //We gonna cancel this current retry and create a new one if the player isn't playing after a certain delay let target = ClosureContainer(closure: { [weak self] sender in self?.retryOrPlayNext() }) let timer = NSTimer(timeInterval: retryTimeout, target: target, selector: "callSelectorOnTarget:", userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) retryTimer = timer return } else { retryCount = 0 } } nextOrStop() } private func nextOrStop() { if mode.intersect(.Repeat) != [] { seekToTime(0) resume() } else if hasNext() { next() } else { stop() } } // MARK: Quality adjustment /** Adjusts quality if necessary based on interruption count. */ private func adjustQualityIfNecessary() { if let currentQuality = currentQuality where adjustQualityAutomatically { if interruptionCount >= adjustQualityAfterInterruptionCount { //Decreasing audio quality let URLInfo: AudioItemURL? = { if currentQuality == .High { return self.currentItem?.mediumQualityURL } if currentQuality == .Medium { return self.currentItem?.lowestQualityURL } return nil }() if let URLInfo = URLInfo where URLInfo.quality != currentQuality { let cip = currentItemProgression let item = AVPlayerItem(URL: URLInfo.URL) qualityIsBeingChanged = true player?.replaceCurrentItemWithPlayerItem(item) if let cip = cip { seekToTime(cip) } qualityIsBeingChanged = false self.currentQuality = URLInfo.quality } } else if interruptionCount == 0 { //Increasing audio quality let URLInfo: AudioItemURL? = { if currentQuality == .Low { return self.currentItem?.mediumQualityURL } if currentQuality == .Medium { return self.currentItem?.highestQualityURL } return nil }() if let URLInfo = URLInfo where URLInfo.quality != currentQuality { let cip = currentItemProgression let item = AVPlayerItem(URL: URLInfo.URL) qualityIsBeingChanged = true player?.replaceCurrentItemWithPlayerItem(item) if let cip = cip { seekToTime(cip) } qualityIsBeingChanged = false self.currentQuality = URLInfo.quality } } interruptionCount = 0 let target = ClosureContainer(closure: { [weak self] sender in self?.adjustQualityIfNecessary() }) let timer = NSTimer(timeInterval: adjustQualityTimeInternal, target: target, selector: "callSelectorOnTarget:", userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) qualityAdjustmentTimer = timer } } // MARK: Background /// The backround task identifier if a background task started. Nil if not. private var backgroundTaskIdentifier: Int? /** Starts a background task if there isn't already one running. */ private func beginBackgroundTask() { if backgroundTaskIdentifier == nil { UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({[weak self] () -> Void in self?.backgroundTaskIdentifier = nil }) } } /** Ends the background task if there is one. */ private func endBackgroundTask() { if let backgroundTaskIdentifier = backgroundTaskIdentifier { if backgroundTaskIdentifier != UIBackgroundTaskInvalid { UIApplication.sharedApplication().endBackgroundTask(backgroundTaskIdentifier) } self.backgroundTaskIdentifier = nil } } // MARK: Mode /** Sorts the queue depending on the current mode. */ private func adaptQueueToPlayerMode() { if mode.intersect(.Shuffle) != [] { enqueuedItems = enqueuedItems?.shuffled() } else { enqueuedItems = enqueuedItems?.sort({ $0.position < $1.position }) } } }
mit
d35ee547f32b293499b9882817b9b540
33.444221
211
0.58806
5.591777
false
false
false
false
jemmons/SessionArtist
Tests/SessionArtistTests/RequestTests.swift
1
4285
import Foundation import XCTest import SessionArtist import Perfidy class RequestTests: XCTestCase { let fakeHost = Host(baseURL: FakeServer.defaultURL, defaultHeaders: [.other("foo"): "bar"]) func testRequestHeaders() { let endpoint = Endpoint(method: .get, path: "/test", headers: [.other("baz"): "thud"]) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual("bar", req.allHTTPHeaderFields!["foo"], "Host headers") XCTAssertEqual("thud", req.allHTTPHeaderFields!["baz"], "Endpoint headers") } } func testURLRequestParam() { let endpoint = Endpoint(method: .trace, path: "/test", headers: [.other("baz"): "thud"]) let req = fakeHost.request(endpoint).urlRequest XCTAssert(req.url!.absoluteString.starts(with: FakeServer.defaultURL.absoluteString)) XCTAssertEqual( "/test", req.url!.path) XCTAssertEqual("TRACE", req.httpMethod) XCTAssertEqual("bar", req.allHTTPHeaderFields!["foo"], "Host headers") XCTAssertEqual("thud", req.allHTTPHeaderFields!["baz"], "Endpoint headers") } func testRequestGetEndpoint() { let params = Params([URLQueryItem(name: "foo", value: "bar")]) let endpoint = Endpoint(method: .get, path: "/test", params: params) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual(req.url!.query, "foo=bar") XCTAssertNil(req.allHTTPHeaderFields!["Content-Type"]) } } func testRequestPostQueryEndpoint() { let params = Params([URLQueryItem(name: "foo", value: "bar")]) let endpoint = Endpoint(method: .postQuery, path: "/test", params: params) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual(req.url!.query, "foo=bar") XCTAssertNil(req.allHTTPHeaderFields!["Content-Type"]) } } func testRequestPostEndpoint() { let params = Params([URLQueryItem(name: "foo", value: "bar")]) let endpoint = Endpoint(method: .post, path: "/test", params: params) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Content-Type"], "application/x-www-form-urlencoded") XCTAssertEqual(String(data: req.httpBody!, encoding: .utf8), "foo=bar") XCTAssertNil(req.url!.query) } } func testRequestPutEndpoint() { let params = Params([URLQueryItem(name: "foo", value: "bar")]) let endpoint = Endpoint(method: .put, path: "/test", params: params) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Content-Type"], "application/x-www-form-urlencoded") XCTAssertEqual(String(data: req.httpBody!, encoding: .utf8), "foo=bar") XCTAssertNil(req.url!.query) } } func testRequestDeleteEndpoint() { let endpoint = Endpoint(method: .delete, path: "/test") doFakeRequest(endpoint: endpoint) { req in XCTAssertNil(req.url!.query) XCTAssertNil(req.httpBody) } } func testOverrideContentType() { let params = Params([URLQueryItem(name: "foo", value: "bar")]) let endpoint = Endpoint(method: .post, path: "/test", params: params, headers: [.contentType: "foobar"]) doFakeRequest(endpoint: endpoint) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Content-Type"], "foobar") XCTAssertEqual(String(data: req.httpBody!, encoding: .utf8), "foo=bar") } } func testGetEndpointWithoutParams() { let endpoint = Endpoint(method: .get, path: "/test") doFakeRequest(endpoint: endpoint) { req in XCTAssertFalse(req.url!.absoluteString.contains("?")) } } } private extension RequestTests { func doFakeRequest(endpoint: Endpoint, requestHandler: @escaping (URLRequest)->Void) { let expectedRequest = expectation(description: "waiting for request") let expectedResponse = expectation(description: "waiting for response") FakeServer.runWith { server in server.add(Route(method: endpoint.method.description, path: endpoint.path)) { req in requestHandler(req) expectedRequest.fulfill() } fakeHost.request(endpoint).data { res in if case .success((.ok, _, _)) = res { expectedResponse.fulfill() } } wait(for: [expectedRequest, expectedResponse], timeout: 1) } } }
mit
1d900721b7b2ded368fe5fe45c6a7d6e
31.961538
108
0.663944
4.21752
false
true
false
false
honghaoz/2048-Solver-AI
2048 AI/AI/TDLearning/BoardPos.swift
1
576
// Copyright © 2019 ChouTi. All rights reserved. import Foundation func == (lhs: BoardPos, rhs: BoardPos) -> Bool { return lhs._row == rhs._row && lhs._column == rhs._column } class BoardPos: Equatable { fileprivate var _row: Int fileprivate var _column: Int init(row: Int, col: Int) { self._row = row self._column = col } func row() -> Int { return _row } func column() -> Int { return _column } // add two BoardPos func add(pos: BoardPos) -> BoardPos { return BoardPos(row: _row + pos._row, col: _column + pos._column) } }
gpl-2.0
1d7ccd8c9aa619e1d1f201f101290e56
18.827586
69
0.608696
3.323699
false
false
false
false
bitomule/ReactiveSwiftRealm
Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ListTests.swift
1
13359
//////////////////////////////////////////////////////////////////////////// // // 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 XCTest import RealmSwift class ListTests: TestCase { var str1: SwiftStringObject? var str2: SwiftStringObject? var arrayObject: SwiftArrayPropertyObject! var array: List<SwiftStringObject>? func createArray() -> SwiftArrayPropertyObject { fatalError("abstract") } func createArrayWithLinks() -> SwiftListOfSwiftObject { fatalError("abstract") } override func setUp() { super.setUp() let str1 = SwiftStringObject() str1.stringCol = "1" self.str1 = str1 let str2 = SwiftStringObject() str2.stringCol = "2" self.str2 = str2 arrayObject = createArray() array = arrayObject.array let realm = realmWithTestPath() try! realm.write { realm.add(str1) realm.add(str2) } realm.beginWrite() } override func tearDown() { try! realmWithTestPath().commitWrite() str1 = nil str2 = nil arrayObject = nil array = nil super.tearDown() } override class func defaultTestSuite() -> XCTestSuite { // Don't run tests for the base class if isEqual(ListTests.self) { return XCTestSuite(name: "empty") } return super.defaultTestSuite() } func testInvalidated() { guard let array = array else { fatalError("Test precondition failure") } XCTAssertFalse(array.isInvalidated) if let realm = arrayObject.realm { realm.delete(arrayObject) XCTAssertTrue(array.isInvalidated) } } func testFastEnumerationWithMutation() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2, str1, str2, str1, str2, str1, str2, str1, str2, str1, str2, str1, str2, str1, str2, str1, str2, str1, str2]) var str = "" for obj in array { str += obj.stringCol array.append(objectsIn: [str1]) } XCTAssertEqual(str, "12121212121212121212") } func testAppendObject() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } for str in [str1, str2, str1] { array.append(str) } XCTAssertEqual(Int(3), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) XCTAssertEqual(str1, array[2]) } func testAppendArray() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2, str1]) XCTAssertEqual(Int(3), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) XCTAssertEqual(str1, array[2]) } func testAppendResults() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: realmWithTestPath().objects(SwiftStringObject.self)) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) } func testInsert() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } XCTAssertEqual(Int(0), array.count) array.insert(str1, at: 0) XCTAssertEqual(Int(1), array.count) XCTAssertEqual(str1, array[0]) array.insert(str2, at: 0) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(_ = array.insert(str2, at: 200)) assertThrows(_ = array.insert(str2, at: -200)) } func testRemoveAtIndex() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2, str1]) array.remove(objectAtIndex: 1) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(array.remove(objectAtIndex: 200)) assertThrows(array.remove(objectAtIndex: -200)) } func testRemoveLast() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2]) array.removeLast() XCTAssertEqual(Int(1), array.count) XCTAssertEqual(str1, array[0]) array.removeLast() XCTAssertEqual(Int(0), array.count) array.removeLast() // should be a no-op XCTAssertEqual(Int(0), array.count) } func testRemoveAll() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2]) array.removeAll() XCTAssertEqual(Int(0), array.count) array.removeAll() // should be a no-op XCTAssertEqual(Int(0), array.count) } func testReplace() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str1]) array.replace(index: 0, object: str2) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) array.replace(index: 1, object: str2) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str2, array[1]) assertThrows(array.replace(index: 200, object: str2)) assertThrows(array.replace(index: -200, object: str2)) } func testMove() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2]) array.move(from: 1, to: 0) XCTAssertEqual(array[0].stringCol, "2") XCTAssertEqual(array[1].stringCol, "1") array.move(from: 0, to: 1) XCTAssertEqual(array[0].stringCol, "1") XCTAssertEqual(array[1].stringCol, "2") array.move(from: 0, to: 0) XCTAssertEqual(array[0].stringCol, "1") XCTAssertEqual(array[1].stringCol, "2") assertThrows(array.move(from: 0, to: 2)) assertThrows(array.move(from: 2, to: 0)) } func testReplaceRange() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str1]) array.replaceSubrange(0..<1, with: [str2]) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) array.replaceSubrange(1..<2, with: [str2]) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str2, array[1]) array.replaceSubrange(0..<0, with: [str2]) XCTAssertEqual(Int(3), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str2, array[1]) XCTAssertEqual(str2, array[2]) array.replaceSubrange(0..<3, with: []) XCTAssertEqual(Int(0), array.count) assertThrows(array.replaceSubrange(200..<201, with: [str2])) assertThrows(array.replaceSubrange(-200..<200, with: [str2])) assertThrows(array.replaceSubrange(0..<200, with: [str2])) } func testSwap() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } array.append(objectsIn: [str1, str2]) array.swap(index1: 0, 1) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) array.swap(index1: 1, 1) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(array.swap(index1: -1, 0)) assertThrows(array.swap(index1: 0, -1)) assertThrows(array.swap(index1: 1000, 0)) assertThrows(array.swap(index1: 0, 1000)) } func testChangesArePersisted() { guard let array = array, let str1 = str1, let str2 = str2 else { fatalError("Test precondition failure") } if let realm = array.realm { array.append(objectsIn: [str1, str2]) let otherArray = realm.objects(SwiftArrayPropertyObject.self).first!.array XCTAssertEqual(Int(2), otherArray.count) } } func testPopulateEmptyArray() { guard let array = array else { fatalError("Test precondition failure") } XCTAssertEqual(array.count, 0, "Should start with no array elements.") let obj = SwiftStringObject() obj.stringCol = "a" array.append(obj) array.append(realmWithTestPath().create(SwiftStringObject.self, value: ["b"])) array.append(obj) XCTAssertEqual(array.count, 3) XCTAssertEqual(array[0].stringCol, "a") XCTAssertEqual(array[1].stringCol, "b") XCTAssertEqual(array[2].stringCol, "a") // Make sure we can enumerate for obj in array { XCTAssertTrue(obj.description.utf16.count > 0, "Object should have description") } } func testEnumeratingListWithListProperties() { let arrayObject = createArrayWithLinks() arrayObject.realm?.beginWrite() for _ in 0..<10 { arrayObject.array.append(SwiftObject()) } try! arrayObject.realm?.commitWrite() XCTAssertEqual(10, arrayObject.array.count) for object in arrayObject.array { XCTAssertEqual(123, object.intCol) XCTAssertEqual(false, object.objectCol!.boolCol) XCTAssertEqual(0, object.arrayCol.count) } } } class ListStandaloneTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let array = SwiftArrayPropertyObject() XCTAssertNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let array = SwiftListOfSwiftObject() XCTAssertNil(array.realm) return array } } class ListNewlyAddedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let array = SwiftArrayPropertyObject() array.name = "name" let realm = realmWithTestPath() try! realm.write { realm.add(array) } XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let array = SwiftListOfSwiftObject() let realm = try! Realm() try! realm.write { realm.add(array) } XCTAssertNotNil(array.realm) return array } } class ListNewlyCreatedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let realm = realmWithTestPath() realm.beginWrite() let array = realm.create(SwiftArrayPropertyObject.self, value: ["name", [], []]) try! realm.commitWrite() XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let realm = try! Realm() realm.beginWrite() let array = realm.create(SwiftListOfSwiftObject.self) try! realm.commitWrite() XCTAssertNotNil(array.realm) return array } } class ListRetrievedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let realm = realmWithTestPath() realm.beginWrite() realm.create(SwiftArrayPropertyObject.self, value: ["name", [], []]) try! realm.commitWrite() let array = realm.objects(SwiftArrayPropertyObject.self).first! XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let realm = try! Realm() realm.beginWrite() realm.create(SwiftListOfSwiftObject.self) try! realm.commitWrite() let array = realm.objects(SwiftListOfSwiftObject.self).first! XCTAssertNotNil(array.realm) return array } }
mit
c524e989eec47eab44269cef9e74b956
29.223982
92
0.603563
4.384312
false
true
false
false
PurpleSweetPotatoes/SwiftKit
SwiftKit/control/BQRefresh/BQRefreshHeaderView.swift
1
3970
// // BQRefreshHeaderView.swift // BQRefresh // // Created by MrBai on 2017/7/5. // Copyright © 2017年 baiqiang. All rights reserved. // import UIKit class BQRefreshHeaderView: BQRefreshView { //MARK: - ***** Ivars ***** private var imgView = UIImageView(image: Bundle.arrowImage()) private let loadingView = UIActivityIndicatorView(style: .gray) private let stateLab: UILabel = BQRefreshView.refreshLab() //MARK: - ***** initialize Method ***** init(_ block:@escaping ()->()) { self.init() self.refreshBlock = block } override init(frame: CGRect) { super.init(frame: frame) self.sizeH = 54 self.top = -self.sizeH self.initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - ***** public Method ***** public func endRefresh() { self.endAnimation() } override func layoutSubviews() { imgView.center = CGPoint(x: self.sizeW * 0.25, y: self.sizeH * 0.5) loadingView.center = imgView.center stateLab.frame = CGRect(x: 0, y: 0, width: self.sizeW, height: self.sizeH) super.layoutSubviews() } //MARK: - ***** private Method ***** private func initUI() { self.addSubview(loadingView) loadingView.center = imgView.center loadingView.isHidden = true self.addSubview(self.stateLab) self.addSubview(imgView) } override func contentOffsetDidChange(change: [NSKeyValueChangeKey : Any]?) { super.contentOffsetDidChange(change: change) if self.status == .refreshing { return } if (self.scrollView.contentOffset.y > self.scrollViewOriginalInset.top) || self.scrollView.contentOffset.y >= origiOffsetY { return } if self.scrollView.isDragging { switch self.status { case .pull: self.stateLab.text = Bundle.refreshString(key: .headerIdle) UIView.animate(withDuration: 0.25, animations: { self.imgView.transform = CGAffineTransform.identity }) if (origiOffsetY - self.scrollView.contentOffset.y) > self.sizeH { self.status = .willRefresh } case .willRefresh: UIView.animate(withDuration: 0.25, animations: { self.imgView.transform = CGAffineTransform(rotationAngle: CGFloat(0.0000001 - Double.pi)) }) self.stateLab.text = Bundle.refreshString(key: .headerPull) if (origiOffsetY - self.scrollView.contentOffset.y) <= self.sizeH { self.status = .pull } default: break } }else { if self.status == .willRefresh { self.beginAnimation() self.refreshBlock() }else if self.status == .pull { self.endAnimation() } } } private func beginAnimation() { self.status = .refreshing self.imgView.transform = CGAffineTransform.identity self.imgView.isHidden = true self.loadingView.isHidden = false self.loadingView.startAnimating() self.stateLab.text = Bundle.refreshString(key: .headerRefresh) UIView.animate(withDuration: 0.25) { self.scrollView.contentInset = UIEdgeInsets(top: self.sizeH, left: 0, bottom: 0, right: 0) } } private func endAnimation() { self.status = .pull UIView.animate(withDuration: 0.25, animations: { self.scrollView.contentInset = UIEdgeInsets.zero }) { (flag) in self.imgView.isHidden = false self.loadingView.stopAnimating() self.loadingView.isHidden = true } } }
apache-2.0
0d622501fd85396f1bf148f7f9778b0f
32.336134
132
0.568692
4.618161
false
false
false
false
inkyfox/RxGoogleMaps
RxGoogleMapsBridge.swift
1
6650
// Copyright (c) RxSwiftCommunity // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import GoogleMaps import RxGoogleMaps import RxCocoa import RxSwift extension RxGMSMapViewDelegateProxy: GMSMapViewDelegate { public func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { return self.didHandleTap(marker) } public func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { return self.markerInfoWindow(marker: marker) } public func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? { return self.markerInfoContents(marker: marker) } public func didTapMyLocationButton(for mapView: GMSMapView) -> Bool { return self.didTapMyLocationButton() } } extension GoogleMaps.GMSMapView: RxGMSMapView { public var delegateWrapper: RxGMSMapViewDelegate? { get { return delegate as? RxGMSMapViewDelegate } set { delegate = newValue as? GMSMapViewDelegate } } public var cameraWrapper: RxGMSCameraPosition { get { return camera as RxGMSCameraPosition } set { camera = newValue as! GMSCameraPosition } } public var selectedMarkerWrapper: RxGMSMarker? { get { return selectedMarker as? RxGMSMarker } set { selectedMarker = newValue as? GMSMarker } } public func animateWrapper(to cameraPosition: RxGMSCameraPosition) { animate(to: cameraPosition as! GMSCameraPosition) } public var settingsWrapper: RxGMSUISettings { return settings as RxGMSUISettings } } extension Reactive where Base: GoogleMaps.GMSMapView { /** Wrapper of: mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) */ public var didChangePosition: ControlEvent<GMSCameraPosition> { return ControlEvent(events: didChangePositionWrapper.map { $0 as! GMSCameraPosition }) } /** Wrapper of: mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) */ public var idleAtPosition: ControlEvent<GMSCameraPosition> { return ControlEvent(events: idleAtPositionWrapper.map { $0 as! GMSCameraPosition }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool */ public var didTapMarker: ControlEvent<GMSMarker> { return ControlEvent(events: didTapMarkerWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) */ public var didTapInfoWindow: ControlEvent<GMSMarker> { return ControlEvent(events: didTapInfoWindowWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) */ public var didLongPressInfoWindow: ControlEvent<GMSMarker> { return ControlEvent(events: didLongPressInfoWindowWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) */ public var didTapOverlay: ControlEvent<GMSOverlay> { return ControlEvent(events: didTapOverlayWrapper.map { $0 as! GMSOverlay }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didCloseInfoWindowOf marker: GMSMarker) */ public var didCloseInfoWindow: ControlEvent<GMSMarker> { return ControlEvent(events: didCloseInfoWindowWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) */ public var didBeginDraggingMarker: ControlEvent<GMSMarker> { return ControlEvent(events: didBeginDraggingMarkerWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker) */ public var didEndDraggingMarker: ControlEvent<GMSMarker> { return ControlEvent(events: didEndDraggingMarkerWrapper.map { $0 as! GMSMarker }) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didDrag marker: GMSMarker) */ public var didDragMarker: ControlEvent<GMSMarker> { return ControlEvent(events: didDragMarkerWrapper.map { $0 as! GMSMarker }) } } extension Reactive where Base: GoogleMaps.GMSMapView { public func handleTapMarker(_ closure: ((GMSMarker) -> (Bool))?) { if let c = closure { handleTapMarkerWrapper { c($0 as! GMSMarker) } } else { handleTapMarkerWrapper(nil) } } public func handleMarkerInfoWindow(_ closure: ((GMSMarker) -> (UIView?))?) { if let c = closure { handleMarkerInfoWindowWrapper { c($0 as! GMSMarker) } } else { handleMarkerInfoWindowWrapper(nil) } } public func handleMarkerInfoContents(_ closure: ((GMSMarker) -> (UIView?))?) { if let c = closure { handleMarkerInfoContentsWrapper { c($0 as! GMSMarker) } } else { handleMarkerInfoContentsWrapper(nil) } } } extension GoogleMaps.GMSUISettings: RxGMSUISettings { } extension GoogleMaps.GMSCameraPosition: RxGMSCameraPosition { } extension GoogleMaps.GMSOverlay: RxGMSOverlay { } extension GoogleMaps.GMSMarker: RxGMSMarker { } extension GoogleMaps.GMSCircle: RxGMSCircle { } extension GoogleMaps.GMSPolyline: RxGMSPolyline { } extension GoogleMaps.GMSPolygon: RxGMSPolygon { } extension GoogleMaps.GMSGroundOverlay: RxGMSGroundOverlay { }
mit
7be20423ea948b42f5e7045d60232f5f
34
97
0.695489
4.784173
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Relationship/RelationshipTableViewModel.swift
2
1139
// // RelationshipViewModel.swift // InstagramAPI // // Created by Admin on 02.06.17. // Copyright © 2017 ConceptOffice. All rights reserved. // import UIKit class RelationshipTableViewModel: NSObject { private var type: RelationshipTableControllerType = .unknown init(type: RelationshipTableControllerType) { self.type = type } func request() -> AnyInstagramNetworkRouter? { switch type { case .follows: return InstagramRelationshipRouter.getFollows case .followedBy: return InstagramRelationshipRouter.getFollowedBy case .requestedBy: return InstagramRelationshipRouter.getRequestedBy case .unknown: return nil } } func getDataSource(request: AnyInstagramNetworkRouter, completion: @escaping (([InstagramUser]?) -> Void)) { InstagramClient().send(request, completion: { (users: InstagramArrayResponse<InstagramUser>?, error: Error? ) in if error == nil { guard let users = users?.data else { completion(nil) return } completion(users) } }) } }
mit
30576e13af68079a5151ef42ccf10d10
23.73913
111
0.650264
4.644898
false
false
false
false
gspd-mobi/rage-ios
Sources/Rage/BodyRageRequest.swift
1
1141
import Foundation open class BodyRageRequest: RageRequest { var body: Data? public override init(httpMethod: HttpMethod, baseUrl: String?) { super.init(httpMethod: httpMethod, baseUrl: baseUrl) } public override init(requestDescription: RequestDescription) { super.init(requestDescription: requestDescription) } open func bodyData(_ value: Data) -> BodyRageRequest { body = value return self } open func bodyString(_ value: String) -> BodyRageRequest { body = value.utf8Data() return self } open override func rawRequest() -> URLRequest { if isAuthorized { _ = authenticator?.authorizeRequest(self) } let url = URLBuilder().fromRequest(self) let request = NSMutableURLRequest(url: url) for (key, value) in headers { request.addValue(value, forHTTPHeaderField: key) } request.httpMethod = httpMethod.stringValue() if httpMethod.hasBody() { request.httpBody = body } return request as URLRequest } }
mit
a917642535938ff7d98b31042f60c9da
24.931818
66
0.609991
5.048673
false
false
false
false
PatrickChow/Swift-Awsome
News/Modules/Channel..Listing/Model/ChannelModel.swift
1
3467
// // Created by Patrick Chow on 2017/6/27. // Copyright (c) 2017 JIEMIAN. All rights reserved. import Foundation import RxSwift import RxCocoa struct ChannelModel { let id: String let name: String let simplifiedChinese: String let location: String let template: String let uniqueStr: String let section: Int let isNewest: Bool let isRecommend: Bool let isEditable: Bool var isSubscribed: Bool } extension ChannelModel { #if DEBUG init(_ name: String) { self.init(id: "1", name: name, simplifiedChinese: name, location: "foo", template: "foo", uniqueStr: "foo", section: 0, isNewest: false, isRecommend: false, isEditable: false, isSubscribed: false) } #endif } #if DEBUG extension ChannelModel: CustomDebugStringConvertible { var debugDescription: String { return "频道名: \(simplifiedChinese),英文: \(name), uniqueStr: \(uniqueStr), location: \(location), 是否已订阅: \(isSubscribed)" } } #endif extension ChannelModel { mutating func subscribed() -> ChannelModel { var item = self item.isSubscribed = true return item } } class TableViewChannelsSubscriptionCommandsModel { typealias Element = [[ChannelModel]] public let items = ReplaySubject<Element>.create(bufferSize: 1) private var _items: Element? private var disposeBag = DisposeBag() init(_ initialItems: Element) { self._items = initialItems setItems(initialItems) } public func subscribing() -> ReplaySubject<IndexPath> { let observer = ReplaySubject<IndexPath>.create(bufferSize: 1) observer.subscribe(onNext: { print("触发了", $0) self.handleSubscribing($0) }) .disposed(by: disposeBag) return observer } private func setItems(_ items: Element) { self.items.onNext(items) } private func handleSubscribing(_ i: IndexPath) { if var items = self._items { items[i.section][i.row] = items[i.section][i.row].subscribed() self._items = items setItems(items) } } } enum TableViewSubscribedChannelsEditingCommand { case setChannels(channels: [ChannelModel]) case deleteChannel(indexPath: IndexPath) case moveChannel(from: IndexPath, to: IndexPath) } struct TableViewSubscribedChannelsSubscriptionCommandsModel { let channels: [ChannelModel] static func executeCommand(state: TableViewSubscribedChannelsSubscriptionCommandsModel, _ command: TableViewSubscribedChannelsEditingCommand) -> TableViewSubscribedChannelsSubscriptionCommandsModel { switch command { case let .setChannels(channels): return TableViewSubscribedChannelsSubscriptionCommandsModel(channels: channels) case let .deleteChannel(indexPath): var all = state.channels all.remove(at: indexPath.row) return TableViewSubscribedChannelsSubscriptionCommandsModel(channels: all) case let .moveChannel(from, to): var all = state.channels let channel = all[from.row] all.remove(at: from.row) all.insert(channel, at: to.row) return TableViewSubscribedChannelsSubscriptionCommandsModel(channels: all) } } }
mit
6cb1f32d4272dbaed5822812e656dff6
29.705357
204
0.642629
4.685286
false
false
false
false
vishalvshekkar/realmDemo
RealmDemo/RealmDemo/Contact.swift
1
530
// // Contact.swift // RealmDemo // // Created by Vishal V Shekkar on 10/08/16. // Copyright © 2016 Vishal. All rights reserved. // import Foundation import RealmSwift class Contact: Object { dynamic var firstName = "" dynamic var lastName = "" dynamic var imageURL: String? = nil dynamic var address = "" dynamic var age: Int16 = 0 var fullNameFL: String { return firstName + " " + lastName } var fullNameLF: String { return lastName + " " + firstName } }
mit
02aba6152b87926256f1f8deebc65b0d
18.62963
49
0.608696
3.977444
false
false
false
false
openxc/openxc-ios-app-demo
openXCenabler/DiagViewController.swift
1
6752
// // DiagViewController.swift // openXCenabler // // Created by Tim Buick on 2016-08-04. // Copyright (c) 2016 Ford Motor Company Licensed under the BSD license. // import UIKit import openXCiOSFramework class DiagViewController: UIViewController, UITextFieldDelegate { // UI outlets @IBOutlet weak var bussel: UISegmentedControl! @IBOutlet weak var idField: UITextField! @IBOutlet weak var modeField: UITextField! @IBOutlet weak var pidField: UITextField! @IBOutlet weak var ploadField: UITextField! @IBOutlet weak var requestBtn: UIButton! @IBOutlet weak var lastReq: UILabel! @IBOutlet weak var rspText: UITextView! var vm: VehicleManager! var bm : BluetoothManager! // string array holding last X diag responses var rspStrings : [String] = [] override func viewDidLoad() { super.viewDidLoad() // grab VM instance vm = VehicleManager.sharedInstance bm = BluetoothManager.sharedInstance // set default diag response target vm.setDiagnosticDefaultTarget(self, action: DiagViewController.default_diag_rsp) // set custom target for specific Diagnostic request vm.addDiagnosticTarget([1,2015,1], target: self, action: DiagViewController.new_diag_rsp) } // method for custom taregt - specific diagnostic request func new_diag_rsp(_ rsp:NSDictionary) { print("in new diag response") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { if(!bm.isBleConnected){ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage:errorMsgBLE) } } func default_diag_rsp(_ rsp:NSDictionary) { // extract the diag resp message let vr = rsp.object(forKey: "vehiclemessage") as! VehicleDiagnosticResponse // create the string we want to show in the received messages UI var newTxt = "bus:"+vr.bus.description+" id:0x"+String(format:"%x",vr.message_id)+" mode:0x"+String(format:"%x",vr.mode)+"timestamp"+String(vr.timestamp) if vr.pid != nil { newTxt = newTxt+" pid:0x"+String(format:"%x",vr.pid!) } newTxt = newTxt+" success:"+vr.success.description if vr.value != nil { newTxt = newTxt+" value:"+vr.value!.description }else{ newTxt = newTxt+" payload:"+(vr.payload.description) } // save only the 5 response strings if rspStrings.count>5 { rspStrings.removeFirst() } // append the new string rspStrings.append(newTxt) // reload the label with the update string list DispatchQueue.main.async { self.rspText.text = self.rspStrings.joined(separator: "\n") self.requestBtn.isEnabled = true } print("Daignostic Value..........\(self.rspStrings)") } // text view delegate to clear keyboard func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder(); return true; } // TODO radio button for bus // diag send button hit @IBAction func sendHit(_ sender: AnyObject) { // hide keyboard when the send button is hit for textField in self.view.subviews where textField is UITextField { textField.resignFirstResponder() } // if the VM isn't operational, don't send anything if bm.connectionState != VehicleManagerConnectionState.operational { lastReq.text = "Not connected to VI" return } // create an empty diag request let cmd = VehicleDiagnosticRequest() // look at segmented control for bus cmd.bus = bussel.selectedSegmentIndex + 1 // check that the msg id field is valid if let mid = idField.text as String? { let midtrim = mid.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if midtrim=="" { lastReq.text = "Invalid command : need a message_id" return } if let midInt = Int(midtrim,radix:16) as NSInteger? { cmd.message_id = midInt } else { lastReq.text = "Invalid command : message_id should be hex number (with no leading 0x)" return } } else { lastReq.text = "Invalid command : need a message_id" return } // check that the mode field is valid if let mode = modeField.text as String? { let modetrim = mode.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if modetrim=="" { lastReq.text = "Invalid command : need a mode" return } if let modeInt = Int(modetrim,radix:16) as NSInteger? { cmd.mode = modeInt } else { lastReq.text = "Invalid command : mode should be hex number (with no leading 0x)" return } } else { lastReq.text = "Invalid command : need a mode" return } //("mode is ",cmd.mode) // check that the pid field is valid (or empty) if let pid = pidField.text as String? { let pidtrim = pid.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (pidtrim=="") { // this is ok, it's optional } else if let pidInt = Int(pidtrim,radix:16) as NSInteger? { cmd.pid = pidInt } else { lastReq.text = "Invalid command : pid should be hex number (with no leading 0x)" return } } else { } if cmd.pid==nil { } else { } //TODO: add payload in diag request if let mload = ploadField.text as String? { let mloadtrim = mload.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if mloadtrim=="" { // its optional } if mloadtrim.characters.count%2==0 { //payload must be even length let appendedStr = "0x" + mloadtrim cmd.payload = appendedStr as NSString } } else { lastReq.text = "Invalid command : payload should be even length" return } // Get the Unix timestamp let timestamp = NSDate().timeIntervalSince1970 cmd.timestamp = NSInteger(timestamp) // send the diag request vm.sendDiagReq(cmd) // update the last request sent label lastReq.text = "bus:"+String(cmd.bus)+" id:0x"+idField.text!+" mode:0x"+modeField.text!+"timestamp"+String(timestamp) if cmd.pid != nil { lastReq.text = lastReq.text!+" pid:0x"+pidField.text! } if !cmd.payload.isEqual(to: "") { lastReq.text = lastReq.text!+" payload:"+ploadField.text! requestBtn.isEnabled = false } } }
bsd-3-clause
edcad2447dab0d9c0ebb3aadc4266478
29.972477
157
0.629591
4.249213
false
false
false
false