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
mohitathwani/swift-corelibs-foundation
Foundation/NSSpecialValue.swift
1
4809
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // internal protocol NSSpecialValueCoding { static func objCType() -> String init(bytes value: UnsafeRawPointer) func encodeWithCoder(_ aCoder: NSCoder) init?(coder aDecoder: NSCoder) func getValue(_ value: UnsafeMutableRawPointer) // Ideally we would make NSSpecialValue a generic class and specialise it for // NSPoint, etc, but then we couldn't implement NSValue.init?(coder:) because // it's not yet possible to specialise classes with a type determined at runtime. // // Nor can we make NSSpecialValueCoding conform to Equatable because it has associated // type requirements. // // So in order to implement equality and hash we have the hack below. func isEqual(_ value: Any) -> Bool var hash: Int { get } var description: String? { get } } internal class NSSpecialValue : NSValue { // Originally these were functions in NSSpecialValueCoding but it's probably // more convenient to keep it as a table here as nothing else really needs to // know about them private static let _specialTypes : Dictionary<Int, NSSpecialValueCoding.Type> = [ 1 : NSPoint.self, 2 : NSSize.self, 3 : NSRect.self, 4 : NSRange.self, 12 : NSEdgeInsets.self ] private static func _typeFromFlags(_ flags: Int) -> NSSpecialValueCoding.Type? { return _specialTypes[flags] } private static func _flagsFromType(_ type: NSSpecialValueCoding.Type) -> Int { for (F, T) in _specialTypes { if T == type { return F } } return 0 } private static func _objCTypeFromType(_ type: NSSpecialValueCoding.Type) -> String? { for (_, T) in _specialTypes { if T == type { return T.objCType() } } return nil } internal static func _typeFromObjCType(_ type: UnsafePointer<Int8>) -> NSSpecialValueCoding.Type? { let objCType = String(cString: type) for (_, T) in _specialTypes { if T.objCType() == objCType { return T } } return nil } internal var _value : NSSpecialValueCoding init(_ value: NSSpecialValueCoding) { self._value = value } required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { guard let specialType = NSSpecialValue._typeFromObjCType(type) else { NSUnimplemented() } self._value = specialType.init(bytes: value) } override func getValue(_ value: UnsafeMutableRawPointer) { self._value.getValue(value) } convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let specialFlags = aDecoder.decodeInteger(forKey: "NS.special") guard let specialType = NSSpecialValue._typeFromFlags(specialFlags) else { return nil } guard let specialValue = specialType.init(coder: aDecoder) else { return nil } self.init(specialValue) } override func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(NSSpecialValue._flagsFromType(type(of: _value)), forKey: "NS.special") _value.encodeWithCoder(aCoder) } override var objCType : UnsafePointer<Int8> { let typeName = NSSpecialValue._objCTypeFromType(type(of: _value)) return typeName!._bridgeToObjectiveC().utf8String! // leaky } override var classForCoder: AnyClass { // for some day when we support class clusters return NSValue.self } override var description : String { if let description = _value.description { return description } else { return super.description } } override func isEqual(_ value: Any?) -> Bool { switch value { case let other as NSSpecialValue: return _value.isEqual(other._value) case let other as NSObject: return self === other default: return false } } override var hash: Int { return _value.hash } }
apache-2.0
67a53153469b992720bb5daabf7f8f23
31.06
103
0.614681
4.714706
false
false
false
false
ingresse/ios-sdk
IngresseSDKTests/Services/MyTicketsServiceTests.swift
1
11849
// // Copyright © 2018 Ingresse. All rights reserved. // import XCTest @testable import IngresseSDK class MyTicketsServiceTests: XCTestCase { var restClient: MockClient! var client: IngresseClient! var service: MyTicketsService! override func setUp() { super.setUp() restClient = MockClient() client = IngresseClient(apiKey: "1234", userAgent: "", restClient: restClient) service = IngresseService(client: client).myTickets } // MARK: - User Wallet func testGetUserWallet() { // Given let asyncExpectation = expectation(description: "userWallet") var response = [String: Any]() response["data"] = [["id": 1]] response["paginationInfo"] = ["currentPage": 1, "lastPage": 10, "totalResults": 1000, "pageSize": 100] restClient.response = response restClient.shouldFail = false let delegate = WalletSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserWallet(userId: "1234", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didSyncItemsPageCalled) XCTAssertNotNil(delegate.resultData) XCTAssertNotNil(delegate.resultPage) XCTAssertEqual(delegate.resultPage?.currentPage, 1) XCTAssertEqual(delegate.resultPage?.lastPage, 10) XCTAssertEqual(delegate.resultPage?.totalResults, 1000) XCTAssertEqual(delegate.resultPage?.pageSize, 100) XCTAssertEqual(delegate.resultData?[0].id, 1) } } func testGetUserWalletFuture() { // Given let asyncExpectation = expectation(description: "userWallet") var response = [String: Any]() response["data"] = [["id": 1]] response["paginationInfo"] = ["currentPage": 1, "lastPage": 10, "totalResults": 1000, "pageSize": 100] restClient.response = response restClient.shouldFail = false let delegate = WalletSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserWallet(userId: "1234", userToken: "1234-token", from: "future", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didSyncItemsPageCalled) guard let request = self.restClient.requestCalled, let url = request.url?.absoluteString else { XCTFail("Invalid URL") return } XCTAssert(url.contains("order=ASC")) XCTAssert(url.contains("from=yesterday")) } } func testGetUserWalletPast() { // Given let asyncExpectation = expectation(description: "userWallet") var response = [String: Any]() response["data"] = [["id": 1]] response["paginationInfo"] = ["currentPage": 1, "lastPage": 10, "totalResults": 1000, "pageSize": 100] restClient.response = response restClient.shouldFail = false let delegate = WalletSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserWallet(userId: "1234", userToken: "1234-token", from: "past", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didSyncItemsPageCalled) guard let request = self.restClient.requestCalled, let url = request.url?.absoluteString else { XCTFail("Invalid URL") return } XCTAssert(url.contains("order=DESC")) XCTAssert(url.contains("to=yesterday")) } } func testGetUserWalletWrongData() { // Given let asyncExpectation = expectation(description: "userWallet") var response = [String: Any]() response["data"] = nil restClient.response = response restClient.shouldFail = false let delegate = WalletSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserWallet(userId: "1234", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailSyncItemsCalled) XCTAssertNotNil(delegate.syncError) let defaultError = APIError.getDefaultError() XCTAssertEqual(delegate.syncError?.code, defaultError.code) XCTAssertEqual(delegate.syncError?.message, defaultError.message) } } func testGetUserWalletFail() { // Given let asyncExpectation = expectation(description: "userWallet") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true let delegate = WalletSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserWallet(userId: "1234", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailSyncItemsCalled) XCTAssertNotNil(delegate.syncError) XCTAssertEqual(delegate.syncError?.code, 1) XCTAssertEqual(delegate.syncError?.message, "message") XCTAssertEqual(delegate.syncError?.category, "category") } } // MARK: - User Tickets func testGetUserTickets() { // Given let asyncExpectation = expectation(description: "userTickets") var response = [String: Any]() response["data"] = [["id": 1]] response["paginationInfo"] = ["currentPage": 1, "lastPage": 10, "totalResults": 1000, "pageSize": 100] restClient.response = response restClient.shouldFail = false let delegate = TicketSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserTickets(userId: "1234", eventId: "2345", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didSyncTicketsPageCalled) XCTAssertNotNil(delegate.resultData) XCTAssertNotNil(delegate.resultPage) XCTAssertEqual(delegate.resultPage?.currentPage, 1) XCTAssertEqual(delegate.resultPage?.lastPage, 10) XCTAssertEqual(delegate.resultPage?.totalResults, 1000) XCTAssertEqual(delegate.resultPage?.pageSize, 100) XCTAssertEqual(delegate.resultData?[0].id, 1) } } func testGetUserTicketsWrongData() { // Given let asyncExpectation = expectation(description: "userTickets") var response = [String: Any]() response["data"] = nil restClient.response = response restClient.shouldFail = false let delegate = TicketSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserTickets(userId: "1234", eventId: "2345", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailSyncTicketsCalled) XCTAssertNotNil(delegate.syncError) let defaultError = APIError.getDefaultError() XCTAssertEqual(delegate.syncError?.code, defaultError.code) XCTAssertEqual(delegate.syncError?.message, defaultError.message) } } func testGetUserTicketsFail() { // Given let asyncExpectation = expectation(description: "userTickets") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true let delegate = TicketSyncDelegateSpy() delegate.asyncExpectation = asyncExpectation // When service.getUserTickets(userId: "1234", eventId: "2345", userToken: "1234-token", page: 1, delegate: delegate) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(delegate.didFailSyncTicketsCalled) XCTAssertNotNil(delegate.syncError) XCTAssertEqual(delegate.syncError?.code, 1) XCTAssertEqual(delegate.syncError?.message, "message") XCTAssertEqual(delegate.syncError?.category, "category") } } // MARK: - Number of Tickets func testGetNumberOfTickets() { // Given let asyncExpectation = expectation(description: "userTickets") var response = [String: Any]() response["data"] = [["id": 1]] response["paginationInfo"] = ["currentPage": 1, "lastPage": 10, "totalResults": 1000, "pageSize": 100] restClient.response = response restClient.shouldFail = false var success = false var apiResponse = 0 var request = Request.Wallet.NumberOfTickets() request.userId = 1234 request.eventId = 2345 request.userToken = "1234-token" // When service.getWalletTicketsOf(request: request, onSuccess: { (number) in success = true apiResponse = number asyncExpectation.fulfill() }, onError: { (_) in }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssert(success) XCTAssertEqual(apiResponse, 1000) } } func testGetNumberOfTicketsWrongData() { // Given let asyncExpectation = expectation(description: "userTickets") var response = [String: Any]() response["data"] = nil restClient.response = response restClient.shouldFail = false var success = false var apiError: APIError? var request = Request.Wallet.NumberOfTickets() request.userId = 1234 request.eventId = 2345 request.userToken = "1234-token" // When service.getWalletTicketsOf(request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) let defaultError = APIError.getDefaultError() XCTAssertEqual(apiError?.code, defaultError.code) XCTAssertEqual(apiError?.message, defaultError.message) } } func testGetNumberOfTicketsFail() { // Given let asyncExpectation = expectation(description: "userTickets") let error = APIError() error.code = 1 error.message = "message" error.category = "category" restClient.error = error restClient.shouldFail = true var success = false var apiError: APIError? var request = Request.Wallet.NumberOfTickets() request.userId = 1234 request.eventId = 2345 request.userToken = "1234-token" // When service.getWalletTicketsOf(request: request, onSuccess: { (_) in }, onError: { (error) in success = false apiError = error asyncExpectation.fulfill() }) // Then waitForExpectations(timeout: 1) { (_) in XCTAssertFalse(success) XCTAssertNotNil(apiError) XCTAssertEqual(apiError?.code, 1) XCTAssertEqual(apiError?.message, "message") XCTAssertEqual(apiError?.category, "category") } } }
mit
4eae24fe6c8d735290c62a24bc8ba274
32.187675
117
0.609976
5.082797
false
false
false
false
aryehToDog/DYZB
DYZB/DYZB/Class/Home/Controller/WKRecommendController.swift
1
3405
// // WKRecommendController.swift // DYZB // // Created by 阿拉斯加的狗 on 2017/8/28. // Copyright © 2017年 阿拉斯加的🐶. All rights reserved. // import UIKit private let kCycleViewH: CGFloat = WKWidth * 3 / 8 private let kGameViewH: CGFloat = 90 class WKRecommendController: WKBaseAnchorViewController { fileprivate lazy var recommerndVM = WKRecommendViewModel() fileprivate lazy var cycleView: WKCycleView = { let cycleView = WKCycleView.cycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: WKWidth, height: kCycleViewH) return cycleView }() fileprivate lazy var gameView: WKRecommendGanmeView = { let gameView = WKRecommendGanmeView.recommendGanmeView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: WKWidth, height: kGameViewH) return gameView }() } // MARK: - 设置UI extension WKRecommendController { override func setupUI() { super.setupUI() //添加cycleView collectionView.addSubview(cycleView) //添加gameView collectionView.addSubview(gameView) collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } extension WKRecommendController { override func reloadData() { self.baseViewModel = self.recommerndVM //发送请求 更新数据 recommerndVM.loadData { self.collectionView.reloadData() var anchorGroup = self.recommerndVM.modelArray anchorGroup.removeFirst() anchorGroup.removeFirst() let groupLastM = WKAnchorGroup() groupLastM.tag_name = "更多" groupLastM.icon_url = "home_more_btn" anchorGroup.append(groupLastM) self.gameView.groupModel = anchorGroup self.finishedCallBackEndAnimatin() } recommerndVM.loadCycleData { //发送网络请求 self.cycleView.cycleModel = self.recommerndVM.cycleModel } } } extension WKRecommendController { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPerttyItemCell, for: indexPath) as! WKPrettyCollectionViewCell let modelGroup = recommerndVM.modelArray[indexPath.section] cell.anchorModel = modelGroup.anchors[indexPath.item] return cell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemwW, height: kPerttyItemH) }else { return CGSize(width: kItemwW, height: kNormalItemH) } } }
apache-2.0
cd66cde89adef659968e5243fab56a4e
25.879032
160
0.594359
5.080793
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/_UIKitDelegate/UITextFieldDelegate/ManagingEditing/UITextFieldDelegateManagePrinting.swift
1
1904
// // UITextFieldDelegateManagePrinting.swift // OOUIKit // // Created by Karsten Litsche on 05.11.17. // import UIKit public final class UITextFieldDelegateManagePrinting: NSObject, UITextFieldDelegate { // MARK: - init convenience override init() { fatalError("Not supported!") } public init(_ decorated: UITextFieldDelegate, filterKey: String = "") { self.decorated = decorated // add space if exist to separate following log self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) " } // MARK: - protocol: UITextFieldDelegate public final func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { printUI("\(filterKey)textfield shouldBeginEditing called") return decorated.textFieldShouldBeginEditing?(textField) ?? true } public final func textFieldDidBeginEditing(_ textField: UITextField) { printUI("\(filterKey)textfield didBeginEditing called") decorated.textFieldDidBeginEditing?(textField) } public final func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { printUI("\(filterKey)textfield shouldEndEditing called") return decorated.textFieldShouldEndEditing?(textField) ?? true } public final func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { printUI("\(filterKey)textfield didEndEditingReason called (\n reason=\(reason.rawValue)\n)") decorated.textFieldDidEndEditing?(textField, reason: reason) } public final func textFieldDidEndEditing(_ textField: UITextField) { printUI("\(filterKey)textfield didEndEditing called") decorated.textFieldDidEndEditing?(textField) } // MARK: - private private let decorated: UITextFieldDelegate private let filterKey: String }
mit
fdc3a66fe879d6f6266aed0f21f67bc8
32.403509
113
0.6875
5.82263
false
false
false
false
hengel2810/swiftBAOS
swiftBAOS/Helper/Reachability.swift
3
12707
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation public enum ReachabilityError: ErrorType { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } public let ReachabilityChangedNotification = "ReachabilityChangedNotification" func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) { let reachability = Unmanaged<Reachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() dispatch_async(dispatch_get_main_queue()) { reachability.reachabilityChanged(flags) } } public class Reachability: NSObject { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case NotReachable, ReachableViaWiFi, ReachableViaWWAN public var description: String { switch self { case .ReachableViaWWAN: return "Cellular" case .ReachableViaWiFi: return "WiFi" case .NotReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var notificationCenter = NSNotificationCenter.defaultCenter() public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .ReachableViaWiFi } if isRunningOnDevice { return .ReachableViaWWAN } } return .NotReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } private var previousFlags: SCNetworkReachabilityFlags? // MARK: - *** Initialisation methods *** required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init(hostname: String) throws { let nodename = (hostname as NSString).UTF8String guard let ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) } self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() throws -> Reachability { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let ref = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(zeroAddress) } return Reachability(reachabilityRef: ref) } public class func reachabilityForLocalWiFi() throws -> Reachability { var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 let address: UInt32 = 0xA9FE0000 localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian) guard let ref = withUnsafePointer(&localWifiAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw ReachabilityError.FailedToCreateWithAddress(localWifiAddress) } return Reachability(reachabilityRef: ref) } // MARK: - *** Notifier methods *** public func startNotifier() throws { guard !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef!, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check let flags = reachabilityFlags reachabilityChanged(flags) notifierRunning = true } public func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { let flags = reachabilityFlags return isReachableWithFlags(flags) } public func isReachableViaWWAN() -> Bool { let flags = reachabilityFlags // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachable(flags) && isOnWWAN(flags) } public func isReachableViaWiFi() -> Bool { let flags = reachabilityFlags // Check we're reachable if !isReachable(flags) { return false } // Must be on WiFi if reachable but not on an iOS device (i.e. simulator) if !isRunningOnDevice { return true } // Check we're NOT on WWAN return !isOnWWAN(flags) } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? private let reachabilitySerialQueue = dispatch_queue_create("uk.co.ashleymills.reachability", DISPATCH_QUEUE_SERIAL) private func reachabilityChanged(flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } if isReachableWithFlags(flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self) previousFlags = flags } private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool { if !isReachable(flags) { return false } if isConnectionRequiredOrTransient(flags) { return false } if isRunningOnDevice { if isOnWWAN(flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) && isConnectionOnTrafficOrDemand(flags) } // Is user intervention required? private func isInterventionRequired() -> Bool { let flags = reachabilityFlags return isConnectionRequired(flags) && isInterventionRequired(flags) } private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags.contains(.IsWWAN) #else return false #endif } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.Reachable) } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionRequired) } private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.InterventionRequired) } private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnTraffic) } private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.ConnectionOnDemand) } func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool { return !flags.intersect([.ConnectionOnTraffic, .ConnectionOnDemand]).isEmpty } private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.TransientConnection) } private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsLocalAddress) } private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.IsDirect) } private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool { let testcase:SCNetworkReachabilityFlags = [.ConnectionRequired, .TransientConnection] return flags.intersect(testcase) == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(&flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(reachabilityFlags) ? "c" : "-" let t = isTransientConnection(reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-" let l = isLocalAddress(reachabilityFlags) ? "l" : "-" let d = isDirect(reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
mit
92420a348ac9e080e8564dedc39de269
34.00551
196
0.660581
5.600264
false
false
false
false
vector-im/riot-ios
Riot/Modules/Room/BubbleReactions/BubbleReactionsViewModel.swift
1
3613
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation @objc final class BubbleReactionsViewModel: NSObject, BubbleReactionsViewModelType { // MARK: - Constants private enum Constants { static let maxItemsWhenLimited: Int = 8 } // MARK: - Properties // MARK: Private private let aggregatedReactions: MXAggregatedReactions private let eventId: String private let showAll: Bool // MARK: Public @objc weak var viewModelDelegate: BubbleReactionsViewModelDelegate? weak var viewDelegate: BubbleReactionsViewModelViewDelegate? // MARK: - Setup @objc init(aggregatedReactions: MXAggregatedReactions, eventId: String, showAll: Bool) { self.aggregatedReactions = aggregatedReactions self.eventId = eventId self.showAll = showAll } // MARK: - Public func process(viewAction: BubbleReactionsViewAction) { switch viewAction { case .loadData: self.loadData() case .tapReaction(let index): guard index < self.aggregatedReactions.reactions.count else { return } let reactionCount = self.aggregatedReactions.reactions[index] if reactionCount.myUserHasReacted { self.viewModelDelegate?.bubbleReactionsViewModel(self, didRemoveReaction: reactionCount, forEventId: self.eventId) } else { self.viewModelDelegate?.bubbleReactionsViewModel(self, didAddReaction: reactionCount, forEventId: self.eventId) } case .addNewReaction: break case .tapShowAction(.showAll): self.viewModelDelegate?.bubbleReactionsViewModel(self, didShowAllTappedForEventId: self.eventId) case .tapShowAction(.showLess): self.viewModelDelegate?.bubbleReactionsViewModel(self, didShowLessTappedForEventId: self.eventId) case .longPress: self.viewModelDelegate?.bubbleReactionsViewModel(self, didLongPressForEventId: self.eventId) } } func loadData() { var reactions = self.aggregatedReactions.reactions var showAllButtonState: BubbleReactionsViewState.ShowAllButtonState = .none // Limit displayed reactions if required if reactions.count > Constants.maxItemsWhenLimited { if self.showAll == true { showAllButtonState = .showLess } else { reactions = Array(reactions[0..<Constants.maxItemsWhenLimited]) showAllButtonState = .showAll } } let reactionsViewData = reactions.map { (reactionCount) -> BubbleReactionViewData in return BubbleReactionViewData(emoji: reactionCount.reaction, countString: "\(reactionCount.count)", isCurrentUserReacted: reactionCount.myUserHasReacted) } self.viewDelegate?.bubbleReactionsViewModel(self, didUpdateViewState: .loaded(reactionsViewData: reactionsViewData, showAllButtonState: showAllButtonState)) } }
apache-2.0
e1899e4552a8f8e862df1f596d188d6f
36.247423
165
0.681705
5.243832
false
false
false
false
peteratseneca/dps923winter2015
Week_10/Where Am I/Classes/SportDetail.swift
3
1069
// // SportDetail.swift // Toronto 2015 // // Created by Peter McIntyre on 2015-03-14. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit class SportDetail: UIViewController { // Data object, passed in by the parent view controller in the segue method var detailItem: Sport! @IBOutlet weak var sportPhoto: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Simply display some data in the debug console let att1 = detailItem.sportDescription let att2 = detailItem.history println("Detail item: \(att1), \(att2)") let att3 = detailItem.venues.count println("\nAt \(att3) venues") for vn in detailItem.venues { let venue = vn as Venue println("...in venue \(venue.venueName)") } // Display the photo, sized to fit sportPhoto.contentMode = UIViewContentMode.ScaleAspectFit sportPhoto.image = UIImage(data: detailItem.photo) } }
mit
2d108731c300be29f8ab8f4f5d3702c5
26.410256
79
0.620206
4.510549
false
false
false
false
mehmetatas/kata
swift/kata/kata/CompositeIteratorImpl.swift
1
1456
class CompositeIteratorImpl<T> : Iterator { private var iterators : Array<IteratorImpl<T>> private var iteratorsToReset : Array<IteratorImpl<T>> private var currentItems : Array<T> // TODO: throw exception for illegal arguments init (iterators : Array<IteratorImpl<T>>) { self.iterators = iterators self.currentItems = Array<T>() self.iteratorsToReset = Array<IteratorImpl<T>>() } private func isEnd() -> Bool { return iteratorsToReset.count == iterators.count } // TODO: make this method static private func reset(iters: Array<IteratorImpl<T>>) { for iter in iters { iter.reset() } } func current() -> Array<T> { currentItems.removeAll(keepCapacity: true) for iter in iterators { currentItems.append(iter.current()) } return currentItems } func moveNext() -> Bool { if (isEnd()) { return false } iteratorsToReset.removeAll(keepCapacity: true) for iter in iterators { if (iter.moveNext()) { break } else { iteratorsToReset.append(iter) } } if (isEnd()) { return false } reset(iteratorsToReset) return true } func reset() { iteratorsToReset.removeAll(keepCapacity: true) reset(iterators) } }
mit
4c139cf98444d554f7a8db77a7c4f89e
22.483871
57
0.559753
4.666667
false
false
false
false
AsimNet/smsGate
smsGate/GroupDetailsView.swift
1
4973
// // GroupDetailsView.swift // smsGate // // Created by Asim al twijry on 10/30/15. // Copyright © 2015 AsimNet. All rights reserved. // import UIKit import ContactsUI import Contacts import RealmSwift class GroupDetailsView: UITableViewController,CNContactPickerDelegate,UIPickerViewDelegate { // MARK: - Variables - Outlets //** Contacts instance **// let contactStore = CNContactStore() //** Group object **// var selectedGroup : Group! var strings : [String] = [""] // MARK: - buttons' Actions @IBAction func selectContacts(sender: AnyObject) { let contactPickerViewController = CNContactPickerViewController() contactPickerViewController.delegate = self print("result : \(strings)") contactPickerViewController.predicateForEnablingContact = NSPredicate(format: "NOT (givenName IN %@) AND phoneNumbers.@count > 0", argumentArray: strings) // print("result33 : \( contactPickerViewController.predicateForEnablingContact!.predicateFormat)") contactPickerViewController.view.tintColor = self.view.tintColor contactPickerViewController.displayedPropertyKeys = [CNContactGivenNameKey, CNContactFamilyNameKey] presentViewController(contactPickerViewController, animated: true, completion: nil) } // MARK: - Contacts Methods func contactPicker(picker: CNContactPickerViewController, didSelectContacts contacts: [CNContact]) { print("Selected \(contacts.count) contacts") for var i = 0;i < contacts.count;i++ { let dummycontact = contacts[i] let phoneNumber = dummycontact.phoneNumbers[0].value as! CNPhoneNumber let result = selectedGroup.contacts.filter { $0.name == (dummycontact.givenName) } print("result : \(result)") if result.isEmpty { // contact does not exist in array let saveContact = Contact() saveContact.name = dummycontact.givenName saveContact.mobileNumber = phoneNumber.stringValue try! Realm().write({ self.selectedGroup.contacts.append(saveContact) }) } } tableView.reloadData() updatePromptString() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return selectedGroup.contacts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // Configure the cell... var dummyContact : Contact! dummyContact = selectedGroup.contacts[indexPath.row] cell.textLabel?.text = dummyContact.mobileNumber cell.detailTextLabel?.text = dummyContact.name strings.append(dummyContact.name) return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Delete the row from the data source var dummyContact : Contact! dummyContact = selectedGroup.contacts[indexPath.row] try! uiRealm.write({ () -> Void in uiRealm.delete(dummyContact) }) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) updatePromptString() } // MARK:- custom method func updatePromptString() -> Void { let promptString:String let contactNo = selectedGroup.contacts.count if(contactNo == 0){ promptString = "لا يوجد مستقبلين" }else if (contactNo == 1){ promptString = "رقم واحد" }else if (contactNo == 2 ){ promptString = "رقمين" }else if (contactNo > 2 && contactNo < 11){ promptString = String(contactNo) + " أرقام" }else{ promptString = String(contactNo) + " رقم" } self.navigationItem.prompt = promptString } }
mit
706956ad4e176f47596630e9a6e9ef1f
29.670807
157
0.58384
5.604994
false
false
false
false
Dwarven/ShadowsocksX-NG
ShadowsocksX-NG/ServerProfileManager.swift
1
2674
// // ServerProfileManager.swift // ShadowsocksX-NG // // Created by 邱宇舟 on 16/6/6. Modified by 秦宇航 16/9/12 // Copyright © 2016年 qiuyuzhou. All rights reserved. // import Cocoa class ServerProfileManager: NSObject { static let instance:ServerProfileManager = ServerProfileManager() var profiles:[ServerProfile] var activeProfileId: String? fileprivate override init() { profiles = [ServerProfile]() let defaults = UserDefaults.standard if let _profiles = defaults.array(forKey: "ServerProfiles") { for _profile in _profiles { let profile = ServerProfile.fromDictionary(_profile as! [String: Any]) profiles.append(profile) } } activeProfileId = defaults.string(forKey: "ActiveServerProfileId") } func setActiveProfiledId(_ id: String) { activeProfileId = id let defaults = UserDefaults.standard defaults.set(id, forKey: "ActiveServerProfileId") } func save() { let defaults = UserDefaults.standard var _profiles = [AnyObject]() for profile in profiles { if profile.isValid() { let _profile = profile.toDictionary() _profiles.append(_profile as AnyObject) } } defaults.set(_profiles, forKey: "ServerProfiles") if getActiveProfile() == nil { activeProfileId = nil } } func getActiveProfile() -> ServerProfile? { if let id = activeProfileId { for p in profiles { if p.uuid == id { return p } } return nil } else { return nil } } func addServerProfileByURL(urls: [URL]) -> Int { var addCount = 0 for url in urls { if let profile = ServerProfile(url: url) { profiles.append(profile) addCount = addCount + 1 } } if addCount > 0 { save() NotificationCenter.default .post(name: NOTIFY_SERVER_PROFILES_CHANGED, object: nil) } return addCount } static func findURLSInText(_ text: String) -> [URL] { var urls = text.split(separator: "\n") .map { String($0).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } .map { URL(string: $0) } .filter { $0 != nil } .map { $0! } urls = urls.filter { $0.scheme == "ss" } return urls } }
gpl-3.0
24a734ec6e32c16b04880e6b40ec3ac5
27.287234
91
0.530275
4.632404
false
false
false
false
samodom/FoundationSwagger
FoundationSwaggerTests/Tests/MethodSwizzlingTestCase.swift
1
4253
// // MethodSwizzlingTestCase.swift // FoundationSwagger // // Created by Sam Odom on 12/27/16. // Copyright © 2016 Swagger Soft. All rights reserved. // import XCTest import FoundationSwagger class MethodSwizzlingTestCase: XCTestCase { enum ClassType { case objectiveC, swift } var surrogate: MethodSurrogate! var originalMethod: Method! var originalImplementation: IMP! var alternateMethod: Method! var alternateImplementation: IMP! var sampleObject: SampleType! var isTestingSwizzledImplementations = false var selectorOriginUnderTest = SelectorOrigin.original var currentCodeSource: CodeSource! var executedContext = false override func tearDown() { surrogate.useOriginalImplementation() super.tearDown() } // MARK: - Mixed implementation func testMixedAndNestedSwizzlingSafety() { setUpSurrogate(classType: .objectiveC, methodType: .instance) // Nested unswizzled ignored surrogate.withOriginalImplementation { XCTFail("This code should not execute") } validateMethodsAreNotSwizzled() // Nested swizzled ignored surrogate.useAlternateImplementation() surrogate.withAlternateImplementation() { XCTFail("This code should not execute") } validateMethodsAreSwizzled() surrogate.useOriginalImplementation() // Nested unswizzled not ignored surrogate.useAlternateImplementation() surrogate.withOriginalImplementation { validateMethodsAreNotSwizzled() } surrogate.useOriginalImplementation() } // Common helpers func setUpSurrogate(classType: ClassType, methodType: MethodType) { switch (classType, methodType) { case (.objectiveC, .`class`): surrogate = objectiveCClassMethodSurrogate() case (.objectiveC, .instance): surrogate = objectiveCInstanceMethodSurrogate() case (.swift, .`class`): surrogate = swiftClassMethodSurrogate() case (.swift, .instance): surrogate = swiftInstanceMethodSurrogate() } loadMethodValues() } private func loadMethodValues() { switch surrogate.owningClass.className() { case SampleObjectiveCClass.className(): sampleObject = SampleObjectiveCClass() case SampleSwiftClass.className(): sampleObject = SampleSwiftClass() default: fatalError("Testing unknown class") } originalMethod = getMethod(ofOrigin: .original) originalImplementation = method_getImplementation(originalMethod) alternateMethod = getMethod(ofOrigin: .alternate) alternateImplementation = method_getImplementation(alternateMethod) } func objectiveCClassMethodSurrogate() -> MethodSurrogate { return MethodSurrogate( forClass: SampleObjectiveCClass.self, ofType: .class, originalSelector: #selector(SampleObjectiveCClass.sampleClassMethod), alternateSelector: #selector(SampleObjectiveCClass.otherClassMethod) ) } func objectiveCInstanceMethodSurrogate() -> MethodSurrogate { return MethodSurrogate( forClass: SampleObjectiveCClass.self, ofType: .instance, originalSelector: #selector(SampleObjectiveCClass.sampleInstanceMethod), alternateSelector: #selector(SampleObjectiveCClass.otherInstanceMethod) ) } func swiftClassMethodSurrogate() -> MethodSurrogate { return MethodSurrogate( forClass: SampleSwiftClass.self, ofType: .class, originalSelector: #selector(SampleSwiftClass.sampleClassMethod), alternateSelector: #selector(SampleSwiftClass.otherClassMethod) ) } func swiftInstanceMethodSurrogate() -> MethodSurrogate { return MethodSurrogate( forClass: SampleSwiftClass.self, ofType: .instance, originalSelector: #selector(SampleSwiftClass.sampleInstanceMethod), alternateSelector: #selector(SampleSwiftClass.otherInstanceMethod) ) } }
mit
b72ff9b42b8b4107a8792a952c31a2a7
28.734266
84
0.668391
5.587385
false
true
false
false
luzefeng/iOS8-day-by-day
17-live-rendering/LiveKnobControl/LiveKnobControl/KnobControl.swift
21
4719
// // Copyright 2014 Scott Logic // // 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 @IBDesignable class KnobControl : UIControl { var minimumValue:CGFloat = 0.0 var maximumValue:CGFloat = 1.0 var _primitiveValue:CGFloat = 0.0 @IBInspectable var value:CGFloat { get { return self._primitiveValue } set { self.setValue(newValue, animated: false) } } @IBInspectable var startAngle:CGFloat { get { return self.knobRenderer.startAngle } set { self.knobRenderer.startAngle = newValue } } @IBInspectable var endAngle:CGFloat { get { return self.knobRenderer.endAngle } set { self.knobRenderer.endAngle = newValue } } let continuous = true lazy var gestureRecognizer : RotationGestureRecognizer = { return RotationGestureRecognizer(target: self, action: "handleGesture:") }() let knobRenderer = KnobRenderer() @IBInspectable var lineWidth : CGFloat { get { return self.knobRenderer.lineWidth } set { self.knobRenderer.lineWidth = newValue } } @IBInspectable var pointerLength : CGFloat { get { return self.knobRenderer.pointerLength } set { self.knobRenderer.pointerLength = newValue } } func setup() { addGestureRecognizer(self.gestureRecognizer) self.createKnobUI() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } override var frame: CGRect { didSet { self.knobRenderer.updateWithBounds(bounds) } } override func layoutSubviews() { self.knobRenderer.updateWithBounds(bounds) } func createKnobUI() { self.knobRenderer.color = tintColor self.knobRenderer.startAngle = CGFloat(-M_PI * 11.0 / 8.0) self.knobRenderer.endAngle = CGFloat(M_PI * 3.0 / 8.0) self.knobRenderer.pointerAngle = knobRenderer.startAngle self.knobRenderer.lineWidth = 2.0 self.knobRenderer.pointerLength = 6.0 layer.addSublayer(self.knobRenderer.trackLayer) layer.addSublayer(self.knobRenderer.pointerLayer) } func setValue(newValue: CGFloat, animated:Bool) { self.knobRenderer.updateWithBounds(bounds) if newValue != self._primitiveValue { self.willChangeValueForKey("value") // Save the value to the backing ivar // Make sure we limit it to the requested bounds self._primitiveValue = min(self.maximumValue, max(self.minimumValue, newValue)) // Now let's update the knob with the correct angle let angleRange = self.endAngle - self.startAngle let valueRange = self.maximumValue - self.minimumValue let angleForValue = (self._primitiveValue - self.minimumValue) / valueRange * angleRange + self.startAngle self.knobRenderer.setPointerAngle(angleForValue, animated:animated) self.didChangeValueForKey("value") } } func handleGesture(gesture:RotationGestureRecognizer) { // Mid-point angle let midPointAngle = (2.0 * CGFloat(M_PI) + self.startAngle - self.endAngle) / 2.0 + self.endAngle // Ensure the angle is within a suitable range var boundedAngle = gesture.touchAngle if boundedAngle > midPointAngle { boundedAngle -= CGFloat(2.0 * M_PI) } else if boundedAngle < (midPointAngle - 2.0 * CGFloat(M_PI)) { boundedAngle += CGFloat(2.0 * M_PI) } // Bound the angle to within the suitable range boundedAngle = min(self.endAngle, max(self.startAngle, boundedAngle)); // Convert the angle to a value let angleRange = self.endAngle - self.startAngle let valueRange = self.maximumValue - self.minimumValue let valueForAngle = (boundedAngle - self.startAngle) / angleRange * valueRange + self.minimumValue // Set the control to this value self.value = valueForAngle // Notify of value change if self.continuous { self.sendActionsForControlEvents(.ValueChanged) } else { // Only send an update if the gesture has completed switch gesture.state { case .Ended, .Cancelled: self.sendActionsForControlEvents(.ValueChanged) default: break } } } override func tintColorDidChange() { self.knobRenderer.color = tintColor } }
apache-2.0
6abb9d11767d39a39ace0eb4abeb00ac
29.25
112
0.705022
4.243705
false
false
false
false
qingcai518/MyReader_ios
MyReader/ChapterController.swift
1
2211
// // ChapterController.swift // MyReader // // Created by RN-079 on 2017/03/01. // Copyright © 2017年 RN-079. All rights reserved. // import UIKit class ChapterController: ViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var closeBtn : UIButton! // params. var chapterInfos = [ChapterInfo]() var bookInfo: LocalBookInfo! @IBAction func doClose() { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() setTableView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func setTableView() { tableView.tableFooterView = UIView() tableView.delegate = self tableView.dataSource = self } } extension ChapterController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(64) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let info = chapterInfos[indexPath.row] let startPage = info.startPage AppUtility.saveCurrentPage(bookId: bookInfo.bookId, pageIndex: startPage) NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName.ChangeChapter), object: nil) self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil) } } extension ChapterController : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chapterInfos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let chapterInfo = chapterInfos[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "ChapterCell", for: indexPath) as! ChapterCell cell.chapterNameLbl.text = chapterInfo.chapterName return cell } }
mit
41c3af22c0c95ed2574271a63734b0ba
30.098592
121
0.683424
4.995475
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/Swiftz/Sources/Swiftz/Writer.swift
3
6850
// // Writer.swift // Swiftz // // Created by Robert Widmann on 8/14/15. // Copyright © 2015-2016 TypeLift. All rights reserved. // #if SWIFT_PACKAGE import Operadics import Swiftx #endif /// The `Writer` Monad represents a computation that appends (writes) to an /// associated `Monoid` value as it evaluates. /// /// `Writer` is most famous for allowing the accumulation of log output during /// program execution. public struct Writer<W : Monoid, T> { /// Extracts the current value and environment. public let runWriter : (T, W) public init(_ runWriter : (T, W)) { self.runWriter = runWriter } /// Returns a `Writer` that applies the function to its current value and /// environment. public func mapWriter<U, V>(_ f : (T, W) -> (U, V)) -> Writer<V, U> { let (t, w) = self.runWriter return Writer<V, U>(f(t, w)) } /// Extracts the current environment from the receiver. public var exec : W { return self.runWriter.1 } } /// Appends the given value to the `Writer`'s environment. public func tell<W>(_ w : W) -> Writer<W, ()> { return Writer(((), w)) } /// Executes the action of the given `Writer` and adds its output to the result /// of the computation. public func listen<W, A>(_ w : Writer<W, A>) -> Writer<W, (A, W)> { let (a, w) = w.runWriter return Writer(((a, w), w)) } /// Executes the action of the given `Writer` then applies the function to the /// produced environment and adds the overall output to the result of the /// computation. public func listens<W, A, B>(_ f : (W) -> B, w : Writer<W, A>) -> Writer<W, (A, B)> { let (a, w) = w.runWriter return Writer(((a, f(w)), w)) } /// Executes the action of the given `Writer` to get a value and a function. /// The function is then applied to the current environment and the output added /// to the result of the computation. public func pass<W, A>(_ w : Writer<W, (A, (W) -> W)>) -> Writer<W, A> { let ((a, f), w) = w.runWriter return Writer((a, f(w))) } /// Executes the actino of the given `Writer` and applies the given function to /// its environment, leaving the value produced untouched. public func censor<W, A>(_ f : (W) -> W, w : Writer<W, A>) -> Writer<W, A> { let (a, w) = w.runWriter return Writer((a, f(w))) } extension Writer /*: Functor*/ { public typealias B = Any public typealias FB = Writer<W, B> public func fmap<B>(_ f : (A) -> B) -> Writer<W, B> { return self.mapWriter { (a, w) in (f(a), w) } } } public func <^> <W, A, B>(_ f : (A) -> B, w : Writer<W, A>) -> Writer<W, B> { return w.fmap(f) } extension Writer /*: Pointed*/ { public typealias A = T public static func pure<W, A>(_ x : A) -> Writer<W, A> { return Writer<W, A>((x, W.mempty)) } } extension Writer /*: Applicative*/ { public typealias FAB = Writer<W, (A) -> B> public func ap(fs : Writer<W, (A) -> B>) -> Writer<W, B> { return fs <*> self } } public func <*> <W, A, B>(wfs : Writer<W, (A) -> B>, xs : Writer<W, A>) -> Writer<W, B> { return wfs.bind(Writer.fmap(xs)) } extension Writer /*: Cartesian*/ { public typealias FTOP = Writer<W, ()> public typealias FTAB = Writer<W, (A, B)> public typealias FTABC = Writer<W, (A, B, C)> public typealias FTABCD = Writer<W, (A, B, C, D)> public static var unit : Writer<W, ()> { return Writer<W, ()>(((), W.mempty)) } public func product<B>(r : Writer<W, B>) -> Writer<W, (A, B)> { let (l1, m1) = self.runWriter let (l2, m2) = r.runWriter return Writer<W, (A, B)>(((l1, l2), m1 <> m2)) } public func product<B, C>(r : Writer<W, B>, _ s : Writer<W, C>) -> Writer<W, (A, B, C)> { let (l1, m1) = self.runWriter let (l2, m2) = r.runWriter let (l3, m3) = s.runWriter return Writer<W, (A, B, C)>(((l1, l2, l3), m1 <> m2 <> m3)) } public func product<B, C, D>(r : Writer<W, B>, _ s : Writer<W, C>, _ t : Writer<W, D>) -> Writer<W, (A, B, C, D)> { let (l1, m1) = self.runWriter let (l2, m2) = r.runWriter let (l3, m3) = s.runWriter let (l4, m4) = t.runWriter return Writer<W, (A, B, C, D)>(((l1, l2, l3, l4), m1 <> m2 <> m3 <> m4)) } } extension Writer /*: ApplicativeOps*/ { public typealias C = Any public typealias FC = Writer<W, C> public typealias D = Any public typealias FD = Writer<W, D> public static func liftA<B>(_ f : @escaping (A) -> B) -> (Writer<W, A>) -> Writer<W, B> { return { a in Writer<W, (A) -> B>.pure(f) <*> a } } public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Writer<W, A>) -> (Writer<W, B>) -> Writer<W, C> { return { a in { b in f <^> a <*> b } } } public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Writer<W, A>) -> (Writer<W, B>) -> (Writer<W, C>) -> Writer<W, D> { return { a in { b in { c in f <^> a <*> b <*> c } } } } } extension Writer /*: Monad*/ { public func bind<B>(_ f : (A) -> Writer<W, B>) -> Writer<W, B> { return self >>- f } } public func >>- <W, A, B>(x : Writer<W, A>, f : (A) -> Writer<W, B>) -> Writer<W,B> { let (a, w) = x.runWriter let (a2, w2) = f(a).runWriter return Writer((a2, w <> w2)) } extension Writer /*: MonadOps*/ { public static func liftM<B>(_ f : @escaping (A) -> B) -> (Writer<W, A>) -> Writer<W, B> { return { (m1 : Writer<W, A>) -> Writer<W, B> in m1 >>- { (x1 : A) in Writer<W, B>.pure(f(x1)) } } } public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Writer<W, A>) -> (Writer<W, B>) -> Writer<W, C> { return { (m1 : Writer<W, A>) -> (Writer<W, B>) -> Writer<W, C> in { (m2 : Writer<W, B>) -> Writer<W, C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in Writer<W, C>.pure(f(x1)(x2)) } } } } } public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Writer<W, A>) -> (Writer<W, B>) -> (Writer<W, C>) -> Writer<W, D> { return { (m1 : Writer<W, A>) -> (Writer<W, B>) -> (Writer<W, C>) -> Writer<W, D> in { (m2 : Writer<W, B>) -> (Writer<W, C>) -> Writer<W, D> in { (m3 : Writer<W, C>) -> Writer<W, D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in Writer<W, D>.pure(f(x1)(x2)(x3)) } } } } } } } } public func >>->> <W, A, B, C>(_ f : @escaping (A) -> Writer<W, B>, g : @escaping (B) -> Writer<W, C>) -> ((A) -> Writer<W, C>) { return { x in f(x) >>- g } } public func <<-<< <W, A, B, C>(g : @escaping (B) -> Writer<W, C>, f : @escaping (A) -> Writer<W, B>) -> ((A) -> Writer<W, C>) { return f >>->> g } public func == <W: Equatable, A : Equatable>(l : Writer<W, A>, r : Writer<W, A>) -> Bool { let (a, w) = l.runWriter let (a2, w2) = r.runWriter return (a == a2) && (w == w2) } public func != <W: Equatable, A : Equatable>(l : Writer<W, A>, r : Writer<W, A>) -> Bool { return !(l == r) } public func sequence<W, A>(_ ms : [Writer<W, A>]) -> Writer<W, [A]> { return ms.reduce(Writer<W, [A]>.pure([]), { n, m in return n.bind { xs in return m.bind { x in return Writer<W, [A]>.pure(xs + [x]) } } }) }
apache-2.0
0f0f2278763f0aceb50b946125bd0d41
31.927885
293
0.559352
2.547991
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/SwiftApp/UIScrollView/tableview/RayTableViewController.swift
1
2925
// // RayTableViewController.swift // SwiftApp // // Created by 邬勇鹏 on 2018/7/23. // Copyright © 2018年 raymond. All rights reserved. // import UIKit import SnapKit class RayTableViewController: RayBaseViewController { fileprivate lazy var table: UITableView = { let frame = CGRect(x: 0, y: kNavigationBarH + kStatusBarH, width: kScreenWidth, height: kSafeScreenHeight) let temp = UITableView(frame: frame, style: .plain) temp.backgroundColor = .clear temp.delegate = self temp.dataSource = self if #available(iOS 11, *) { temp.contentInsetAdjustmentBehavior = .never } return temp }() fileprivate lazy var header: UIView = { let v = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 200)) v.backgroundColor = .green v.addSubview(menu) return v }() fileprivate lazy var menu: UIButton = { let btn = UIButton(frame: CGRect(x: 50, y: 170, width: 120, height: 30)) btn.backgroundColor = UIColor.purple btn.addTarget(self, action: #selector(clickMenuAction), for: .touchUpInside) return btn }() fileprivate lazy var footer: UIView = { let v = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 100)) v.backgroundColor = .red return v }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .orange self.view.addSubview(self.table) self.table.tableHeaderView = header self.table.tableFooterView = footer } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } } extension RayTableViewController { @objc private func clickMenuAction() { print("-------") } func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.y if offset >= 170 { //移动到view上 self.view.addSubview(menu) menu.y = table.y } else { self.header.addSubview(menu) menu.y = 170 } } } extension RayTableViewController: UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.selectionStyle = .none cell?.textLabel?.text = "啛啛喳喳错错错" return cell! } }
apache-2.0
484c5595cc0af4ff8eaefaee4d29ed73
29.145833
114
0.613683
4.6304
false
false
false
false
manavgabhawala/swift
stdlib/public/core/OutputStream.swift
1
20039
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Input/Output interfaces //===----------------------------------------------------------------------===// /// A type that can be the target of text-streaming operations. /// /// You can send the output of the standard library's `print(_:to:)` and /// `dump(_:to:)` functions to an instance of a type that conforms to the /// `TextOutputStream` protocol instead of to standard output. Swift's /// `String` type conforms to `TextOutputStream` already, so you can capture /// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of /// logging it to standard output. /// /// var s = "" /// for n in 1...5 { /// print(n, terminator: "", to: &s) /// } /// // s == "12345" /// /// Conforming to the TextOutputStream Protocol /// =========================================== /// /// To make your custom type conform to the `TextOutputStream` protocol, /// implement the required `write(_:)` method. Functions that use a /// `TextOutputStream` target may call `write(_:)` multiple times per writing /// operation. /// /// As an example, here's an implementation of an output stream that converts /// any input to its plain ASCII representation before sending it to standard /// output. /// /// struct ASCIILogger: TextOutputStream { /// mutating func write(_ string: String) { /// let ascii = string.unicodeScalars.lazy.map { scalar in /// scalar == "\n" /// ? "\n" /// : scalar.escaped(asASCII: true) /// } /// print(ascii.joined(separator: ""), terminator: "") /// } /// } /// /// The `ASCIILogger` type's `write(_:)` method processes its string input by /// escaping each Unicode scalar, with the exception of `"\n"` line returns. /// By sending the output of the `print(_:to:)` function to an instance of /// `ASCIILogger`, you invoke its `write(_:)` method. /// /// let s = "Hearts ♡ and Diamonds ♢" /// print(s) /// // Prints "Hearts ♡ and Diamonds ♢" /// /// var asciiLogger = ASCIILogger() /// print(s, to: &asciiLogger) /// // Prints "Hearts \u{2661} and Diamonds \u{2662}" public protocol TextOutputStream { mutating func _lock() mutating func _unlock() /// Appends the given string to the stream. mutating func write(_ string: String) } extension TextOutputStream { public mutating func _lock() {} public mutating func _unlock() {} } /// A source of text-streaming operations. /// /// Instances of types that conform to the `TextOutputStreamable` protocol can /// write their value to instances of any type that conforms to the /// `TextOutputStream` protocol. The Swift standard library's text-related /// types, `String`, `Character`, and `UnicodeScalar`, all conform to /// `TextOutputStreamable`. /// /// Conforming to the TextOutputStreamable Protocol /// ===================================== /// /// To add `TextOutputStreamable` conformance to a custom type, implement the /// required `write(to:)` method. Call the given output stream's `write(_:)` /// method in your implementation. public protocol TextOutputStreamable { /// Writes a textual representation of this instance into the given output /// stream. func write<Target : TextOutputStream>(to target: inout Target) } @available(*, unavailable, renamed: "TextOutputStreamable") typealias Streamable = TextOutputStreamable /// A type with a customized textual representation. /// /// Types that conform to the `CustomStringConvertible` protocol can provide /// their own representation to be used when converting an instance to a /// string. The `String(describing:)` initializer is the preferred way to /// convert an instance of *any* type to a string. If the passed instance /// conforms to `CustomStringConvertible`, the `String(describing:)` /// initializer and the `print(_:)` function use the instance's custom /// `description` property. /// /// Accessing a type's `description` property directly or using /// `CustomStringConvertible` as a generic constraint is discouraged. /// /// Conforming to the CustomStringConvertible Protocol /// ================================================== /// /// Add `CustomStringConvertible` conformance to your custom types by defining /// a `description` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(p) /// // Prints "Point(x: 21, y: 30)" /// /// After implementing the `description` property and declaring /// `CustomStringConvertible` conformance, the `Point` type provides its own /// custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(p) /// // Prints "(21, 30)" /// /// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible` public protocol CustomStringConvertible { /// A textual representation of this instance. /// /// Instead of accessing this property directly, convert an instance of any /// type to a string by using the `String(describing:)` initializer. For /// example: /// /// struct Point: CustomStringConvertible { /// let x: Int, y: Int /// /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(describing: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `description` property. var description: String { get } } /// A type that can be represented as a string in a lossless, unambiguous way. /// /// For example, the integer value 1050 can be represented in its entirety as /// the string "1050". /// /// The description property of a conforming type must be a value-preserving /// representation of the original value. As such, it should be possible to /// re-create an instance from its string representation. public protocol LosslessStringConvertible : CustomStringConvertible { /// Instantiates an instance of the conforming type from a string /// representation. init?(_ description: String) } /// A type with a customized textual representation suitable for debugging /// purposes. /// /// Swift provides a default debugging textual representation for any type. /// That default representation is used by the `String(reflecting:)` /// initializer and the `debugPrint(_:)` function for types that don't provide /// their own. To customize that representation, make your type conform to the /// `CustomDebugStringConvertible` protocol. /// /// Because the `String(reflecting:)` initializer works for instances of *any* /// type, returning an instance's `debugDescription` if the value passed /// conforms to `CustomDebugStringConvertible`, accessing a type's /// `debugDescription` property directly or using /// `CustomDebugStringConvertible` as a generic constraint is discouraged. /// /// Conforming to the CustomDebugStringConvertible Protocol /// ======================================================= /// /// Add `CustomDebugStringConvertible` conformance to your custom types by /// defining a `debugDescription` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing the /// `debugDescription` property, `Point` provides its own custom debugging /// representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" /// /// - SeeAlso: `String.init<T>(reflecting: T)`, `CustomStringConvertible` public protocol CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. var debugDescription: String { get } } //===----------------------------------------------------------------------===// // Default (ad-hoc) printing //===----------------------------------------------------------------------===// @_silgen_name("swift_EnumCaseName") func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>? @_silgen_name("swift_OpaqueSummary") func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>? /// Do our best to print a value that cannot be printed directly. @_semantics("optimize.sil.specialize.generic.never") internal func _adHocPrint_unlocked<T, TargetStream : TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream, isDebugPrint: Bool ) { func printTypeName(_ type: Any.Type) { // Print type names without qualification, unless we're debugPrint'ing. target.write(_typeName(type, qualified: isDebugPrint)) } if let displayStyle = mirror.displayStyle { switch displayStyle { case .optional: if let child = mirror.children.first { _debugPrint_unlocked(child.1, &target) } else { _debugPrint_unlocked("nil", &target) } case .tuple: target.write("(") var first = true for (label, value) in mirror.children { if first { first = false } else { target.write(", ") } if let label = label { if !label.isEmpty && label[label.startIndex] != "." { target.write(label) target.write(": ") } } _debugPrint_unlocked(value, &target) } target.write(")") case .struct: printTypeName(mirror.subjectType) target.write("(") var first = true for (label, value) in mirror.children { if let label = label { if first { first = false } else { target.write(", ") } target.write(label) target.write(": ") _debugPrint_unlocked(value, &target) } } target.write(")") case .enum: if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { // Write the qualified type name in debugPrint. if isDebugPrint { printTypeName(mirror.subjectType) target.write(".") } target.write(caseName) } else { // If the case name is garbage, just print the type name. printTypeName(mirror.subjectType) } if let (_, value) = mirror.children.first { if Mirror(reflecting: value).displayStyle == .tuple { _debugPrint_unlocked(value, &target) } else { target.write("(") _debugPrint_unlocked(value, &target) target.write(")") } } default: target.write(_typeName(mirror.subjectType)) } } else if let metatypeValue = value as? Any.Type { // Metatype printTypeName(metatypeValue) } else { // Fall back to the type or an opaque summary of the kind if let cString = _opaqueSummary(mirror.subjectType), let opaqueSummary = String(validatingUTF8: cString) { target.write(opaqueSummary) } else { target.write(_typeName(mirror.subjectType, qualified: true)) } } } @inline(never) @_semantics("optimize.sil.specialize.generic.never") @_semantics("stdlib_binary_only") internal func _print_unlocked<T, TargetStream : TextOutputStream>( _ value: T, _ target: inout TargetStream ) { // Optional has no representation suitable for display; therefore, // values of optional type should be printed as a debug // string. Check for Optional first, before checking protocol // conformance below, because an Optional value is convertible to a // protocol if its wrapped type conforms to that protocol. if _isOptional(type(of: value)) { let debugPrintable = value as! CustomDebugStringConvertible debugPrintable.debugDescription.write(to: &target) return } if case let streamableObject as TextOutputStreamable = value { streamableObject.write(to: &target) return } if case let printableObject as CustomStringConvertible = value { printableObject.description.write(to: &target) return } if case let debugPrintableObject as CustomDebugStringConvertible = value { debugPrintableObject.debugDescription.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false) } /// Returns the result of `print`'ing `x` into a `String`. /// /// Exactly the same as `String`, but annotated 'readonly' to allow /// the optimizer to remove calls where results are unused. /// /// This function is forbidden from being inlined because when building the /// standard library inlining makes us drop the special semantics. @inline(never) @effects(readonly) func _toStringReadOnlyStreamable<T : TextOutputStreamable>(_ x: T) -> String { var result = "" x.write(to: &result) return result } @inline(never) @effects(readonly) func _toStringReadOnlyPrintable<T : CustomStringConvertible>(_ x: T) -> String { return x.description } //===----------------------------------------------------------------------===// // `debugPrint` //===----------------------------------------------------------------------===// @_semantics("optimize.sil.specialize.generic.never") @inline(never) public func _debugPrint_unlocked<T, TargetStream : TextOutputStream>( _ value: T, _ target: inout TargetStream ) { if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } @_semantics("optimize.sil.specialize.generic.never") internal func _dumpPrint_unlocked<T, TargetStream : TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream ) { if let displayStyle = mirror.displayStyle { // Containers and tuples are always displayed in terms of their element // count switch displayStyle { case .tuple: let count = mirror.children.count target.write(count == 1 ? "(1 element)" : "(\(count) elements)") return case .collection: let count = mirror.children.count target.write(count == 1 ? "1 element" : "\(count) elements") return case .dictionary: let count = mirror.children.count target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs") return case .`set`: let count = mirror.children.count target.write(count == 1 ? "1 member" : "\(count) members") return default: break } } if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } if let displayStyle = mirror.displayStyle { switch displayStyle { case .`class`, .`struct`: // Classes and structs without custom representations are displayed as // their fully qualified type name target.write(_typeName(mirror.subjectType, qualified: true)) return case .`enum`: target.write(_typeName(mirror.subjectType, qualified: true)) if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { target.write(".") target.write(caseName) } return default: break } } _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } //===----------------------------------------------------------------------===// // OutputStreams //===----------------------------------------------------------------------===// internal struct _Stdout : TextOutputStream { mutating func _lock() { _swift_stdlib_flockfile_stdout() } mutating func _unlock() { _swift_stdlib_funlockfile_stdout() } mutating func write(_ string: String) { if string.isEmpty { return } if let asciiBuffer = string._core.asciiBuffer { defer { _fixLifetime(string) } _swift_stdlib_fwrite_stdout( UnsafePointer(asciiBuffer.baseAddress!), asciiBuffer.count, 1) return } for c in string.utf8 { _swift_stdlib_putchar_unlocked(Int32(c)) } } } extension String : TextOutputStream { /// Appends the given string to this string. /// /// - Parameter other: A string to append. public mutating func write(_ other: String) { self += other } } //===----------------------------------------------------------------------===// // Streamables //===----------------------------------------------------------------------===// extension String : TextOutputStreamable { /// Writes the string into the given output stream. /// /// - Parameter target: An output stream. public func write<Target : TextOutputStream>(to target: inout Target) { target.write(self) } } extension Character : TextOutputStreamable { /// Writes the character into the given output stream. /// /// - Parameter target: An output stream. public func write<Target : TextOutputStream>(to target: inout Target) { target.write(String(self)) } } extension UnicodeScalar : TextOutputStreamable { /// Writes the textual representation of the Unicode scalar into the given /// output stream. /// /// - Parameter target: An output stream. public func write<Target : TextOutputStream>(to target: inout Target) { target.write(String(Character(self))) } } /// A hook for playgrounds to print through. public var _playgroundPrintHook : ((String) -> Void)? = {_ in () } internal struct _TeeStream< L : TextOutputStream, R : TextOutputStream > : TextOutputStream { var left: L var right: R /// Append the given `string` to this stream. mutating func write(_ string: String) { left.write(string); right.write(string) } mutating func _lock() { left._lock(); right._lock() } mutating func _unlock() { right._unlock(); left._unlock() } } @available(*, unavailable, renamed: "TextOutputStream") public typealias OutputStreamType = TextOutputStream extension TextOutputStreamable { @available(*, unavailable, renamed: "write(to:)") public func writeTo<Target : TextOutputStream>(_ target: inout Target) { Builtin.unreachable() } }
apache-2.0
1e253f030e5d63511c6fd3259d7fb619
32.665546
80
0.617443
4.609066
false
false
false
false
christophhagen/Signal-iOS
Signal/test/Models/MesssagesBubblesSizeCalculatorTest.swift
1
4620
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import XCTest import SignalServiceKit @testable import Signal /** * This is a brittle test, which will break if our layout changes. * * It serves mostly as documentation for cases to consider when changing the cell measurement logic. * Primarly these test cases came out of a bug introduced in iOS10, * which prevents us from computing proper bounding box for text that uses the UIEmoji font. * * If one of these tests breaks, it should be OK to update the expected value so long as you've tested the result renders * correctly in the running app (the reference sizes were computed in the context of an iphone6 layout. * @see `FakeiPhone6JSQMessagesCollectionViewFlowLayout` */ class MesssagesBubblesSizeCalculatorTest: XCTestCase { let thread = TSContactThread()! let contactsManager = OWSContactsManager() func viewItemForText(_ text: String?) -> ConversationViewItem { let interaction = TSOutgoingMessage(timestamp: 0, in: thread, messageBody: text) interaction.save() var viewItem: ConversationViewItem! interaction.dbReadWriteConnection().readWrite { transaction in viewItem = ConversationViewItem(interaction: interaction, isGroupThread: false, transaction: transaction) } viewItem.shouldShowDate = false viewItem.shouldHideRecipientStatus = true return viewItem } func messageBubbleSize(for viewItem: ConversationViewItem) -> CGSize { viewItem.clearCachedLayoutState() // These are the expected values on iPhone SE. let viewWidth = 320 let contentWidth = 300 return viewItem.cellSize(forViewWidth: Int32(viewWidth), contentWidth:Int32(contentWidth)) } func testHeightForEmptyMessage() { let text: String? = "" let viewItem = self.viewItemForText(text) let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(42, actual.height) } func testHeightForShort1LineMessage() { let text = "foo" let viewItem = self.viewItemForText(text) let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(42, actual.height) } func testHeightForLong1LineMessage() { let text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 x" let viewItem = self.viewItemForText(text) let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(64, actual.height) } func testHeightForShort2LineMessage() { let text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 x 1" let viewItem = self.viewItemForText(text) let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(64, actual.height) } func testHeightForLong2LineMessage() { let text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 x 1 2 3 4 5 6 7 8 9 10 11 12 13 14 x" let viewItem = self.viewItemForText(text) let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(86, actual.height) } func testHeightForiOS10EmojiBug() { let viewItem = self.viewItemForText("Wunderschönen Guten Morgaaaahhhn 😝 - hast du gut geschlafen ☺️😘") let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(86, actual.height) } func testHeightForiOS10EmojiBug2() { let viewItem = self.viewItemForText("Test test test test test test test test test test test test 😊❤️❤️") let actual = messageBubbleSize(for: viewItem) XCTAssertEqual(86, actual.height) } func testHeightForChineseWithEmojiBug() { let viewItem = self.viewItemForText("一二三四五六七八九十甲乙丙😝戊己庚辛壬圭咖啡牛奶餅乾水果蛋糕") let actual = messageBubbleSize(for: viewItem) // erroneously seeing 69 with the emoji fix in place. XCTAssertEqual(86, actual.height) } func testHeightForChineseWithoutEmojiBug() { let viewItem = self.viewItemForText("一二三四五六七八九十甲乙丙丁戊己庚辛壬圭咖啡牛奶餅乾水果蛋糕") let actual = messageBubbleSize(for: viewItem) // erroneously seeing 69 with the emoji fix in place. XCTAssertEqual(86, actual.height) } func testHeightForiOS10DoubleSpaceNumbersBug() { let viewItem = self.viewItemForText("12345678901234567890") let actual = messageBubbleSize(for: viewItem) // erroneously seeing 51 with emoji fix in place. It's the call to "fix string" XCTAssertEqual(64, actual.height) } }
gpl-3.0
1fcdeb6bbcad63f798f14a4ce8d60f60
36.923077
121
0.690331
3.789069
false
true
false
false
tardieu/swift
test/IRGen/witness_table_objc_associated_type.swift
3
2221
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s protocol A {} protocol B { associatedtype AA: A func foo() } @objc protocol O {} protocol C { associatedtype OO: O func foo() } struct SA: A {} struct SB: B { typealias AA = SA func foo() {} } // CHECK-LABEL: @_T034witness_table_objc_associated_type2SBVAA1BAAWP = hidden constant [3 x i8*] [ // CHECK: i8* bitcast (%swift.type* ()* @_T034witness_table_objc_associated_type2SAVMa to i8*) // CHECK: i8* bitcast (i8** ()* @_T034witness_table_objc_associated_type2SAVAA1AAAWa to i8*) // CHECK: i8* bitcast {{.*}} @_T034witness_table_objc_associated_type2SBVAA1BAaaDP3fooyyFTW // CHECK: ] class CO: O {} struct SO: C { typealias OO = CO func foo() {} } // CHECK-LABEL: @_T034witness_table_objc_associated_type2SOVAA1CAAWP = hidden constant [2 x i8*] [ // CHECK: i8* bitcast (%swift.type* ()* @_T034witness_table_objc_associated_type2COCMa to i8*) // CHECK: i8* bitcast {{.*}} @_T034witness_table_objc_associated_type2SOVAA1CAaaDP3fooyyFTW // CHECK: ] // CHECK-LABEL: define hidden void @_T034witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyxAA1BRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B) func witnessOffsetAfterAssociatedType<T: B>(_ x: T) { // CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.B, i32 2 // CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]] // CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]] // CHECK: call void [[FOO]] x.foo() } // CHECK-LABEL: define hidden void @_T034witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyxAA1CRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} { func witnessOffsetAfterAssociatedTypeObjC<T: C>(_ x: T) { // CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.C, i32 1 // CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]] // CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]] // CHECK: call void [[FOO]] x.foo() }
apache-2.0
f61c3b041a1bbe5e8c34ed3b3c495360
40.12963
191
0.631247
3.172857
false
false
false
false
nghiaphunguyen/NKit
NKit/Source/UIImage/UIImage+Color.swift
1
1225
// // UIImage+Color.swift // // Created by Nghia Nguyen on 12/3/15. // import UIKit public extension UIImage { @objc public static func nk_fromColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { let rect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } @objc public static func nk_ellipseFromColor(_ color: UIColor, size: CGSize) -> UIImage { let rect: CGRect = CGRectMake(0.0, 0.0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fillEllipse(in: rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
mit
5b2220d8ff7f47f419d48ef745484b67
30.410256
116
0.64898
5.041152
false
false
false
false
chipivk/SwiftPages
SwiftPages/RAReorderableLayout.swift
1
24790
// // RAReorderableLayout.swift // RAReorderableLayout // // Created by Ryo Aoyama on 10/12/14. // Copyright (c) 2014 Ryo Aoyama. All rights reserved. // import UIKit @objc public protocol RAReorderableLayoutDelegate: UICollectionViewDelegateFlowLayout { optional func collectionView(collectionView: UICollectionView, atIndexPath: NSIndexPath, willMoveToIndexPath toIndexPath: NSIndexPath) optional func collectionView(collectionView: UICollectionView, atIndexPath: NSIndexPath, didMoveToIndexPath toIndexPath: NSIndexPath) optional func collectionView(collectionView: UICollectionView, allowMoveAtIndexPath indexPath: NSIndexPath) -> Bool optional func collectionView(collectionView: UICollectionView, atIndexPath: NSIndexPath, canMoveToIndexPath: NSIndexPath) -> Bool optional func collectionView(collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, willBeginDraggingItemAtIndexPath indexPath: NSIndexPath) optional func collectionView(collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, didBeginDraggingItemAtIndexPath indexPath: NSIndexPath) optional func collectionView(collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, willEndDraggingItemToIndexPath indexPath: NSIndexPath) optional func collectionView(collectionView: UICollectionView, collectionViewLayout layout: RAReorderableLayout, didEndDraggingItemToIndexPath indexPath: NSIndexPath) } @objc public protocol RAReorderableLayoutDataSource: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int optional func collectionView(collectionView: UICollectionView, reorderingItemAlphaInSection section: Int) -> CGFloat optional func scrollTrigerEdgeInsetsInCollectionView(collectionView: UICollectionView) -> UIEdgeInsets optional func scrollTrigerPaddingInCollectionView(collectionView: UICollectionView) -> UIEdgeInsets optional func scrollSpeedValueInCollectionView(collectionView: UICollectionView) -> CGFloat } public class RAReorderableLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate { private enum direction { case toTop case toEnd case stay private func scrollValue(speedValue speedValue: CGFloat, percentage: CGFloat) -> CGFloat { var value: CGFloat = 0.0 switch self { case toTop: value = -speedValue case toEnd: value = speedValue case .stay: return 0 } let proofedPercentage: CGFloat = max(min(1.0, percentage), 0) return value * proofedPercentage } } public weak var delegate: RAReorderableLayoutDelegate? { set { self.collectionView?.delegate = delegate } get { return self.collectionView?.delegate as? RAReorderableLayoutDelegate } } public weak var datasource: RAReorderableLayoutDataSource? { set { self.collectionView?.delegate = delegate } get { return self.collectionView?.dataSource as? RAReorderableLayoutDataSource } } private var displayLink: CADisplayLink? private var longPress: UILongPressGestureRecognizer? private var panGesture: UIPanGestureRecognizer? private var continuousScrollDirection: direction = .stay private var cellFakeView: RACellFakeView? private var panTranslation: CGPoint? private var fakeCellCenter: CGPoint? public var trigerInsets: UIEdgeInsets = UIEdgeInsetsMake(100.0, 100.0, 100.0, 100.0) public var trigerPadding: UIEdgeInsets = UIEdgeInsetsZero public var scrollSpeedValue: CGFloat = 10.0 private var offsetFromTop: CGFloat { let contentOffset = self.collectionView!.contentOffset return self.scrollDirection == .Vertical ? contentOffset.y : contentOffset.x } private var insetsTop: CGFloat { let contentInsets = self.collectionView!.contentInset return self.scrollDirection == .Vertical ? contentInsets.top : contentInsets.left } private var insetsEnd: CGFloat { let contentInsets = self.collectionView!.contentInset return self.scrollDirection == .Vertical ? contentInsets.bottom : contentInsets.right } private var contentLength: CGFloat { let contentSize = self.collectionView!.contentSize return self.scrollDirection == .Vertical ? contentSize.height : contentSize.width } private var collectionViewLength: CGFloat { let collectionViewSize = self.collectionView!.bounds.size return self.scrollDirection == .Vertical ? collectionViewSize.height : collectionViewSize.width } private var fakeCellTopEdge: CGFloat? { if let fakeCell = self.cellFakeView { return self.scrollDirection == .Vertical ? CGRectGetMinY(fakeCell.frame) : CGRectGetMinX(fakeCell.frame) } return nil } private var fakeCellEndEdge: CGFloat? { if let fakeCell = self.cellFakeView { return self.scrollDirection == .Vertical ? CGRectGetMaxY(fakeCell.frame) : CGRectGetMaxX(fakeCell.frame) } return nil } private var trigerInsetTop: CGFloat { return self.scrollDirection == .Vertical ? self.trigerInsets.top : self.trigerInsets.left } private var trigerInsetEnd: CGFloat { return self.scrollDirection == .Vertical ? self.trigerInsets.top : self.trigerInsets.left } private var trigerPaddingTop: CGFloat { if self.scrollDirection == .Vertical { return self.trigerPadding.top }else { return self.trigerPadding.left } } private var trigerPaddingEnd: CGFloat { if self.scrollDirection == .Vertical { return self.trigerPadding.bottom }else { return self.trigerPadding.right } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configureObserver() } override init() { super.init() self.configureObserver() } deinit { self.removeObserver(self, forKeyPath: "collectionView") } override public func prepareLayout() { super.prepareLayout() // scroll triger insets if let insets = self.datasource?.scrollTrigerEdgeInsetsInCollectionView?(self.collectionView!) { self.trigerInsets = insets } // scroll trier padding if let padding = self.datasource?.scrollTrigerPaddingInCollectionView?(self.collectionView!) { self.trigerPadding = padding } // scroll speed value if let speed = self.datasource?.scrollSpeedValueInCollectionView?(self.collectionView!) { self.scrollSpeedValue = speed } } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attributesArray = super.layoutAttributesForElementsInRect(rect) if attributesArray != nil { for attribute in attributesArray! { let layoutAttribute = attribute if layoutAttribute.representedElementCategory == .Cell { if layoutAttribute.indexPath.isEqual(self.cellFakeView?.indexPath) { var cellAlpha: CGFloat = 0 // reordering cell alpha if let alpha = self.datasource?.collectionView?(self.collectionView!, reorderingItemAlphaInSection: layoutAttribute.indexPath.section) { cellAlpha = alpha } layoutAttribute.alpha = cellAlpha } } } } return attributesArray } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "collectionView" { self.setUpGestureRecognizers() }else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } private func configureObserver() { self.addObserver(self, forKeyPath: "collectionView", options: [], context: nil) } private func setUpDisplayLink() { if self.displayLink != nil { return } self.displayLink = CADisplayLink(target: self, selector: "continuousScroll") self.displayLink!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } private func invalidateDisplayLink() { self.continuousScrollDirection = .stay self.displayLink?.invalidate() self.displayLink = nil } // begein scroll private func beginScrollIfNeeded() { if self.cellFakeView == nil { return } let offset = self.offsetFromTop _ = self.insetsTop _ = self.insetsEnd let trigerInsetTop = self.trigerInsetTop let trigerInsetEnd = self.trigerInsetEnd let paddingTop = self.trigerPaddingTop let paddingEnd = self.trigerPaddingEnd let length = self.collectionViewLength let fakeCellTopEdge = self.fakeCellTopEdge let fakeCellEndEdge = self.fakeCellEndEdge if fakeCellTopEdge <= offset + paddingTop + trigerInsetTop { self.continuousScrollDirection = .toTop self.setUpDisplayLink() }else if fakeCellEndEdge >= offset + length - paddingEnd - trigerInsetEnd { self.continuousScrollDirection = .toEnd self.setUpDisplayLink() }else { self.invalidateDisplayLink() } } // move item private func moveItemIfNeeded() { var atIndexPath: NSIndexPath? var toIndexPath: NSIndexPath? if let fakeCell = self.cellFakeView { atIndexPath = fakeCell.indexPath toIndexPath = self.collectionView!.indexPathForItemAtPoint(cellFakeView!.center) } if atIndexPath == nil || toIndexPath == nil { return } if atIndexPath!.isEqual(toIndexPath) { return } // can move item if let canMove = self.delegate?.collectionView?(self.collectionView!, atIndexPath: atIndexPath!, canMoveToIndexPath: toIndexPath!) { if !canMove { return } } // will move item self.delegate?.collectionView?(self.collectionView!, atIndexPath: atIndexPath!, willMoveToIndexPath: toIndexPath!) let attribute = self.layoutAttributesForItemAtIndexPath(toIndexPath!)! self.collectionView!.performBatchUpdates({ () -> Void in self.cellFakeView!.indexPath = toIndexPath self.cellFakeView!.cellFrame = attribute.frame self.cellFakeView!.changeBoundsIfNeeded(attribute.bounds) self.collectionView!.deleteItemsAtIndexPaths([atIndexPath!]) self.collectionView!.insertItemsAtIndexPaths([toIndexPath!]) // did move item self.delegate?.collectionView?(self.collectionView!, atIndexPath: atIndexPath!, didMoveToIndexPath: toIndexPath!) }, completion:nil) } internal func continuousScroll() { if self.cellFakeView == nil { return } let percentage: CGFloat = self.calcTrigerPercentage() var scrollRate: CGFloat = self.continuousScrollDirection.scrollValue(speedValue: self.scrollSpeedValue, percentage: percentage) let offset: CGFloat = self.offsetFromTop let insetTop: CGFloat = self.insetsTop let insetEnd: CGFloat = self.insetsEnd let length: CGFloat = self.collectionViewLength let contentLength: CGFloat = self.contentLength if contentLength + insetTop + insetEnd <= length { return } if offset + scrollRate <= -insetTop { scrollRate = -insetTop - offset }else if offset + scrollRate >= contentLength + insetEnd - length { scrollRate = contentLength + insetEnd - length - offset } self.collectionView!.performBatchUpdates({ () -> Void in if self.scrollDirection == .Vertical { self.fakeCellCenter?.y += scrollRate self.cellFakeView?.center.y = self.fakeCellCenter!.y + self.panTranslation!.y self.collectionView?.contentOffset.y += scrollRate }else { self.fakeCellCenter?.x += scrollRate self.cellFakeView?.center.x = self.fakeCellCenter!.x + self.panTranslation!.x self.collectionView?.contentOffset.x += scrollRate } }, completion: nil) self.moveItemIfNeeded() } private func calcTrigerPercentage() -> CGFloat { if self.cellFakeView == nil { return 0 } let offset = self.offsetFromTop let offsetEnd = self.offsetFromTop + self.collectionViewLength let insetTop = self.insetsTop _ = self.insetsEnd let trigerInsetTop = self.trigerInsetTop let trigerInsetEnd = self.trigerInsetEnd _ = self.trigerPaddingTop let paddingEnd = self.trigerPaddingEnd var percentage: CGFloat = 0 if self.continuousScrollDirection == .toTop { if let fakeCellEdge = self.fakeCellTopEdge { percentage = 1.0 - ((fakeCellEdge - (offset + trigerPaddingTop)) / trigerInsetTop) } }else if self.continuousScrollDirection == .toEnd { if let fakeCellEdge = self.fakeCellEndEdge { percentage = 1.0 - (((insetTop + offsetEnd - paddingEnd) - (fakeCellEdge + insetTop)) / trigerInsetEnd) } } percentage = min(1.0, percentage) percentage = max(0, percentage) return percentage } // gesture recognizers private func setUpGestureRecognizers() { if self.collectionView == nil { return } self.longPress = UILongPressGestureRecognizer(target: self, action: "handleLongPress:") self.panGesture = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") self.longPress?.delegate = self self.panGesture?.delegate = self self.panGesture?.maximumNumberOfTouches = 1 let gestures: NSArray! = self.collectionView?.gestureRecognizers gestures.enumerateObjectsUsingBlock { (gestureRecognizer, index, finish) -> Void in if gestureRecognizer is UILongPressGestureRecognizer { gestureRecognizer.requireGestureRecognizerToFail(self.longPress!) } self.collectionView?.addGestureRecognizer(self.longPress!) self.collectionView?.addGestureRecognizer(self.panGesture!) } } public func cancelDrag() { self.cancelDrag(toIndexPath: nil) } private func cancelDrag(toIndexPath toIndexPath: NSIndexPath!) { if self.cellFakeView == nil { return } // will end drag item self.delegate?.collectionView?(self.collectionView!, collectionViewLayout: self, willEndDraggingItemToIndexPath: toIndexPath) self.collectionView?.scrollsToTop = true self.fakeCellCenter = nil self.invalidateDisplayLink() self.cellFakeView!.pushBackView({ () -> Void in self.cellFakeView!.removeFromSuperview() self.cellFakeView = nil self.invalidateLayout() // did end drag item self.delegate?.collectionView?(self.collectionView!, collectionViewLayout: self, didEndDraggingItemToIndexPath: toIndexPath) }) } // long press gesture internal func handleLongPress(longPress: UILongPressGestureRecognizer!) { let location = longPress.locationInView(self.collectionView) var indexPath: NSIndexPath? = self.collectionView?.indexPathForItemAtPoint(location) if self.cellFakeView != nil { indexPath = self.cellFakeView!.indexPath } if indexPath == nil { return } switch longPress.state { case .Began: // will begin drag item self.delegate?.collectionView?(self.collectionView!, collectionViewLayout: self, willBeginDraggingItemAtIndexPath: indexPath!) self.collectionView?.scrollsToTop = false let currentCell: UICollectionViewCell? = self.collectionView?.cellForItemAtIndexPath(indexPath!) self.cellFakeView = RACellFakeView(cell: currentCell!) self.cellFakeView!.indexPath = indexPath self.cellFakeView!.originalCenter = currentCell?.center self.cellFakeView!.cellFrame = self.layoutAttributesForItemAtIndexPath(indexPath!)!.frame self.collectionView?.addSubview(self.cellFakeView!) self.fakeCellCenter = self.cellFakeView!.center self.invalidateLayout() self.cellFakeView!.pushFowardView() // did begin drag item self.delegate?.collectionView?(self.collectionView!, collectionViewLayout: self, didBeginDraggingItemAtIndexPath: indexPath!) case .Cancelled: fallthrough case .Ended: self.cancelDrag(toIndexPath: indexPath) default: break } } // pan gesture internal func handlePanGesture(pan: UIPanGestureRecognizer!) { self.panTranslation = pan.translationInView(self.collectionView!) if self.cellFakeView != nil && self.fakeCellCenter != nil && self.panTranslation != nil { switch pan.state { case .Changed: self.cellFakeView!.center.x = self.fakeCellCenter!.x + panTranslation!.x self.cellFakeView!.center.y = self.fakeCellCenter!.y + panTranslation!.y self.beginScrollIfNeeded() self.moveItemIfNeeded() case .Cancelled: fallthrough case .Ended: self.invalidateDisplayLink() default: break } } } // gesture recognize delegate public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { // allow move item let location = gestureRecognizer.locationInView(self.collectionView) if let indexPath = self.collectionView?.indexPathForItemAtPoint(location) { if self.delegate?.collectionView?(self.collectionView!, allowMoveAtIndexPath: indexPath) == false { return false } } if gestureRecognizer.isEqual(self.longPress) { if (self.collectionView!.panGestureRecognizer.state != .Possible && self.collectionView!.panGestureRecognizer.state != .Failed) { return false } }else if gestureRecognizer.isEqual(self.panGesture) { if (self.longPress!.state == .Possible || self.longPress!.state == .Failed) { return false } } return true } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isEqual(self.longPress) { if otherGestureRecognizer.isEqual(self.panGesture) { return true } }else if gestureRecognizer.isEqual(self.panGesture) { if otherGestureRecognizer.isEqual(self.longPress) { return true }else { return false } }else if gestureRecognizer.isEqual(self.collectionView?.panGestureRecognizer) { if (self.longPress!.state != .Possible || self.longPress!.state != .Failed) { return false } } return true } } private class RACellFakeView: UIView { weak var cell: UICollectionViewCell? var cellFakeImageView: UIImageView? var cellFakeHightedView: UIImageView? private var indexPath: NSIndexPath? private var originalCenter: CGPoint? private var cellFrame: CGRect? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(cell: UICollectionViewCell) { super.init(frame: cell.frame) self.cell = cell self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOffset = CGSizeMake(0, 0) self.layer.shadowOpacity = 0 self.layer.shadowRadius = 5.0 self.layer.shouldRasterize = false self.cellFakeImageView = UIImageView(frame: self.bounds) self.cellFakeImageView?.contentMode = UIViewContentMode.ScaleAspectFill self.cellFakeImageView?.autoresizingMask = [.FlexibleWidth , .FlexibleHeight] self.cellFakeHightedView = UIImageView(frame: self.bounds) self.cellFakeHightedView?.contentMode = UIViewContentMode.ScaleAspectFill self.cellFakeHightedView?.autoresizingMask = [.FlexibleWidth , .FlexibleHeight] cell.highlighted = true self.cellFakeHightedView?.image = getCellImage() cell.highlighted = false self.cellFakeImageView?.image = getCellImage() self.addSubview(self.cellFakeImageView!) self.addSubview(self.cellFakeHightedView!) } func changeBoundsIfNeeded(bounds: CGRect) { if CGRectEqualToRect(self.bounds, bounds) { return } UIView.animateWithDuration(0.3, delay: 0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: { () -> Void in self.bounds = bounds }, completion: nil) } func pushFowardView() { UIView.animateWithDuration(0.3, delay: 0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: { self.center = self.originalCenter! self.transform = CGAffineTransformMakeScale(1.1, 1.1) self.cellFakeHightedView!.alpha = 0; let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity") shadowAnimation.fromValue = 0 shadowAnimation.toValue = 0.7 shadowAnimation.removedOnCompletion = false shadowAnimation.fillMode = kCAFillModeForwards self.layer.addAnimation(shadowAnimation, forKey: "applyShadow") }, completion: { (finished) -> Void in self.cellFakeHightedView!.removeFromSuperview() }) } func pushBackView(completion: (()->Void)?) { UIView.animateWithDuration(0.3, delay: 0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: { self.transform = CGAffineTransformIdentity self.frame = self.cellFrame! let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity") shadowAnimation.fromValue = 0.7 shadowAnimation.toValue = 0 shadowAnimation.removedOnCompletion = false shadowAnimation.fillMode = kCAFillModeForwards self.layer.addAnimation(shadowAnimation, forKey: "removeShadow") }, completion: { (finished) -> Void in if completion != nil { completion!() } }) } private func getCellImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.cell!.bounds.size, false, UIScreen.mainScreen().scale * 2) self.cell!.drawViewHierarchyInRect(self.cell!.bounds, afterScreenUpdates: true) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
8bb8da7a5324993e246f4e1cc873eba3
38.102524
179
0.634449
5.594674
false
false
false
false
bgould/thrift
lib/swift/Sources/TList.swift
12
3821
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public struct TList<Element : TSerializable & Hashable> : RandomAccessCollection, MutableCollection, ExpressibleByArrayLiteral, TSerializable, Hashable { public typealias Storage = Array<Element> public typealias Indices = Storage.Indices internal var storage = Storage() public init() { } public init(arrayLiteral elements: Element...) { self.storage = Storage(elements) } public init<Source : Sequence>(_ sequence: Source) where Source.Iterator.Element == Element { storage = Storage(sequence) } /// Mark: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(storage) } /// Mark: TSerializable public static var thriftType : TType { return .list } public static func read(from proto: TProtocol) throws -> TList { let (elementType, size) = try proto.readListBegin() if elementType != Element.thriftType { throw TProtocolError(error: .invalidData, extendedError: .unexpectedType(type: elementType)) } var list = TList() for _ in 0..<size { let element = try Element.read(from: proto) list.storage.append(element) } try proto.readListEnd() return list } public func write(to proto: TProtocol) throws { try proto.writeListBegin(elementType: Element.thriftType, size: Int32(self.count)) for element in self.storage { try Element.write(element, to: proto) } try proto.writeListEnd() } /// Mark: MutableCollection public typealias SubSequence = Storage.SubSequence public typealias Index = Storage.Index public subscript(position: Storage.Index) -> Element { get { return storage[position] } set { storage[position] = newValue } } public subscript(range: Range<Index>) -> SubSequence { get { return storage[range] } set { storage[range] = newValue } } public var startIndex: Index { return storage.startIndex } public var endIndex: Index { return storage.endIndex } public func formIndex(after i: inout Index) { storage.formIndex(after: &i) } public func formIndex(before i: inout Int) { storage.formIndex(before: &i) } public func index(after i: Index) -> Index { return storage.index(after: i) } public func index(before i: Int) -> Int { return storage.index(before: i) } } extension TList : RangeReplaceableCollection { public mutating func replaceSubrange<C: Collection>(_ subrange: Range<Index>, with newElements: C) where C.Iterator.Element == Element { storage.replaceSubrange(subrange, with: newElements) } } extension TList : CustomStringConvertible, CustomDebugStringConvertible { public var description : String { return storage.description } public var debugDescription : String { return storage.debugDescription } } public func ==<Element>(lhs: TList<Element>, rhs: TList<Element>) -> Bool { return lhs.storage.elementsEqual(rhs.storage) { $0 == $1 } }
apache-2.0
149b3f9a47cf2a835d454ad911f7b9cc
27.729323
153
0.692489
4.391954
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/PresenterCard.swift
1
2908
/* * Copyright (C) 2015 - 2018, 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 PresenterCard: Card { /// A preset wrapper around presenterViewEdgeInsets. open var presenterViewEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { presenterViewEdgeInsets = EdgeInsetsPresetToValue(preset: presenterViewEdgeInsetsPreset) } } /// A reference to presenterViewEdgeInsets. @IBInspectable open var presenterViewEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the presenterView. @IBInspectable open var presenterView: UIView? { didSet { oldValue?.removeFromSuperview() if let v = presenterView { v.clipsToBounds = true container.addSubview(v) } layoutSubviews() } } open override func reload() { var h: CGFloat = 0 if let v = toolbar { h = prepare(view: v, with: toolbarEdgeInsets, from: h) } if let v = presenterView { h = prepare(view: v, with: presenterViewEdgeInsets, from: h) } if let v = contentView { h = prepare(view: v, with: contentViewEdgeInsets, from: h) } if let v = bottomBar { h = prepare(view: v, with: bottomBarEdgeInsets, from: h) } container.frame.size.height = h bounds.size.height = h } }
bsd-3-clause
ebbf7cd7a05370f3d313a5fc0996ebb8
32.813953
94
0.70564
4.508527
false
false
false
false
developerY/Active-Learning-Swift-2.0_DEMO
ActiveLearningSwift2.playground/Pages/Methods.xcplaygroundpage/Contents.swift
3
6855
//: [Previous](@previous) // ------------------------------------------------------------------------------------------------ // Things to know: // // * Methods can be in the form of Instance Methods, which apply to a given instance of a class // struct or enumeration and Type Methods, which apply to the type itself, like static methods // in C-like languages. // ------------------------------------------------------------------------------------------------ // Instance Methods // // Instance methods work on instances of a class, structure or enumeration. In order to call an // instance method, you must first instantiate the class, structure or enumeration and then place // the call on that instance. // // Here, we'll create a class with a single instance method: class SomeClass { func doSomething() { // ... } } // Since this should be pretty clear, let's jump into parameters for methods with internal and // external names. // // The defaults for external names are different for methods than they are for global functions. // // For methods, the default behavior is that the caller must always specify all but the first // external parameter name when calling the method. Member authors need not specify the external // names for those parameters as the default is to treat all parameters as if they had the "#" // specifier, which creates an external parameter name that mirrors the local parameter name. // // To override this default-external-names-for-second-and-beyond-parameters, specify an "_" as the // external parameter name for all but the first parameter. // // If you want the caller to also use external name for the first parameter, be sure to add your // own '#' symbol to the local name or specify the external name explicitly. // // Here's a class that exercises the various combinations of internal and external name usages: class Counter { var count = 0; // No parameters func increment() { count++ } // One parameter, no external parameter name needed by caller func incrementBy(amount: Int) { count += amount } // One parameter, overriding default behavior to requre caller to use external parameter name // on first (and only) parameter func addValueTo(value amount: Int) { count += amount } // Two parameters. Since no external names are specified, default behavior is implied: Caller // need not specify the first parameter's external name, but must specify all others: func addTwiceWithExternalImplied(first: Int, second: Int) { count += first count += second } // Two parameters. Using explicit external parameter names on all parameters to force caller // to use them for all parameters, including the first. func addTwiceWithExternalSpecified(a first: Int, b second: Int) { count += first count += second } // Two parameters. Using the external parameter shorthand ("#") to force caller to use // external parameter name on first parameter and defaulting to shared local/external names // for the rest. func addTwiceWithExternalSpecified2(#first: Int, second: Int) { count += first count += second } // Two parameters. Disabling all external names func addTwiceWithExternalSpecified3(first: Int, _ second: Int) { count += first count += second } } // Now let's see how we call each of those functions var counter = Counter() counter.increment() counter.incrementBy(4) counter.addValueTo(value: 4) counter.addTwiceWithExternalImplied(50, second: 4) counter.addTwiceWithExternalSpecified(a: 50, b: 4) counter.addTwiceWithExternalSpecified2(first: 10, second: 10) counter.addTwiceWithExternalSpecified3(10, 10) counter.count // The 'self' property refers to the current instance of a class, structure or enumeration. For // C++ developers, think of 'self' as 'this'. class Point { var x: Int = 10 func setX(x: Int) { // Using self to disambiguate from the local parameter self.x = x } } // ------------------------------------------------------------------------------------------------ // Mutation // // Instance methods cannot by default modify properties of structures or enumerations. To enable // this, mark them as 'mutating': struct Point2 { var x: Int = 10 // Note the need for the keyword 'mutating' mutating func setX(x: Int) { self.x = x } } // We'll create a constant Point2... let fixedPoint = Point2(x: 3) // Because 'fixedPoint' is constant, we are not allowed to call mutating memthods: // // The following line won't compile: // // fixedPoint.setX(4) // If you're working with a structure or enumeration (not a class), uou can assign to 'self' // directly struct Point3 { var x = 0 // This does not work with classes mutating func replaceMe(newX: Int) { self = Point3(x: 3) } } // Assigning to 'self' in an enumeration is used to change to a different member of the same // enumeration: enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case Off: self = Low case Low: self = High case High: self = Off } } } // ------------------------------------------------------------------------------------------------ // Type Methods // // Type methods are like C++'s static methods. // // They can only access Type members. struct LevelTracker { var currentLevel = 1 static var highestUnlockedLevel = 1 static func unlockedLevel(level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func levelIsUnlocked(level: Int) -> Bool { return level <= highestUnlockedLevel } mutating func advanceToLevel(level: Int) -> Bool { if LevelTracker.levelIsUnlocked(level) { currentLevel = level return true } else { return false } } } // To call a type method, use the type name, not the instance name: LevelTracker.levelIsUnlocked(3) // If we attempt to use an instance to call a type method, we'll get an error var levelTracker = LevelTracker() // The following line will not compile: // // levelTracker.levelIsUnlocked(3) // For classes, type methods use the 'class' keyword rather than the 'static' keyword: class SomeOtherClass { class func isGreaterThan100(value: Int) -> Bool { return value > 100 } } // We call class type methods with the type name just as we do for structures and enumerations: SomeOtherClass.isGreaterThan100(105) //: [Next](@next)
apache-2.0
ece854f97025f48d7b19d58742c47bb3
27.682008
99
0.627571
4.509868
false
false
false
false
tarunon/Barrel
Realm/Extensions.swift
1
1225
// // Extensions.swift // BarrelRealm // // Created by Nobuo Saito on 2015/11/10. // Copyright © 2015年 tarunon. All rights reserved. // import Foundation import RealmSwift import Barrel extension Object: ExpressionType { public typealias ValueType = Object } extension List: ExpressionType, ManyType { public typealias ValueType = List public typealias ElementType = ExpressionWrapper<T> } extension LinkingObjects: ExpressionType, ManyType { public typealias ValueType = LinkingObjects public typealias ElementType = ExpressionWrapper<T> } internal extension NSSortDescriptor { func toRealmObject() -> SortDescriptor { return SortDescriptor(keyPath: self.key!, ascending: ascending) } } public extension Realm { func objects<T>() -> Results<T> { return self.objects(T.self) } } public protocol RealmObjectType { } extension Object: RealmObjectType { } public extension RealmObjectType where Self: Object { public static func objects(_ realm: Realm) -> Results<Self> { return realm.objects() } public static func insert(_ realm: Realm) -> Self { let object = Self() realm.add(object) return object } }
mit
71927f7b1326af616b62b2eb2ad282f4
20.438596
71
0.694763
4.348754
false
false
false
false
hooman/swift
test/Interop/Cxx/implementation-only-imports/check-operator-visibility.swift
10
847
// RUN: %empty-directory(%t) // RUN: %target-swiftxx-frontend -emit-module -o %t/FortyTwo.swiftmodule -I %S/Inputs %s // Swift should consider all sources for a decl and recognize that the // decl is not hidden behind @_implementationOnly in all modules. // This test, as well as `check-operator-visibility-inversed.swift` checks // that the operator decl can be found when at least one of the // modules is not `@_implementationOnly`. @_implementationOnly import UserA import UserB // Operator `+` is a non-member function. @_inlineable public func addWrappers() { let wrapperA = MagicWrapper() let wrapperB = MagicWrapper() let _ = wrapperA + wrapperB } // Operator `-` is a member function. @_inlineable public func subtractWrappers() { var wrapperA = MagicWrapper() let wrapperB = MagicWrapper() let _ = wrapperA - wrapperB }
apache-2.0
dceb7f65a1a97c12233633fec3e751b0
29.25
88
0.726092
3.798206
false
false
false
false
PauloMigAlmeida/Signals
SwiftSignalKit/Queue.swift
1
2379
import Foundation private let _QueueSpecificKey = NSObject() private let QueueSpecificKey: UnsafePointer<Void> = UnsafePointer<Void>(Unmanaged<AnyObject>.passUnretained(_QueueSpecificKey).toOpaque()) public final class Queue { private let nativeQueue: dispatch_queue_t private var specific: UnsafeMutablePointer<Void> private let specialIsMainQueue: Bool public var queue: dispatch_queue_t { get { return self.nativeQueue } } public class func mainQueue() -> Queue { return Queue(queue: dispatch_get_main_queue(), specialIsMainQueue: true) } public class func concurrentDefaultQueue() -> Queue { return Queue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), specialIsMainQueue: false) } public class func concurrentBackgroundQueue() -> Queue { return Queue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), specialIsMainQueue: false) } public init(queue: dispatch_queue_t) { self.nativeQueue = queue self.specific = nil self.specialIsMainQueue = false } private init(queue: dispatch_queue_t, specialIsMainQueue: Bool) { self.nativeQueue = queue self.specific = nil self.specialIsMainQueue = specialIsMainQueue } public init() { self.nativeQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) self.specific = nil self.specialIsMainQueue = false self.specific = UnsafeMutablePointer<Void>(Unmanaged<Queue>.passUnretained(self).toOpaque()) dispatch_queue_set_specific(self.nativeQueue, QueueSpecificKey, self.specific, nil) } public func async(f: Void -> Void) { if self.specific != nil && dispatch_get_specific(QueueSpecificKey) == self.specific { f() } else if self.specialIsMainQueue && NSThread.isMainThread() { f() } else { dispatch_async(self.nativeQueue, f) } } public func dispatch(f: Void -> Void) { if self.specific != nil && dispatch_get_specific(QueueSpecificKey) == self.specific { f() } else if self.specialIsMainQueue && NSThread.isMainThread() { f() } else { dispatch_async(self.nativeQueue, f) } } }
mit
5e9723b4af777b565613c15f51f30d76
33.478261
138
0.639765
4.505682
false
false
false
false
primetimer/PrimeFactors
PrimeFactors/Classes/FactorCache.swift
1
6125
// // PrimeCache.swift // PFactors // // Created by Stephan Jancar on 20.10.17. // import Foundation import BigInt public class FactorCache { //static let strat = PrimeFactorStrategyAsync() //Much too slow private var pcache = NSCache<NSString, PrimeFactors>() static public var shared = FactorCache() private let first : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,71,73,79,83,89,97] private init() {} public func IsFactored(p: BigUInt) -> PrimeFactors? { if PrimeCache.shared.IsPrime(p: p) { return PrimeFactors(n: p) } //Already Factored in Cache? let nsstr = NSString(string: String(p.hashValue)) if let cachep = pcache.object(forKey: nsstr) { return cachep } return nil } public func Factor(p: BigUInt, cancel : CalcCancelProt?) -> PrimeFactors { var ans = PrimeFactors(n: p) if ans.unfactored == 1 { return ans } let nsstr = NSString(string: String(p.hashValue)) if let cachep = pcache.object(forKey: nsstr) { return cachep } //let factors = PrimeFactorStrategyAsync.shared.Factorize(n: p) let strat = PrimeFactorStrategy() ans = strat.Factorize(ninput: p, cancel: cancel) // let nsarr = NSFactorArray(f: factors) pcache.setObject(ans, forKey: nsstr) return ans } public func Sigma(p: BigUInt, cancel: CalcCancelProt?) -> BigUInt? { if p == 0 { return 0 } if p == 1 { return 1 } var (ret,produkt) = (BigUInt(1),BigUInt(1)) let factors = Factor(p: p, cancel: cancel) if factors.unfactored > 1 { return nil } let count = factors.factors.count if count == 0 { return ret } for i in 0..<count { produkt = produkt * factors.factors[i] if (i + 1 < count) && (factors.factors[i] == factors.factors [i+1]) { continue } ret = ret * ( produkt * (factors.factors[i]) - 1 ) / ((factors.factors[i]) - 1) produkt = BigUInt(1) } return ret } public func Divisors(p: BigUInt,cancel: CalcCancelProt?) -> [BigUInt] { let factors = Factor(p: p,cancel: cancel) if cancel?.IsCancelled() ?? false { return [1,p] } let c = factors.factors.count if c == 0 { return [BigUInt(1)] } factors.factors.sort() // for i in 0..<c { // print(i,":",factors.factors[i]) // } let d1 = factors.factors[0] var d1potenz : BigUInt = 1 var multiplicity = 0 while multiplicity < c { if factors.factors[multiplicity] != d1 { break } multiplicity = multiplicity + 1 d1potenz = d1potenz * d1 } //let ret : [UInt64] = [] if c > multiplicity { let p2 = p/d1potenz var ret = Divisors(p: p2,cancel: cancel) if cancel?.IsCancelled() ?? false { return [1,p] } let n = ret.count d1potenz = d1 for _ in 1...multiplicity { for i in 0..<n { ret.append(d1potenz*ret[i]) } d1potenz = d1potenz * d1 } return ret } var ret : [BigUInt] = [BigUInt(1)] d1potenz = 1 for _ in 1...multiplicity { d1potenz = d1 * d1potenz ret.append(d1potenz) } return ret } } public class FactorsWithPot { private (set) var factors : [FactorWithPot] private (set) var unfactored : BigUInt! private (set) var n : BigUInt! convenience init(n: BigUInt, cancel : CalcCancelProt?) { let pf = FactorCache.shared.Factor(p: n, cancel: cancel) self.init(pf: pf) } public init(pf : PrimeFactors) { self.unfactored = pf.unfactored factors = [] var pot = 1 for (index,f) in pf.factors.enumerated() { if index+1 == pf.factors.count { let fwithpot = FactorWithPot(f: f, e: pot) factors.append(fwithpot) } else { if f == pf.factors[index+1] { pot = pot + 1 } else { let fwithpot = FactorWithPot(f: f, e: pot) factors.append(fwithpot) pot = 1 } } } } } public struct FactorWithPot { public init(f: BigUInt) { self.f = f self.e = 1 } public init(f: BigUInt, e: Int) { self.f = f self.e = e } public var f: BigUInt = 0 public var e: Int = 0 } public extension FactorCache { public func Latex(n: BigUInt, withpot : Bool, cancel: CalcCancelProt?) -> String? { if n<2 { return nil } let factors = Factor(p: n,cancel: cancel) if cancel?.IsCancelled() ?? false { return nil } if factors.factors.count < 2 { return nil } var latex = String(n) + "=" if withpot { let fwithpots = FactorsWithPot(n: n, cancel: cancel) for (index,f) in fwithpots.factors.enumerated() { if index > 0 { latex = latex + "\\cdot{" } latex = latex + String(f.f) if f.e > 1 { latex = latex + "^{" + String(f.e) + "}" } if index>0 { latex = latex + "}" } } } else { for (index,f) in factors.factors.enumerated() { if index > 0 { latex = latex + "\\cdot{" } latex = latex + String(f) if index > 0 { latex = latex + "}" } } } if factors.unfactored > 1 { latex = latex + "\\cdot{?}" } //latex = latex + "\\\\" return latex } }
mit
bf6f1f56a0fe383a2ede04b3fe64371f
29.02451
104
0.487347
3.876582
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/AlamofireViewController.swift
2
2733
// // AlamofireViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/11/29. // Copyright © 2016年 Snail. All rights reserved. // import UIKit class AlamofireViewController: CustomViewController { let url = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json" @IBOutlet weak var aImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initView() } func initView() { navTitleLabel.text = "Alamofire" rightBtn.isHidden = false } override func rightAction() { upload() } func getData() { AlamofireManager.shared.request(url: url, SuccessHandler: { data in print(data) //TODO:把NSData转换成JSON let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : Any] //TODO:把JSON转换成NSData let tempData = try? JSONSerialization.data(withJSONObject: json ?? "", options: .prettyPrinted) print(json) }, FailureHandler: { error in print(error.localizedDescription) }) } func downloadImage() { let url = "https://httpbin.org/image/png" /* AlamofireManager.shared.request(url: url, SuccessHandler: {data in self.aImageView.image = UIImage(data: data) }, FailureHandler: {err in print("err---\(err)") }) */ print(NSHomeDirectory()) AlamofireManager.shared.download(url: url, SuccessHandler: {data in self.aImageView.image = UIImage(data: data) }, FailureHandler: {error in print("Error-----\(error)") }, ProgressHandler: {progress in print("Progress----\(progress)") }) } func upload() { let url = "https://httpbin.org/post" AlamofireManager.shared.upload(url: url) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
b9d864333db6a154d189591b046b0557
27.270833
141
0.587325
4.872531
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_034_Search_For_A_Range.swift
1
1340
/* https://leetcode.com/problems/search-for-a-range/ #34 Search for a Range Level: medium Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. Inspired by @stellari at https://leetcode.com/discuss/18242/clean-iterative-solution-binary-searches-with-explanation */ import Foundation struct Medium_034_Search_For_A_Range { static func searchRange(nums: [Int], target: Int) -> [Int] { var i: Int = 0 var j: Int = nums.count - 1 var result: [Int] = Array<Int>(repeating: -1, count: 2) while i < j { let mid: Int = (i+j)/2 if nums[mid] < target { i = mid + 1 } else { j = mid } } if nums[i] != target { return result } else { result[0] = i } j = nums.count - 1 while i < j { let mid: Int = (i+j)/2 + 1 if nums[mid] > target { j = mid - 1 } else { i = mid } } result[1] = j return result } }
mit
ff02015cd1d01f823c7ca9b47c71df9c
23.363636
117
0.516418
3.56383
false
false
false
false
iqingchen/DouYuZhiBo
DY/DY/Classes/Main/View/CollectionBaseCell.swift
1
1116
// // CollectionBaseCell.swift // DY // // Created by zhang on 16/12/5. // Copyright © 2016年 zhang. All rights reserved. // import UIKit import Kingfisher class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else {return} // 1.在线人数显示文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" } else { onlineStr = "\(anchor.online)在线" } onlineBtn.setTitle(onlineStr, for: UIControlState()) // 2.昵称的显示 nickNameLabel.text = anchor.nickname // 3.设置封面图片 guard let iconUrl = URL(string: anchor.vertical_src) else {return} iconImageView.kf.setImage(with: iconUrl) } } }
mit
8afbb4e717bb50e440598e5f0a81bb6c
27.351351
78
0.571973
4.482906
false
false
false
false
parthdubal/MyNewyorkTimes
MyNewyorkTimes/Common/Utility/Utility.swift
1
2764
// // Utility.swift // ContactApp // // Created by Parth on 01/04/17. // Copyright © 2017 Parth Dubal. All rights reserved. // import Foundation import UIKit import SVProgressHUD extension UIColor { class func RGB(_ red:CGFloat,green:CGFloat,blue:CGFloat,alpha:CGFloat = 1.0) -> UIColor { return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha) } } extension UIImageView{ func asyncImageDownload(url:String) -> Void { NetworkService.sharedServices().downloadImage(stringUrl: url) { (resultImage:UIImage?) in if let image = resultImage{ self.image = image } } } } extension NSError { class func serverError(errorMessage: String = "Server error occured") -> NSError { return NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [NSLocalizedDescriptionKey:errorMessage]) } } extension String { func isNumber() -> Bool { let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) if range == nil { return true } return false } func isStringEmpty() -> Bool { let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if str.isEmpty { return true } return false } } extension Date { static func stringToDate(stringDate:String,formate:String) -> Date? { let formatter = DateFormatter() formatter.dateFormat = formate formatter.timeZone = TimeZone(abbreviation: "UTC") let convertDate = formatter.date(from: stringDate) return convertDate } func shortDateTimeFormate() -> String { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium let convertString = formatter.string(from: self) return convertString } } extension UIView { func setBorder(color:UIColor) { self.layer.borderColor = color.cgColor self.layer.borderWidth = 1.0 } } extension SVProgressHUD { class func setHUDdesign() { SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.setBackgroundColor(UIColor.black) SVProgressHUD.setForegroundColor(UIColor.white); SVProgressHUD.setDefaultStyle(.dark) } class func showHUD(status: String = "Loading...") { SVProgressHUD.show(withStatus: status) } class func dismissHUD(error:String = "") { if error.isEmpty { SVProgressHUD.dismiss() } else { SVProgressHUD.showError(withStatus: error) } } }
mit
44561d557f5a6224ce1de2477691b54e
21.647541
123
0.613464
4.522095
false
false
false
false
adrfer/swift
test/decl/enum/enumtest.swift
1
7586
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Tests for various simple enum constructs //===----------------------------------------------------------------------===// public enum unionSearchFlags { case None case Backwards case Anchored init() { self = .None } } func test1() -> unionSearchFlags { let _ : unionSearchFlags var b = unionSearchFlags.None b = unionSearchFlags.Anchored _ = b return unionSearchFlags.Backwards } func test1a() -> unionSearchFlags { var _ : unionSearchFlags var b : unionSearchFlags = .None b = .Anchored _ = b // ForwardIndexType use of MaybeInt. _ = MaybeInt.None return .Backwards } func test1b(b : Bool) { _ = 123 _ = .description == 1 // expected-error{{type of expression is ambiguous without more context}} } enum MaybeInt { case None case Some(Int) init(_ i: Int) { self = MaybeInt.Some(i) } } func test2(a: Int, _ b: Int, _ c: MaybeInt) { _ = MaybeInt.Some(4) _ = MaybeInt.Some _ = MaybeInt.Some(b) test2(1, 2, .None) } enum ZeroOneTwoThree { case Zero case One(Int) case Two(Int, Int) case Three(Int,Int,Int) case Unknown(MaybeInt, MaybeInt, MaybeInt) init (_ i: Int) { self = .One(i) } init (_ i: Int, _ j: Int, _ k: Int) { self = .Three(i, j, k) } init (_ i: MaybeInt, _ j: MaybeInt, _ k: MaybeInt) { self = .Unknown(i, j, k) } } func test3(a: ZeroOneTwoThree) { _ = ZeroOneTwoThree.Three(1,2,3) _ = ZeroOneTwoThree.Unknown(MaybeInt.None, MaybeInt.Some(4), MaybeInt.Some(32)) _ = ZeroOneTwoThree(MaybeInt.None, MaybeInt(4), MaybeInt(32)) var _ : Int = ZeroOneTwoThree.Zero // expected-error {{cannot convert value of type 'ZeroOneTwoThree' to specified type 'Int'}} test3 ZeroOneTwoThree.Zero // expected-error {{expression resolves to an unused function}} expected-error{{consecutive statements}} {{8-8=;}} test3 (ZeroOneTwoThree.Zero) test3(ZeroOneTwoThree.Zero) test3 // expected-error {{expression resolves to an unused function}} (ZeroOneTwoThree.Zero) var _ : ZeroOneTwoThree = .One(4) var _ : (Int,Int) -> ZeroOneTwoThree = .Two // expected-error{{type '(Int, Int) -> ZeroOneTwoThree' has no member 'Two'}} var _ : Int = .Two // expected-error{{type 'Int' has no member 'Two'}} } func test3a(a: ZeroOneTwoThree) { var e : ZeroOneTwoThree = (.Three(1, 2, 3)) var f = ZeroOneTwoThree.Unknown(.None, .Some(4), .Some(32)) var g = .None // expected-error {{reference to member 'None' cannot be resolved without a contextual type}} // Overload resolution can resolve this to the right constructor. var h = ZeroOneTwoThree(1) test3a; // expected-error {{unused function}} .Zero // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}} test3a // expected-error {{unused function}} (.Zero) // expected-error {{type of expression is ambiguous without more context}} test3a(.Zero) } struct CGPoint { var x : Int, y : Int } typealias OtherPoint = ( x : Int, y : Int) func test4() { var a : CGPoint // Note: we reject the following because it conflicts with the current // "init" hack. var b = CGPoint.CGPoint(1, 2) // expected-error {{type 'CGPoint' has no member 'CGPoint'}} var c = CGPoint(x: 2, y : 1) // Using injected name. var e = CGPoint.x // expected-error {{member 'x' cannot be used on type 'CGPoint'}} var f = OtherPoint.x // expected-error {{type 'OtherPoint' (aka '(x: Int, y: Int)') has no member 'x'}} } struct CGSize { var width : Int, height : Int } extension CGSize { func area() -> Int { return width*self.height } func area_wrapper() -> Int { return area() } } struct CGRect { var origin : CGPoint, size : CGSize func area() -> Int { return self.size.area() } } func area(r: CGRect) -> Int { return r.size.area() } extension CGRect { func search(x: Int) -> CGSize {} func bad_search(_: Int) -> CGSize {} } func test5(myorigin: CGPoint) { let x1 = CGRect(origin: myorigin, size: CGSize(width: 42, height: 123)) let x2 = x1 4+5 // Dot syntax. _ = x2.origin.x _ = x1.size.area() _ = (r : x1.size).r.area() _ = x1.size.area() _ = (r : x1.size).r.area() _ = x1.area _ = x1.search(42) _ = x1.search(42).width // TODO: something like this (name binding on the LHS): // var (CGSize(width, height)) = CGSize(1,2) // TODO: something like this, how do we get it in scope in the {} block? //if (var Some(x) = somemaybeint) { ... } } struct StructTest1 { var a : Int, c, b : Int typealias ElementType = Int } enum UnionTest1 { case x case y(Int) func foo() {} init() { self = .x } } extension UnionTest1 { func food() {} func bar() {} // Type method. static func baz() {} } struct EmptyStruct { func foo() {} } func f() { let a : UnionTest1 a.bar() UnionTest1.baz() // dot syntax access to a static method. // Test that we can get the "address of a member". var _ : () -> () = UnionTest1.baz var _ : (UnionTest1) -> () -> () = UnionTest1.bar } func union_error(a: ZeroOneTwoThree) { var _ : ZeroOneTwoThree = .Zero(1) // expected-error {{contextual member 'Zero' has no associated value}} var _ : ZeroOneTwoThree = .One // expected-error {{contextual member 'One' expects argument of type 'Int'}} var _ : ZeroOneTwoThree = .foo // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} var _ : ZeroOneTwoThree = .foo() // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}} } func local_struct() { struct s { func y() {} } } //===----------------------------------------------------------------------===// // A silly units example showing "user defined literals". //===----------------------------------------------------------------------===// struct distance { var v : Int } func - (lhs: distance, rhs: distance) -> distance {} extension Int { func km() -> distance {} func cm() -> distance {} } func units(x: Int) -> distance { x.km() - 4.cm() - 42.km() } var %% : distance -> distance // expected-error {{expected pattern}} func badTupleElement() { typealias X = (x : Int, y : Int) var y = X.y // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'y'}} var z = X.z // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'z'}} } enum Direction { case North(distance: Int) case NorthEast(distanceNorth: Int, distanceEast: Int) } func testDirection() { var dir: Direction = .North(distance: 5) dir = .NorthEast(distanceNorth: 5, distanceEast: 7) var i: Int switch dir { case .North(let x): i = x break case .NorthEast(let x): i = x.distanceEast break } _ = i } enum NestedSingleElementTuple { case Case(x: (y: Int)) // expected-error{{cannot create a single-element tuple with an element label}} {{17-20=}} } enum SimpleEnum { case X, Y } func testSimpleEnum() { let _ : SimpleEnum = .X let _ : SimpleEnum = (.X) let _ : SimpleEnum=.X // expected-error {{'=' must have consistent whitespace on both sides}} } enum SR510: String { case Thing = "thing" case Bob = {"test"} // expected-error {{raw value for enum case must be a literal}} } // <rdar://problem/21269142> Diagnostic should say why enum has no .rawValue member enum E21269142 { // expected-note {{did you mean to specify a raw type on the enum declaration?}} case Foo } print(E21269142.Foo.rawValue) // expected-error {{value of type 'E21269142' has no member 'rawValue'}}
apache-2.0
c3e4ccb7964e4cc761ca6b26825ed7ae
23.872131
143
0.607698
3.531657
false
true
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/FlattenedScalars.swift
1
5056
// TODO: Move all these to Penguin. import _Differentiation import PenguinStructures public struct FlattenedScalars<Base: MutableCollection> where Base.Element: Vector { var base: Base init(_ base: Base) { self.base = base } } extension FlattenedScalars: Sequence { public typealias Element = Base.Element.Scalars.Element public struct Iterator: IteratorProtocol { var outer: Base.Iterator var inner: Base.Element.Scalars.Iterator? init(outer: Base.Iterator, inner: Base.Element.Scalars.Iterator? = nil) { self.outer = outer self.inner = inner } public mutating func next() -> Element? { while true { if let r = inner?.next() { return r } guard let o = outer.next() else { return nil } inner = o.scalars.makeIterator() } } } public func makeIterator() -> Iterator { Iterator(outer: base.makeIterator()) } // https://bugs.swift.org/browse/SR-13486 points out that the withContiguousStorageIfAvailable // method is dangerously underspecified, so we don't implement it here. public func _customContainsEquatableElement(_ e: Element) -> Bool? { let m = base.lazy.map({ $0.scalars._customContainsEquatableElement(e) }) if let x = m.first(where: { $0 != false }) { return x } return false } public __consuming func _copyContents( initializing t: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var r = 0 var outer = base.makeIterator() while r < t.count, let e = outer.next() { var (inner, r1) = e.scalars._copyContents( initializing: .init(start: t.baseAddress.map { $0 + r }, count: t.count - r)) r += r1 // See if we ran out of target space before reaching the end of the inner collection. I think // this will be rare, so instead of using an O(N) `e.count` and comparing with `r1` in all // passes of the outer loop, spend `inner` seeing if we reached the end and reconstitute it in // O(N) if not. if inner.next() != nil { @inline(never) func earlyExit() -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var i = e.scalars.makeIterator() for _ in 0..<r1 { _ = i.next() } return (.init(outer: outer, inner: i), r) } return earlyExit() } } return (.init(outer: outer, inner: nil), r) } } extension FlattenedScalars: MutableCollection { public typealias Index = FlattenedIndex<Base.Index, Base.Element.Scalars.Index> public var startIndex: Index { .init(firstValidIn: base, innerCollection: \.scalars) } public var endIndex: Index { .init(endIn: base) } public func index(after x: Index) -> Index { .init(nextAfter: x, in: base, innerCollection: \.scalars) } public func formIndex(after x: inout Index) { x.formNextValid(in: base, innerCollection: \.scalars) } public subscript(i: Index) -> Element { get { base[i.outer].scalars[i.inner!] } set { base[i.outer].scalars[i.inner!] = newValue } _modify { yield &base[i.outer].scalars[i.inner!] } } public var isEmpty: Bool { base.allSatisfy { $0.scalars.isEmpty } } public var count: Int { base.lazy.map(\.scalars.count).reduce(0, +) } /* TODO: implement or discard func _customIndexOfEquatableElement(_ element: Element) -> Index?? { } func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { } /// Returns an index that is the specified distance from the given index. func index(_ i: Index, offsetBy distance: Int) -> Index { } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { vtable[0].indexOffsetByLimitedBy(self, i, distance, limit) } /// Returns the distance between two indices. func distance(from start: Index, to end: Index) -> Int { vtable[0].distance(self, start, end) } // https://bugs.swift.org/browse/SR-13486 points out that these two // methods are dangerously underspecified, so we don't implement them here. public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { } /// Exchanges the values at the specified indices of the collection. public mutating func swapAt(_ i: Index, _ j: Index) { } */ }
apache-2.0
eac5b0638ca8a1d9076e3fcf5bbf1835
31.619355
100
0.660601
4.025478
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/UIViewAnimationViewController.swift
1
3811
import UIKit class UIViewAnimationViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.white let v1 = UIView() self.view.addSubview(v1) v1.translatesAutoresizingMaskIntoConstraints = false v1.widthAnchor.constraint(equalToConstant: 100).isActive = true v1.heightAnchor.constraint(equalToConstant: 100).isActive = true v1.backgroundColor = UIColor.blue v1.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true v1.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true UIView.animate(withDuration: 2, animations: { v1.backgroundColor = UIColor.red }) let v2 = UIView() self.view.addSubview(v2) v2.backgroundColor = UIColor.yellow v2.translatesAutoresizingMaskIntoConstraints = false v2.widthAnchor.constraint(equalToConstant: 100).isActive = true v2.heightAnchor.constraint(equalToConstant: 100).isActive = true v2.topAnchor.constraint(equalTo: v1.bottomAnchor).isActive = true v2.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true UIView.animate(withDuration: 2, animations: { v2.backgroundColor = UIColor.cyan v2.center.x += 100 }) let v3 = UIView() let v4 = UIView() self.view.addSubview(v3) self.view.addSubview(v4) v3.backgroundColor = UIColor.brown v4.backgroundColor = UIColor.black v3.translatesAutoresizingMaskIntoConstraints = false v4.translatesAutoresizingMaskIntoConstraints = false v3.widthAnchor.constraint(equalToConstant: 100).isActive = true v3.heightAnchor.constraint(equalToConstant: 100).isActive = true v4.widthAnchor.constraint(equalTo: v3.widthAnchor).isActive = true v4.heightAnchor.constraint(equalTo: v3.heightAnchor).isActive = true v3.topAnchor.constraint(equalTo: v2.bottomAnchor).isActive = true v3.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true v4.topAnchor.constraint(equalTo: v3.topAnchor).isActive = true v4.leftAnchor.constraint(equalTo: v3.leftAnchor).isActive = true v3.alpha = 1 v4.alpha = 0 UIView.animate(withDuration: 2, animations: { v4.alpha = 1 v3.alpha = 0 }) let v5 = UIView() v5.backgroundColor = UIColor.darkGray v5.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(v5) v5.widthAnchor.constraint(equalToConstant: 100).isActive = true v5.heightAnchor.constraint(equalToConstant: 100).isActive = true v5.topAnchor.constraint(equalTo: v3.bottomAnchor).isActive = true v5.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true UIView.animate(withDuration: 2, animations: { v5.backgroundColor = UIColor.green UIView.performWithoutAnimation{ v5.center.y += 100 } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
ca316ea82ffe69e662c8eab7f9b2632e
38.28866
106
0.65757
4.854777
false
false
false
false
wegenern/Toucan
ToucanPlayground.playground/section-1.swift
5
4069
// ToucanPlayground.playground // // Copyright (c) 2014 Gavin Bunney, Bunney Apps (http://bunney.net.au) // // 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 Toucan // // Toucan Playground! // // Note: Due to a current limitation in Xcode7, you need to first Build the // Toucan.framework for a 64bit device before running this playground :) // let portraitImage = UIImage(named: "Portrait.jpg") let landscapeImage = UIImage(named: "Landscape.jpg") let octagonMask = UIImage(named: "OctagonMask.png") // ------------------------------------------------------------ // Resizing // ------------------------------------------------------------ // Crop will resize to fit one dimension, then crop the other Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Crop).image // Clip will resize so one dimension is equal to the size, the other shrunk down to retain aspect ratio Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Clip).image // Scale will resize so the image fits exactly, altering the aspect ratio Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Scale).image // ------------------------------------------------------------ // Masking // ------------------------------------------------------------ let landscapeCropped = Toucan(image: landscapeImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Crop).image // We can mask with an ellipse! Toucan(image: landscapeImage!).maskWithEllipse().image // Demonstrate creating a circular mask -> resizes to a square image then mask with an ellipse Toucan(image: landscapeCropped).maskWithEllipse().image // Mask with borders too! Toucan(image: landscapeCropped).maskWithEllipse(borderWidth: 10, borderColor: UIColor.yellowColor()).image // Rounded Rects are all in style Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30).image // And can be fancy with borders Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30, borderWidth: 10, borderColor: UIColor.purpleColor()).image // Masking with an custom image mask Toucan(image: landscapeCropped).maskWithImage(maskImage: octagonMask!).image //testing the path stuff let path = UIBezierPath() path.moveToPoint(CGPointMake(0, 50)) path.addLineToPoint(CGPointMake(50, 0)) path.addLineToPoint(CGPointMake(100, 50)) path.addLineToPoint(CGPointMake(50, 100)) path.closePath() Toucan(image: landscapeCropped).maskWithPath(path: path).image Toucan(image: landscapeCropped).maskWithPathClosure(path: {(rect) -> (UIBezierPath) in return UIBezierPath(roundedRect: rect, cornerRadius: 50.0) }).image // ------------------------------------------------------------ // Layers // ------------------------------------------------------------ // We can draw ontop of another image Toucan(image: portraitImage!).layerWithOverlayImage(octagonMask!, overlayFrame: CGRectMake(450, 400, 200, 200)).image
mit
f4cd0ebdf27c5c7e10243ba9456945bd
41.831579
136
0.69796
4.551454
false
false
false
false
maximkhatskevich/MKHAPIClient
Sources/Core/Helpers.swift
1
1587
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //--- public typealias OnEncodeRequest = (URLRequest, Parameters?) -> Result<URLRequest, RequestEncodingIssue> //--- public enum HTTPHeaderFieldName: String { case authorization = "Authorization", contentType = "Content-Type" } //--- public enum ContentType: String { case formURLEncoded = "application/x-www-form-urlencoded; charset=utf-8" case json = "application/json" case plist = "application/x-plist" }
mit
cf03a4803823c2ed334e3994f9833d6f
29.519231
97
0.759294
4.547278
false
false
false
false
lfaoro/Cast
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift
1
1873
// // SubscribeOn.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class SubscribeOnSink<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.E typealias Parent = SubscribeOn<Element> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { observer?.on(event) if event.isStopEvent { self.dispose() } } func run() -> Disposable { let disposeEverything = SerialDisposable() let cancelSchedule = SingleAssignmentDisposable() disposeEverything.disposable = cancelSchedule let scheduleResult = parent.scheduler.schedule(()) { (_) -> RxResult<Disposable> in let subscription = self.parent.source.subscribeSafe(self) disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) return NopDisposableResult } cancelSchedule.disposable = getScheduledDisposable(scheduleResult) return disposeEverything } } class SubscribeOn<Element> : Producer<Element> { let source: Observable<Element> let scheduler: ImmediateScheduler init(source: Observable<Element>, scheduler: ImmediateScheduler) { self.source = source self.scheduler = scheduler } override func run<O : ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
df2478ea926b79b17448ccacff532019
29.225806
140
0.644955
4.778061
false
false
false
false
malcommac/CircularScrollView
Example/CircularScrollView/ViewController.swift
1
2467
// // ViewController.swift // CircularScrollView // // Created by daniele margutti on 06/03/2015. // Copyright (c) 06/03/2015 daniele margutti. All rights reserved. // import UIKit import CircularScrollView class ViewController: UIViewController, CircularScrollViewDataSource,CircularScrollViewDelegate { var circularControl : CircularScrollView? var backColors : [UIColor]! var viewControllers : [AnyObject] var numberOfPages: Int override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { backColors = [ UIColor.yellowColor(),UIColor.orangeColor(),UIColor.redColor(),UIColor.blueColor(),UIColor.cyanColor(),UIColor.lightGrayColor()] numberOfPages = count(backColors) viewControllers = [] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { backColors = [ UIColor.yellowColor(),UIColor.orangeColor(),UIColor.redColor(),UIColor.blueColor(),UIColor.cyanColor(),UIColor.lightGrayColor()] numberOfPages = count(backColors) viewControllers = [] super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() for (var x = 0; x < numberOfPages; ++x) { self.viewControllers.append(NSNull()) } circularControl = CircularScrollView(frame: self.view.bounds) self.view.addSubview(circularControl!) circularControl?.delegate = self circularControl?.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfPagesInCircularScrollView(#scroll: CircularScrollView!) -> Int! { return count(backColors!) } func circularScrollView(#scroll: CircularScrollView!, viewControllerAtIndex index: Int!) -> UIViewController! { return self.viewControllerAtIndex(index) } private func viewControllerAtIndex(index: Int!) -> UIViewController! { var item : AnyObject? = viewControllers[index] if let item = item as? UIViewController { return item } else { var vc = UIViewController() vc.view.backgroundColor = backColors[index] vc.view.frame = circularControl!.bounds let label = UILabel() label.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight label.frame = vc.view.bounds label.font = UIFont.systemFontOfSize(40) label.textAlignment = NSTextAlignment.Center label.text = "#\(index)" vc.view.addSubview(label) viewControllers[index] = vc return vc } } }
mit
a164aeed7209de7f5d63760e432eb0ea
29.8375
145
0.738143
4.246127
false
false
false
false
breadwallet/breadwallet-ios
breadwalletTests/BRReplicatedKVStoreTests.swift
1
14303
// // BRReplicatedKVStoreTests.swift // breadwallet // // Created by Samuel Sutch on 12/7/16. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import XCTest @testable import breadwallet import WalletKit class BRReplicatedKVStoreTestAdapter: BRRemoteKVStoreAdaptor { let testCase: XCTestCase var db = [String: (UInt64, Date, [UInt8], Bool)]() init(testCase: XCTestCase) { self.testCase = testCase } func keys(_ completionFunc: @escaping ([(String, UInt64, Date, BRRemoteKVStoreError?)], BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] KEYS") DispatchQueue.main.async { let res = self.db.map { (t) -> (String, UInt64, Date, BRRemoteKVStoreError?) in return (t.0, t.1.0, t.1.1, t.1.3 ? BRRemoteKVStoreError.tombstone : nil) } completionFunc(res, nil) } } func ver(key: String, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] VER \(key)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), .notFound) } completionFunc(obj.0, obj.1, obj.3 ? .tombstone : nil) } } func get(_ key: String, version: UInt64, completionFunc: @escaping (UInt64, Date, [UInt8], BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] GET \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), [], .notFound) } if version != obj.0 { return completionFunc(0, Date(), [], .conflict) } completionFunc(obj.0, obj.1, obj.2, obj.3 ? .tombstone : nil) } } func put(_ key: String, value: [UInt8], version: UInt64, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] PUT \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { if version != 1 { return completionFunc(1, Date(), .notFound) } let newObj = (UInt64(1), Date(), value, false) self.db[key] = newObj return completionFunc(1, newObj.1, nil) } if version != obj.0 { return completionFunc(0, Date(), .conflict) } let newObj = (obj.0 + 1, Date(), value, false) self.db[key] = newObj completionFunc(newObj.0, newObj.1, nil) } } func del(_ key: String, version: UInt64, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] DEL \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), .notFound) } if version != obj.0 { return completionFunc(0, Date(), .conflict) } let newObj = (obj.0 + 1, Date(), obj.2, true) self.db[key] = newObj completionFunc(newObj.0, newObj.1, nil) } } } class BRReplicatedKVStoreTest: XCTestCase { var store: BRReplicatedKVStore! var key: Key { let privKey = "S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy" return Key.createFromString(asPrivate: privKey)! } var adapter: BRReplicatedKVStoreTestAdapter! override func setUp() { super.setUp() adapter = BRReplicatedKVStoreTestAdapter(testCase: self) adapter.db["hello"] = (1, Date(), [0, 1], false) adapter.db["removed"] = (2, Date(), [0, 2], true) for i in 1...20 { adapter.db["testkey-\(i)"] = (1, Date(), [0, UInt8(i + 2)], false) } store = try! BRReplicatedKVStore(encryptionKey: key, remoteAdaptor: adapter) store.encryptedReplication = false } override func tearDown() { super.tearDown() try! BRReplicatedKVStore.rmdb() store = nil } func XCTAssertDatabasesAreSynced() { // this only works for keys that are not marked deleted var remoteKV = [String: [UInt8]]() for (k, v) in adapter.db { if !v.3 { remoteKV[k] = v.2 } } let allLocalKeys = try! store.localKeys() var localKV = [String: [UInt8]]() for i in allLocalKeys { if !i.4 { localKV[i.0] = try! store.get(i.0).3 } } for (k, v) in remoteKV { XCTAssertEqual(v, localKV[k] ?? []) } for (k, v) in localKV { XCTAssertEqual(v, remoteKV[k] ?? []) } } // MARK: - local db tests func testSetLocalDoesntThrow() { let (v1, t1) = try! store.set("hello", value: [0, 0, 0], localVer: 0) XCTAssertEqual(1, v1) XCTAssertNotNil(t1) } func testSetLocalIncrementsVersion() { _ = try! store.set("hello", value: [0, 1], localVer: 0) XCTAssertEqual(try! store.localVersion("hello").0, 1) } func testSetThenGet() { let (v1, t1) = try! store.set("hello", value: [0, 1], localVer: 0) let (v, t, d, val) = try! store.get("hello") XCTAssertEqual(val, [0, 1]) XCTAssertEqual(v1, v) XCTAssertEqual(t1.timeIntervalSince1970, t.timeIntervalSince1970, accuracy: 0.001) XCTAssertEqual(d, false) } func testSetThenSetIncrementsVersion() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (v2, _) = try! store.set("hello", value: [0, 2], localVer: v1) XCTAssertEqual(v2, v1 + UInt64(1)) } func testSetThenDel() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (v2, _) = try! store.del("hello", localVer: v1) XCTAssertEqual(v2, v1 + UInt64(1)) } func testSetThenDelThenGet() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) _ = try! store.del("hello", localVer: v1) let (v2, _, d, _) = try! store.get("hello") XCTAssert(d) XCTAssertEqual(v2, v1 + UInt64(1)) } func testSetWithIncorrectFirstVersionFails() { XCTAssertThrowsError(try store.set("hello", value: [0, 1], localVer: 1)) } func testSetWithStaleVersionFails() { _ = try! store.set("hello", value: [0, 1], localVer: 0) XCTAssertThrowsError(try store.set("hello", value: [0, 1], localVer: 0)) } func testGetNonExistentKeyFails() { XCTAssertThrowsError(try store.get("hello")) } func testGetNonExistentKeyVersionFails() { XCTAssertThrowsError(try store.get("hello", version: 1)) } func testGetAllKeys() { let (v1, t1) = try! store.set("hello", value: [0, 1], localVer: 0) let lst = try! store.localKeys() XCTAssertEqual(1, lst.count) XCTAssertEqual("hello", lst[0].0) XCTAssertEqual(v1, lst[0].1) XCTAssertEqual(t1.timeIntervalSince1970, lst[0].2.timeIntervalSince1970, accuracy: 0.001) XCTAssertEqual(0, lst[0].3) XCTAssertEqual(false, lst[0].4) } func testSetRemoteVersion() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (newV, _) = try! store.setRemoteVersion(key: "hello", localVer: v1, remoteVer: 1) XCTAssertEqual(newV, v1 + UInt64(1)) let rmv = try! store.remoteVersion("hello") XCTAssertEqual(rmv, 1) } // MARK: - syncing tests func testBasicSyncGetAllObjects() { let exp = expectation(description: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(timeout: 1, handler: nil) let allKeys = try! store.localKeys() XCTAssertEqual(adapter.db.count - 1, allKeys.count) // minus 1: there is a deleted key that needent be synced XCTAssertDatabasesAreSynced() } func testSyncTenTimes() { let exp = expectation(description: "sync") var n = 10 var handler: (_ e: Error?) -> () = { e in return } handler = { (e: Error?) in XCTAssertNil(e) if n > 0 { self.store.syncAllKeys(handler) n -= 1 } else { exp.fulfill() } } handler(nil) waitForExpectations(timeout: 2, handler: nil) XCTAssertDatabasesAreSynced() } func testSyncAddsLocalKeysToRemote() { store.syncImmediately = false _ = try! store.set("derp", value: [0, 1], localVer: 0) let exp = expectation(description: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(adapter.db["derp"]!.2, [0, 1]) XCTAssertDatabasesAreSynced() } func testSyncSavesRemoteVersion() { let exp = expectation(description: "sync") store.syncAllKeys { err in XCTAssertNil(err) exp.fulfill() } waitForExpectations(timeout: 1, handler: nil) let rv = try! store.remoteVersion("hello") XCTAssertEqual(adapter.db["hello"]!.0, 1) // it should not have done any mutations XCTAssertEqual(adapter.db["hello"]!.0, UInt64(rv)) // only saved the remote version XCTAssertDatabasesAreSynced() } func testSyncPreventsAnotherConcurrentSync() { let exp1 = expectation(description: "sync") let exp2 = expectation(description: "sync2") store.syncAllKeys { e in exp1.fulfill() } store.syncAllKeys { (e) in XCTAssertEqual(e, BRReplicatedKVStoreError.alreadyReplicating) exp2.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testLocalDeleteReplicates() { let exp1 = expectation(description: "sync1") store.syncImmediately = false _ = try! store.set("goodbye_cruel_world", value: [0, 1], localVer: 0) store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() _ = try! store.del("goodbye_cruel_world", localVer: try! store.localVersion("goodbye_cruel_world").0) let exp2 = expectation(description: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() XCTAssertEqual(adapter.db["goodbye_cruel_world"]!.3, true) } func testLocalUpdateReplicates() { let exp1 = expectation(description: "sync1") store.syncImmediately = false _ = try! store.set("goodbye_cruel_world", value: [0, 1], localVer: 0) store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() _ = try! store.set("goodbye_cruel_world", value: [1, 0, 0, 1], localVer: try! store.localVersion("goodbye_cruel_world").0) let exp2 = expectation(description: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testRemoteDeleteReplicates() { let exp1 = expectation(description: "sync1") store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() adapter.db["hello"]?.0 += 1 adapter.db["hello"]?.1 = Date() adapter.db["hello"]?.3 = true let exp2 = expectation(description: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() let (_, _, h, _) = try! store.get("hello") XCTAssertEqual(h, true) let exp3 = expectation(description: "sync3") store.syncAllKeys { (e) in XCTAssertNil(e) exp3.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testRemoteUpdateReplicates() { let exp1 = expectation(description: "sync1") store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() adapter.db["hello"]?.0 += 1 adapter.db["hello"]?.1 = Date() adapter.db["hello"]?.2 = [0, 1, 1, 1, 1, 1, 11 , 1, 1, 1, 1, 1, 0x8c] let exp2 = expectation(description: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() let (_, _, _, b) = try! store.get("hello") XCTAssertEqual(b, [0, 1, 1, 1, 1, 1, 11 , 1, 1, 1, 1, 1, 0x8c]) let exp3 = expectation(description: "sync3") store.syncAllKeys { (e) in XCTAssertNil(e) exp3.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testEnableEncryptedReplication() { adapter.db.removeAll() store.encryptedReplication = true _ = try! store.set("derp", value: [0, 1], localVer: 0) let exp = expectation(description: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(timeout: 1, handler: nil) XCTAssertNotEqual(adapter.db["derp"]!.2, [0, 1]) } }
mit
ea208cc7ccd26e5e0a4b3f7cde5bdd77
34.844612
133
0.558663
3.914067
false
true
false
false
MobileToolkit/Tesseract
Tesseract/RestfulClient+DELETE.swift
2
1248
// // RestfulClient+DELETE.swift // Tesseract // // Created by Sebastian Owodzin on 08/09/2015. // Copyright © 2015 mobiletoolkit.org. All rights reserved. // import Foundation extension RestfulClient { public func DELETE<T where T: RestfulCollection, T: RestfulCollectionObject>(objectType: T.Type, objectID: AnyObject, completionHandler: (NSError?) -> Void) { let request = NSMutableURLRequest(URL: RestfulClient.buildEndpointURL(objectType.collectionObjectURIPath(), uriParams: URIParams(attributes: [objectType.collectionObjectIDAttribute(): objectID], queryParams: nil))!) request.HTTPMethod = "DELETE" let dataTask = urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in if let error = error { completionHandler(error) } else { let httpResponse = response as! NSHTTPURLResponse if 204 == httpResponse.statusCode { completionHandler(nil) } else { completionHandler(RestfulClient.buildTesseractError(.DELETE, response: httpResponse, responseData: data)) } } } dataTask.resume() } }
mit
78d40d233a1f9bbbe67a0df81e8fb493
36.787879
223
0.632719
4.909449
false
false
false
false
brentdax/swift
stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift
4
43461
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import StdlibUnittest // These tests are shared between partition(by:) and sort(). public struct PartitionExhaustiveTest { public let sequence: [Int] public let loc: SourceLoc public init( _ sequence: [Int], file: String = #file, line: UInt = #line ) { self.sequence = sequence self.loc = SourceLoc(file, line, comment: "test data") } } enum SillyError : Error { case JazzHands } public let partitionExhaustiveTests = [ PartitionExhaustiveTest([]), PartitionExhaustiveTest([ 10 ]), PartitionExhaustiveTest([ 10, 10 ]), PartitionExhaustiveTest([ 10, 20 ]), PartitionExhaustiveTest([ 10, 10, 10 ]), PartitionExhaustiveTest([ 10, 10, 20 ]), PartitionExhaustiveTest([ 10, 20, 20 ]), PartitionExhaustiveTest([ 10, 20, 30 ]), PartitionExhaustiveTest([ 10, 10, 10, 10 ]), PartitionExhaustiveTest([ 10, 10, 10, 20 ]), PartitionExhaustiveTest([ 10, 10, 20, 20 ]), PartitionExhaustiveTest([ 10, 20, 30, 40 ]), PartitionExhaustiveTest([ 10, 10, 10, 10, 10 ]), PartitionExhaustiveTest([ 10, 10, 10, 20, 20 ]), PartitionExhaustiveTest([ 10, 10, 10, 20, 30 ]), PartitionExhaustiveTest([ 10, 10, 20, 20, 30 ]), PartitionExhaustiveTest([ 10, 10, 20, 30, 40 ]), PartitionExhaustiveTest([ 10, 20, 30, 40, 50 ]), PartitionExhaustiveTest([ 10, 20, 30, 40, 50, 60 ]), ] //Random collection of 30 elements public let largeElementSortTests = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [30, 29, 28, 27, 26, 25, 20, 19, 18, 5, 4, 3, 2, 1, 15, 14, 13, 12, 11, 10, 9, 24, 23, 22, 21, 8, 17, 16, 7, 6], [30, 29, 25, 20, 19, 18, 5, 4, 3, 2, 1, 28, 27, 26, 15, 14, 13, 12, 24, 23, 22, 21, 8, 17, 16, 7, 6, 11, 10, 9], [3, 2, 1, 20, 19, 18, 5, 4, 28, 27, 26, 11, 10, 9, 15, 14, 13, 12, 24, 23, 22, 21, 8, 17, 16, 7, 6, 30, 29, 25], ] public func withInvalidOrderings(_ body: (@escaping (Int, Int) -> Bool) -> Void) { // Test some ordering predicates that don't create strict weak orderings body { (_,_) in true } body { (_,_) in false } var i = 0 body { (_,_) in defer {i += 1}; return i % 2 == 0 } body { (_,_) in defer {i += 1}; return i % 3 == 0 } body { (_,_) in defer {i += 1}; return i % 5 == 0 } } internal func _mapInPlace<C : MutableCollection>( _ elements: inout C, _ transform: (C.Element) -> C.Element ) { for i in elements.indices { elements[i] = transform(elements[i]) } } internal func makeBufferAccessLoggingMutableCollection< C >(wrapping c: C) -> BufferAccessLoggingMutableBidirectionalCollection<C> { return BufferAccessLoggingMutableBidirectionalCollection(wrapping: c) } internal func makeBufferAccessLoggingMutableCollection< C >(wrapping c: C) -> BufferAccessLoggingMutableRandomAccessCollection<C> { return BufferAccessLoggingMutableRandomAccessCollection(wrapping: c) } extension TestSuite { public func addMutableCollectionTests< C : MutableCollection, CollectionWithEquatableElement : MutableCollection, CollectionWithComparableElement : MutableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), makeCollectionOfComparable: @escaping ([CollectionWithComparableElement.Element]) -> CollectionWithComparableElement, wrapValueIntoComparable: @escaping (MinimalComparableValue) -> CollectionWithComparableElement.Element, extractValueFromComparable: @escaping ((CollectionWithComparableElement.Element) -> MinimalComparableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, withUnsafeMutableBufferPointerIsSupported: Bool, isFixedLengthCollection: Bool, collectionIsBidirectional: Bool = false ) where CollectionWithEquatableElement.Element : Equatable, CollectionWithComparableElement.Element : Comparable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional ) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } func makeWrappedCollectionWithComparableElement( _ elements: [MinimalComparableValue] ) -> CollectionWithComparableElement { return makeCollectionOfComparable(elements.map(wrapValueIntoComparable)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // subscript(_: Index) //===----------------------------------------------------------------------===// if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .none { self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/NonEmpty/Set") { var c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) c[index] = wrapValue(OpaqueValue(9999)) } self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/Empty/Set") { var c = makeWrappedCollection([]) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) c[index] = wrapValue(OpaqueValue(9999)) } let tests = cartesianProduct( subscriptRangeTests, _SubSequenceSubscriptOnIndexMode.all) self.test("\(testNamePrefix).SubSequence.subscript(_: Index)/Set/OutOfBounds") .forEach(in: tests) { (test, mode) in let elements = test.collection let sliceFromLeft = test.bounds.lowerBound let sliceFromRight = elements.count - test.bounds.upperBound print("\(elements)/sliceFromLeft=\(sliceFromLeft)/sliceFromRight=\(sliceFromRight)") let base = makeWrappedCollection(elements) let sliceStartIndex = base.index(base.startIndex, offsetBy: numericCast(sliceFromLeft)) let sliceEndIndex = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) var slice = base[sliceStartIndex..<sliceEndIndex] expectType(C.SubSequence.self, &slice) var index: C.Index = base.startIndex switch mode { case .inRange: let sliceNumericIndices = sliceFromLeft..<(elements.count - sliceFromRight) for (i, index) in base.indices.enumerated() { if sliceNumericIndices.contains(i) { slice[index] = wrapValue(OpaqueValue(elements[i].value + 90000)) } } for (i, index) in base.indices.enumerated() { if sliceNumericIndices.contains(i) { expectEqual( elements[i].value + 90000, extractValue(slice[index]).value) expectEqual( extractValue(base[index]).value + 90000, extractValue(slice[index]).value) } } return case .outOfRangeToTheLeft: if sliceFromLeft == 0 { return } index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) case .outOfRangeToTheRight: if sliceFromRight == 0 { return } index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) case .baseEndIndex: index = base.endIndex case .sliceEndIndex: index = sliceEndIndex } expectCrashLater() slice[index] = wrapValue(OpaqueValue(9999)) } } //===----------------------------------------------------------------------===// // subscript(_: Range) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).subscript(_: Range)/Set/semantics") { for test in subscriptRangeTests { var expectedCollection = test.collection _mapInPlace(&expectedCollection[test.bounds(in: expectedCollection)]) { OpaqueValue($0.value + 90000) } do { // Call setter with new elements coming from a different collection. var c = makeWrappedCollection(test.collection) let newElements = makeWrappedCollection( test.expected.map { OpaqueValue($0.value + 90000) }) c[test.bounds(in: c)] = newElements[...] // FIXME: improve checkForwardCollection to check the SubSequence type. /* // TODO: swift-3-indexing-model: uncomment the following. checkForwardCollection( expectedCollection.map(wrapValue), c, resiliencyChecks: .none) { extractValue($0).value == extractValue($1).value } */ } do { // Call setter implicitly through an inout mutation. var c = makeWrappedCollection(test.collection) var s = c[test.bounds(in: c)] _mapInPlace(&s) { wrapValue(OpaqueValue(extractValue($0).value + 90000)) } // FIXME: improve checkForwardCollection to check the SubSequence type. /* // TODO: swift-3-indexing-model: uncomment the following. checkForwardCollection( expectedCollection.map(wrapValue), c, resiliencyChecks: .none) { extractValue($0).value == extractValue($1).value } */ } } } if isFixedLengthCollection { self.test("\(testNamePrefix).subscript(_: Range)/Set/LargerRange") { var c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) let newElements = makeWrappedCollection([ 91010, 92020, 93030, 94040 ].map(OpaqueValue.init)) expectCrashLater() c[...] = newElements[...] } self.test("\(testNamePrefix).subscript(_: Range)/Set/SmallerRange") { var c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) let newElements = makeWrappedCollection([ 91010, 92020 ].map(OpaqueValue.init)) expectCrashLater() c[...] = newElements[...] } } else { self.test("\(testNamePrefix).subscript(_: Range)/Set/DifferentlySizedRange") { for test in replaceRangeTests { var c = makeWrappedCollection(test.collection) let newElements = makeWrappedCollection(test.newElements) let rangeToReplace = test.rangeSelection.range(in: c) c[rangeToReplace] = newElements[...] expectEqualSequence( test.expected, c.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } } if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .none { let tests = cartesianProduct( subscriptRangeTests, _SubSequenceSubscriptOnRangeMode.all) self.test("\(testNamePrefix).SubSequence.subscript(_: Range)/Set/OutOfBounds") .forEach(in: tests) { (test, mode) in let elements = test.collection let sliceFromLeft = test.bounds.lowerBound let sliceFromRight = elements.count - test.bounds.upperBound print("\(elements)/sliceFromLeft=\(sliceFromLeft)/sliceFromRight=\(sliceFromRight)") let base = makeWrappedCollection(elements) let sliceStartIndex = base.index(base.startIndex, offsetBy: numericCast(sliceFromLeft)) let sliceEndIndex = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) var slice = base[sliceStartIndex..<sliceEndIndex] expectType(C.SubSequence.self, &slice) var bounds: Range<C.Index> = base.startIndex..<base.startIndex switch mode { case .inRange: let sliceNumericIndices = sliceFromLeft..<(elements.count - sliceFromRight + 1) for (i, subSliceStartIndex) in base.indices.enumerated() { for (j, subSliceEndIndex) in base.indices.enumerated() { if i <= j && sliceNumericIndices.contains(i) && sliceNumericIndices.contains(j) { let newValues = makeWrappedCollection( elements[i..<j].map { OpaqueValue($0.value + 90000) } ) slice[subSliceStartIndex..<subSliceEndIndex] = newValues[...] let subSlice = slice[subSliceStartIndex..<subSliceEndIndex] for (k, index) in subSlice.indices.enumerated() { expectEqual( elements[i + k].value + 90000, extractValue(subSlice[index]).value) expectEqual( extractValue(base[index]).value + 90000, extractValue(subSlice[index]).value) expectEqual( extractValue(slice[index]).value, extractValue(subSlice[index]).value) } let oldValues = makeWrappedCollection(Array(elements[i..<j])) slice[subSliceStartIndex..<subSliceEndIndex] = oldValues[...] } } } return case .outOfRangeToTheLeftEmpty: if sliceFromLeft == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) bounds = index..<index break case .outOfRangeToTheLeftNonEmpty: if sliceFromLeft == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) bounds = index..<sliceStartIndex break case .outOfRangeToTheRightEmpty: if sliceFromRight == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) bounds = index..<index break case .outOfRangeToTheRightNonEmpty: if sliceFromRight == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) bounds = sliceEndIndex..<index break case .outOfRangeBothSides: if sliceFromLeft == 0 { return } if sliceFromRight == 0 { return } bounds = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) ..< base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) break case .baseEndIndex: if sliceFromRight == 0 { return } bounds = sliceEndIndex..<base.endIndex break } let count: Int = numericCast( base.distance(from: bounds.lowerBound, to: bounds.upperBound)) let newValues = makeWrappedCollection(Array(elements[0..<count])) let newSlice = newValues[...] expectCrashLater() slice[bounds] = newSlice } } //===----------------------------------------------------------------------===// // _withUnsafeMutableBufferPointerIfSupported() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix)._withUnsafeMutableBufferPointerIfSupported()/semantics") { for test in subscriptRangeTests { var c = makeWrappedCollection(test.collection) var result = c._withUnsafeMutableBufferPointerIfSupported { (bufferPointer) -> OpaqueValue<Array<OpaqueValue<Int>>> in let value = OpaqueValue(bufferPointer.map(extractValue)) return value } expectType(Optional<OpaqueValue<Array<OpaqueValue<Int>>>>.self, &result) if withUnsafeMutableBufferPointerIsSupported { expectEqualSequence(test.collection, result!.value) { $0.value == $1.value } } else { expectNil(result) } } } //===----------------------------------------------------------------------===// // sort() //===----------------------------------------------------------------------===// func checkSortedPredicateThrow( sequence: [Int], lessImpl: ((Int, Int) -> Bool), throwIndex: Int ) { let extract = extractValue let throwElement = sequence[throwIndex] var thrown = false let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } var result: [C.Element] = [] let c = makeWrappedCollection(elements) let closureLifetimeTracker = LifetimeTracked(0) do { result = try c.sorted { (lhs, rhs) throws -> Bool in _blackHole(closureLifetimeTracker) if throwElement == extractValue(rhs).value { thrown = true throw SillyError.JazzHands } return lessImpl(extractValue(lhs).value, extractValue(rhs).value) } } catch {} // Check that the original collection is unchanged. expectEqualSequence( elements.map { $0.value }, c.map { extract($0).value }) // If `sorted` throws then result will be empty else // returned result must be sorted. if thrown { expectEqual(0, result.count) } else { // Check that the elements are sorted. let extractedResult = result.map(extract) for i in extractedResult.indices { if i != extractedResult.index(before: extractedResult.endIndex) { let first = extractedResult[i].value let second = extractedResult[extractedResult.index(after: i)].value let result = lessImpl(second, first) expectFalse(result) } } } } self.test("\(testNamePrefix).sorted/DispatchesThrough_withUnsafeMutableBufferPointerIfSupported/WhereElementIsComparable") { let sequence = [ 5, 4, 3, 2, 1 ] let elements: [MinimalComparableValue] = zip(sequence, 0..<sequence.count).map { MinimalComparableValue($0, identity: $1) } let c = makeWrappedCollectionWithComparableElement(elements) var lc = LoggingMutableCollection(wrapping: c) let result = lc.sorted() let extractedResult = result.map(extractValueFromComparable) // This sort operation is not in-place. // The collection is copied into an array before sorting. expectEqual( 0, lc.log._withUnsafeMutableBufferPointerIfSupported[type(of: lc)]) expectEqual( 0, lc.log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[type(of: lc)]) expectEqualSequence([ 1, 2, 3, 4, 5 ], extractedResult.map { $0.value }) } func checkSort_WhereElementIsComparable( sequence: [Int], equalImpl: @escaping ((Int, Int) -> Bool), lessImpl: @escaping ((Int, Int) -> Bool), verifyOrder: Bool ) { MinimalComparableValue.equalImpl.value = equalImpl MinimalComparableValue.lessImpl.value = lessImpl let extract = extractValueFromComparable let elements: [MinimalComparableValue] = zip(sequence, 0..<sequence.count).map { MinimalComparableValue($0, identity: $1) } let c = makeWrappedCollectionWithComparableElement(elements) let result = c.sorted() // Check that the original collection is unchanged. expectEqualSequence( elements.map { $0.value }, c.map { extract($0).value }) let extractedResult = result.map(extract) // Check that we didn't lose any elements. expectEqualsUnordered( 0..<sequence.count, extractedResult.map { $0.identity }) // Check that the elements are sorted. if verifyOrder { for i in extractedResult.indices { if i != extractedResult.index(before: extractedResult.endIndex) { let first = extractedResult[i].value let second = extractedResult[extractedResult.index(after: i)].value expectFalse(lessImpl(second, first)) } } } } self.test("\(testNamePrefix).sorted/WhereElementIsComparable") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in checkSort_WhereElementIsComparable( sequence: sequence, equalImpl: { $0 == $1 }, lessImpl: { $0 < $1 }, verifyOrder: true) } } } self.test("\(testNamePrefix).sorted/WhereElementIsComparable/InvalidOrderings") { withInvalidOrderings { (comparisonPredicate: @escaping (Int, Int) -> Bool) in for i in 0..<7 { forAllPermutations(i) { (sequence) in checkSort_WhereElementIsComparable( sequence: sequence, equalImpl: { !comparisonPredicate($0, $1) && !comparisonPredicate($1, $0) }, lessImpl: comparisonPredicate, verifyOrder: false) } } } } self.test("\(testNamePrefix).sorted/ThrowingPredicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in for i in 0..<sequence.count { checkSortedPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } } self.test("\(testNamePrefix).sorted/ThrowingPredicateWithLargeNumberElements") { for sequence in largeElementSortTests { for i in 0..<sequence.count { checkSortedPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } self.test("\(testNamePrefix).sorted/DispatchesThrough_withUnsafeMutableBufferPointerIfSupported/Predicate") { let sequence = [ 5, 4, 3, 2, 1 ] let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } let c = makeWrappedCollection(elements) var lc = LoggingMutableCollection(wrapping: c) let result = lc.sorted { extractValue($0).value < extractValue($1).value } let extractedResult = result.map(extractValue) // This sort operation is not in-place. // The collection is copied into an array before sorting. expectEqual( 0, lc.log._withUnsafeMutableBufferPointerIfSupported[type(of: lc)]) expectEqual( 0, lc.log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[type(of: lc)]) expectEqualSequence([ 1, 2, 3, 4, 5 ], extractedResult.map { $0.value }) } func checkSort_Predicate( sequence: [Int], equalImpl: @escaping ((Int, Int) -> Bool), lessImpl: @escaping ((Int, Int) -> Bool), verifyOrder: Bool ) { let extract = extractValue let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } let c = makeWrappedCollection(elements) let closureLifetimeTracker = LifetimeTracked(0) let result = c.sorted { (lhs, rhs) in _blackHole(closureLifetimeTracker) return lessImpl(extractValue(lhs).value, extractValue(rhs).value) } // Check that the original collection is unchanged. expectEqualSequence( elements.map { $0.value }, c.map { extract($0).value }) let extractedResult = result.map(extract) // Check that we didn't lose any elements. expectEqualsUnordered( 0..<sequence.count, extractedResult.map { $0.identity }) // Check that the elements are sorted. if verifyOrder { for i in extractedResult.indices { if i != extractedResult.index(before: extractedResult.endIndex) { let first = extractedResult[i].value let second = extractedResult[extractedResult.index(after: i)].value expectFalse(lessImpl(second, first)) } } } } self.test("\(testNamePrefix).sorted/Predicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in checkSort_Predicate( sequence: sequence, equalImpl: { $0 == $1 }, lessImpl: { $0 < $1 }, verifyOrder: true) } } } self.test("\(testNamePrefix).sorted/Predicate/InvalidOrderings") { withInvalidOrderings { (comparisonPredicate: @escaping (Int, Int) -> Bool) in for i in 0..<7 { forAllPermutations(i) { (sequence) in checkSort_Predicate( sequence: sequence, equalImpl: { !comparisonPredicate($0, $1) && !comparisonPredicate($1, $0) }, lessImpl: comparisonPredicate, verifyOrder: false) } } } } self.test("\(testNamePrefix).sorted/ThrowingPredicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in for i in 0..<sequence.count { checkSortedPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } } self.test("\(testNamePrefix).sorted/ThrowingPredicateWithLargeNumberElements") { for sequence in largeElementSortTests { for i in 0..<sequence.count { checkSortedPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } //===----------------------------------------------------------------------===// // partition(by:) //===----------------------------------------------------------------------===// func checkPartition( sequence: [Int], pivotValue: Int, lessImpl: ((Int, Int) -> Bool), verifyOrder: Bool ) { let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } var c = makeWrappedCollection(elements) let closureLifetimeTracker = LifetimeTracked(0) let pivot = c.partition(by: { val in _blackHole(closureLifetimeTracker) return !lessImpl(extractValue(val).value, pivotValue) }) // Check that we didn't lose any elements. let identities = c.map { extractValue($0).identity } expectEqualsUnordered(0..<sequence.count, identities) if verifyOrder { // All the elements in the first partition are less than the pivot // value. for i in c[c.startIndex..<pivot].indices { expectLT(extractValue(c[i]).value, pivotValue) } // All the elements in the second partition are greater or equal to // the pivot value. for i in c[pivot..<c.endIndex].indices { expectGE(extractValue(c[i]).value, pivotValue) } } } self.test("\(testNamePrefix).partition") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in checkPartition( sequence: sequence, pivotValue: sequence.first ?? 0, lessImpl: { $0 < $1 }, verifyOrder: true) // Pivot value where all elements will pass the partitioning predicate checkPartition( sequence: sequence, pivotValue: Int.min, lessImpl: { $0 < $1 }, verifyOrder: true) // Pivot value where no element will pass the partitioning predicate checkPartition( sequence: sequence, pivotValue: Int.max, lessImpl: { $0 < $1 }, verifyOrder: true) } } } self.test("\(testNamePrefix).partition/InvalidOrderings") { withInvalidOrderings { (comparisonPredicate) in for i in 0..<7 { forAllPermutations(i) { (sequence) in checkPartition( sequence: sequence, pivotValue: sequence.first ?? 0, lessImpl: comparisonPredicate, verifyOrder: false) } } } } //===----------------------------------------------------------------------===// } // addMutableCollectionTests public func addMutableBidirectionalCollectionTests< C : BidirectionalCollection & MutableCollection, CollectionWithEquatableElement : BidirectionalCollection & MutableCollection, CollectionWithComparableElement : BidirectionalCollection & MutableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), makeCollectionOfComparable: @escaping ([CollectionWithComparableElement.Element]) -> CollectionWithComparableElement, wrapValueIntoComparable: @escaping (MinimalComparableValue) -> CollectionWithComparableElement.Element, extractValueFromComparable: @escaping ((CollectionWithComparableElement.Element) -> MinimalComparableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, withUnsafeMutableBufferPointerIsSupported: Bool, isFixedLengthCollection: Bool ) where CollectionWithEquatableElement.Element : Equatable, CollectionWithComparableElement.Element : Comparable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addMutableCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: wrapValueIntoComparable, extractValueFromComparable: extractValueFromComparable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, withUnsafeMutableBufferPointerIsSupported: withUnsafeMutableBufferPointerIsSupported, isFixedLengthCollection: isFixedLengthCollection, collectionIsBidirectional: true ) addBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // subscript(_: Index) //===----------------------------------------------------------------------===// if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .none { self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/NonEmpty/Set") { var c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.startIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) c[index] = wrapValue(OpaqueValue(9999)) } self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/Empty/Set") { var c = makeWrappedCollection([]) var index = c.startIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) c[index] = wrapValue(OpaqueValue(9999)) } } //===----------------------------------------------------------------------===// // reverse() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).reverse()") { for test in reverseTests { var c = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) c.reverse() expectEqual( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // partition(by:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).partition/DispatchesThrough_withUnsafeMutableBufferPointerIfSupported") { let sequence = [ 5, 4, 3, 2, 1 ] let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } let c = makeWrappedCollection(elements) var lc = makeBufferAccessLoggingMutableCollection(wrapping: c) let closureLifetimeTracker = LifetimeTracked(0) let first = c.first let pivot = lc.partition(by: { val in _blackHole(closureLifetimeTracker) return !(extractValue(val).value < extractValue(first!).value) }) expectEqual( 1, lc.log._withUnsafeMutableBufferPointerIfSupported[type(of: lc)]) expectEqual( withUnsafeMutableBufferPointerIsSupported ? 1 : 0, lc.log._withUnsafeMutableBufferPointerIfSupportedNonNilReturns[type(of: lc)]) expectEqual(4, lc.distance(from: lc.startIndex, to: pivot)) expectEqualsUnordered([1, 2, 3, 4], lc.prefix(upTo: pivot).map { extractValue($0).value }) expectEqualsUnordered([5], lc.suffix(from: pivot).map { extractValue($0).value }) } //===----------------------------------------------------------------------===// } // addMutableBidirectionalCollectionTests public func addMutableRandomAccessCollectionTests< C : RandomAccessCollection & MutableCollection, CollectionWithEquatableElement : RandomAccessCollection & MutableCollection, CollectionWithComparableElement : RandomAccessCollection & MutableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), makeCollectionOfComparable: @escaping ([CollectionWithComparableElement.Element]) -> CollectionWithComparableElement, wrapValueIntoComparable: @escaping (MinimalComparableValue) -> CollectionWithComparableElement.Element, extractValueFromComparable: @escaping ((CollectionWithComparableElement.Element) -> MinimalComparableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, withUnsafeMutableBufferPointerIsSupported: Bool, isFixedLengthCollection: Bool ) where CollectionWithEquatableElement.Element : Equatable, CollectionWithComparableElement.Element : Comparable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addMutableBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: wrapValueIntoComparable, extractValueFromComparable: extractValueFromComparable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, withUnsafeMutableBufferPointerIsSupported: withUnsafeMutableBufferPointerIsSupported, isFixedLengthCollection: isFixedLengthCollection) addRandomAccessCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } func makeWrappedCollectionWithComparableElement( _ elements: [MinimalComparableValue] ) -> CollectionWithComparableElement { return makeCollectionOfComparable(elements.map(wrapValueIntoComparable)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // sort() //===----------------------------------------------------------------------===// func checkSortPredicateThrow( sequence: [Int], lessImpl: ((Int, Int) -> Bool), throwIndex: Int ) { let extract = extractValue let throwElement = sequence[throwIndex] let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } var c = makeWrappedCollection(elements) let closureLifetimeTracker = LifetimeTracked(0) do { try c.sort { (lhs, rhs) throws -> Bool in _blackHole(closureLifetimeTracker) if throwElement == extractValue(rhs).value { throw SillyError.JazzHands } return lessImpl(extractValue(lhs).value, extractValue(rhs).value) } } catch {} //Check no element should lost and added expectEqualsUnordered( sequence, c.map { extract($0).value }) } func checkSortInPlace_WhereElementIsComparable( sequence: [Int], equalImpl: @escaping ((Int, Int) -> Bool), lessImpl: @escaping ((Int, Int) -> Bool), verifyOrder: Bool ) { MinimalComparableValue.equalImpl.value = equalImpl MinimalComparableValue.lessImpl.value = lessImpl let extract = extractValueFromComparable let elements: [MinimalComparableValue] = zip(sequence, 0..<sequence.count).map { MinimalComparableValue($0, identity: $1) } var c = makeWrappedCollectionWithComparableElement(elements) c.sort() let extractedResult = c.map(extract) // Check that we didn't lose any elements. expectEqualsUnordered( 0..<sequence.count, extractedResult.map { $0.identity }) // Check that the elements are sorted. if verifyOrder { for i in extractedResult.indices { if i != extractedResult.index(before: extractedResult.endIndex) { let first = extractedResult[i].value let second = extractedResult[extractedResult.index(after: i)].value expectFalse(lessImpl(second, first)) } } } } self.test("\(testNamePrefix).sort/WhereElementIsEquatable") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in checkSortInPlace_WhereElementIsComparable( sequence: sequence, equalImpl: { $0 == $1 }, lessImpl: { $0 < $1 }, verifyOrder: true) } } } self.test("\(testNamePrefix).sort/WhereElementIsEquatable/InvalidOrderings") { withInvalidOrderings { (comparisonPredicate : @escaping (Int, Int) -> Bool) in for i in 0..<7 { forAllPermutations(i) { (sequence) in checkSortInPlace_WhereElementIsComparable( sequence: sequence, equalImpl: { !comparisonPredicate($0, $1) && !comparisonPredicate($1, $0) }, lessImpl: comparisonPredicate, verifyOrder: false) } } } } self.test("\(testNamePrefix).sort/ThrowingPredicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in for i in 0..<sequence.count { checkSortPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } } self.test("\(testNamePrefix).sort/ThrowingPredicateWithLargeNumberElements") { for sequence in largeElementSortTests { for i in 0..<sequence.count { checkSortPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } func checkSortInPlace_Predicate( sequence: [Int], equalImpl: @escaping ((Int, Int) -> Bool), lessImpl: @escaping ((Int, Int) -> Bool), verifyOrder: Bool ) { let extract = extractValue let elements: [OpaqueValue<Int>] = zip(sequence, 0..<sequence.count).map { OpaqueValue($0, identity: $1) } var c = makeWrappedCollection(elements) let closureLifetimeTracker = LifetimeTracked(0) c.sort { (lhs, rhs) in _blackHole(closureLifetimeTracker) return lessImpl(extractValue(lhs).value, extractValue(rhs).value) } let extractedResult = c.map(extract) // Check that we didn't lose any elements. expectEqualsUnordered( 0..<sequence.count, extractedResult.map { $0.identity }) // Check that the elements are sorted. if verifyOrder { for i in extractedResult.indices { if i != extractedResult.index(before: extractedResult.endIndex) { let first = extractedResult[i].value let second = extractedResult[extractedResult.index(after: i)].value expectFalse(lessImpl(second, first)) } } } } self.test("\(testNamePrefix).sort/Predicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in checkSortInPlace_Predicate( sequence: sequence, equalImpl: { $0 == $1 }, lessImpl: { $0 < $1 }, verifyOrder: true) } } } self.test("\(testNamePrefix).sort/Predicate/InvalidOrderings") { withInvalidOrderings { (comparisonPredicate : @escaping (Int, Int) -> Bool) in for i in 0..<7 { forAllPermutations(i) { (sequence) in checkSortInPlace_Predicate( sequence: sequence, equalImpl: { !comparisonPredicate($0, $1) && !comparisonPredicate($1, $0) }, lessImpl: comparisonPredicate, verifyOrder: false) } } } } self.test("\(testNamePrefix).sort/ThrowingPredicate") { for test in partitionExhaustiveTests { forAllPermutations(test.sequence) { (sequence) in for i in 0..<sequence.count { checkSortPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } } self.test("\(testNamePrefix).sort/ThrowingPredicateWithLargeNumberElements") { for sequence in largeElementSortTests { for i in 0..<sequence.count { checkSortPredicateThrow( sequence: sequence, lessImpl: { $0 < $1 }, throwIndex: i) } } } //===----------------------------------------------------------------------===// } // addMutableRandomAccessCollectionTests }
apache-2.0
4c0c014da1bd2f2ccea4a27bbb53c04c
32.900936
124
0.652953
4.727105
false
true
false
false
jedisct1/swift-sodium
Sodium/Stream.swift
3
2722
import Foundation import Clibsodium public struct Stream { public let Primitive = String(validatingUTF8: crypto_stream_primitive()) } extension Stream { /** XOR the input with a key stream derived from a secret key and a nonce. Applying the same operation twice outputs the original input. No authentication tag is added to the output. The data can be tampered with; an adversary can flip arbitrary bits. In order to encrypt data using a secret key, the SecretBox class is likely to be what you are looking for. In order to generate a deterministic stream out of a seed, the RandomBytes.deterministic_rand() function is likely to be what you need. - Parameter input: Input data - Parameter nonce: Nonce - Parameter secretKey: The secret key - Returns: input XOR keystream(secretKey, nonce) */ public func xor(input: Bytes, nonce: Nonce, secretKey: Key) -> Bytes? { guard secretKey.count == KeyBytes, nonce.count == NonceBytes else { return nil } var output = Bytes(count: input.count) guard .SUCCESS == crypto_stream_xor ( &output, input, UInt64(input.count), nonce, secretKey ).exitCode else { return nil } return output } /** XOR the input with a key stream derived from a secret key and a random nonce. Applying the same operation twice outputs the original input. No authentication tag is added to the output. The data can be tampered with; an adversary can flip arbitrary bits. In order to encrypt data using a secret key, the SecretBox class is likely to be what you are looking for. In order to generate a deterministic stream out of a seed, the RandomBytes.deterministic_rand() function is likely to be what you need. - Parameter input: Input data - Parameter nonce: Nonce - Parameter secretKey: The secret key - Returns: (input XOR keystream(secretKey, nonce), nonce) */ public func xor(input: Bytes, secretKey: Key) -> (output:Bytes, nonce: Nonce)? { let nonce = self.nonce() guard let output: Bytes = xor( input: input, nonce: nonce, secretKey: secretKey ) else { return nil } return (output: output, nonce: nonce) } } extension Stream: NonceGenerator { public typealias Nonce = Bytes public var NonceBytes: Int { return Int(crypto_secretbox_noncebytes()) } } extension Stream: SecretKeyGenerator { public typealias Key = Bytes public var KeyBytes: Int { return Int(crypto_secretbox_keybytes()) } public static let keygen: (_ k: UnsafeMutablePointer<UInt8>) -> Void = crypto_stream_keygen }
isc
7e54baec56bb8c5efc4e43e2b3240901
36.805556
140
0.675974
4.462295
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/CocoaFileSystemRuntime.swift
2
7216
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation private let documentsFolder = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0].asNS.stringByDeletingLastPathComponent // Public methods for working with files class CocoaFiles { class func pathFromDescriptor(path: String) -> String { return documentsFolder + path } } // Implementation of FileSystem storage @objc class CocoaFileSystemRuntime : NSObject, ARFileSystemRuntime { let manager = NSFileManager.defaultManager() override init() { super.init() } func createTempFile() -> ARFileSystemReference! { let fileName = "/tmp/\(NSUUID().UUIDString)" NSFileManager.defaultManager().createFileAtPath(documentsFolder + fileName, contents: nil, attributes: nil) return CocoaFile(path: fileName) } func commitTempFile(sourceFile: ARFileSystemReference!, withFileId fileId: jlong, withFileName fileName: String!) -> ARFileSystemReference! { // Finding file available name // let path = "\(documentsFolder)/Documents/\(fileId)_\(fileName)" let descriptor = "/Documents/\(fileId)_\(fileName)" // // if manager.fileExistsAtPath("\(documentsFolder)/Documents/\(fileId)_\(fileName)") { // do { // try manager.removeItemAtPath(path) // } catch _ { // return nil // } // } let srcUrl = NSURL(fileURLWithPath: documentsFolder + sourceFile.getDescriptor()!) let destUrl = NSURL(fileURLWithPath: documentsFolder + descriptor) // manager.replaceItemAtURL(srcUrl, withItemAtURL: destUrl, backupItemName: nil, options: 0, resultingItemURL: nil) // Moving file to new place do { try manager.replaceItemAtURL(destUrl, withItemAtURL: srcUrl, backupItemName: nil, options: NSFileManagerItemReplacementOptions(rawValue: 0), resultingItemURL: nil) // try manager.moveItemAtPath(documentsFolder + sourceFile.getDescriptor()!, toPath: path) return CocoaFile(path: descriptor) } catch _ { return nil } } func fileFromDescriptor(descriptor: String!) -> ARFileSystemReference! { return CocoaFile(path: descriptor) } func isFsPersistent() -> Bool { return true } } class CocoaFile : NSObject, ARFileSystemReference { let path: String; let realPath: String; init(path:String) { self.path = path self.realPath = CocoaFiles.pathFromDescriptor(path) } func getDescriptor() -> String! { return path; } func isExist() -> Bool { return NSFileManager().fileExistsAtPath(realPath); } func isInAppMemory() -> jboolean { return false } func isInTempDirectory() -> jboolean { return false } func getSize() -> jint { do { let attrs = try NSFileManager().attributesOfItemAtPath(realPath) return jint(NSDictionary.fileSize(attrs)()) } catch _ { return 0 } } func openRead() -> ARPromise! { let fileHandle = NSFileHandle(forReadingAtPath: realPath) if (fileHandle == nil) { return ARPromise.failure(JavaLangRuntimeException(NSString: "Unable to open file")) } return ARPromise.success(CocoaInputFile(fileHandle: fileHandle!)) } func openWriteWithSize(size: jint) -> ARPromise! { let fileHandle = NSFileHandle(forWritingAtPath: realPath) if (fileHandle == nil) { return ARPromise.failure(JavaLangRuntimeException(NSString: "Unable to open file")) } fileHandle!.seekToFileOffset(UInt64(size)) fileHandle!.seekToFileOffset(0) return ARPromise.success(CocoaOutputFile(fileHandle: fileHandle!)) } } class CocoaOutputFile : NSObject, AROutputFile { let fileHandle: NSFileHandle init(fileHandle:NSFileHandle) { self.fileHandle = fileHandle } func writeWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset dataOffset: jint, withLength dataLen: jint) -> Bool { let pointer = data.buffer().advancedBy(Int(dataOffset)) let srcData = NSData(bytesNoCopy: pointer, length: Int(dataLen), freeWhenDone: false) fileHandle.seekToFileOffset(UInt64(fileOffset)) fileHandle.writeData(srcData) return true; } func close() -> Bool { self.fileHandle.synchronizeFile() self.fileHandle.closeFile() return true; } } class CocoaInputFile :NSObject, ARInputFile { let fileHandle:NSFileHandle init(fileHandle:NSFileHandle) { self.fileHandle = fileHandle } func readWithOffset(fileOffset: jint, withLength len: jint) -> ARPromise! { return ARPromise { (resolver) in dispatchBackground { self.fileHandle.seekToFileOffset(UInt64(fileOffset)) let readed: NSData = self.fileHandle.readDataOfLength(Int(len)) let data = IOSByteArray(length: UInt(len)) var srcBuffer = UnsafeMutablePointer<UInt8>(readed.bytes) var destBuffer = UnsafeMutablePointer<UInt8>(data.buffer()) let readCount = min(Int(len), Int(readed.length)) for _ in 0..<readCount { destBuffer.memory = srcBuffer.memory destBuffer = destBuffer.successor() srcBuffer = srcBuffer.successor() } resolver.result(ARFilePart(offset: fileOffset, withLength: len, withContents: data)) } } } func close() -> ARPromise! { self.fileHandle.closeFile() return ARPromise.success(nil) } // func readWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset offset: jint, withLength len: jint, withCallback callback: ARFileReadCallback!) { // // dispatchBackground { // // self.fileHandle.seekToFileOffset(UInt64(fileOffset)) // // let readed: NSData = self.fileHandle.readDataOfLength(Int(len)) // // var srcBuffer = UnsafeMutablePointer<UInt8>(readed.bytes) // var destBuffer = UnsafeMutablePointer<UInt8>(data.buffer()) // let len = min(Int(len), Int(readed.length)) // for _ in offset..<offset+len { // destBuffer.memory = srcBuffer.memory // destBuffer = destBuffer.successor() // srcBuffer = srcBuffer.successor() // } // // callback.onFileReadWithOffset(fileOffset, withData: data, withDataOffset: offset, withLength: jint(len)) // } // } // func close() -> Bool { // self.fileHandle.closeFile() // return true // } }
agpl-3.0
05ee97fca101aef0ca15feb436426cb2
31.954338
193
0.60546
5.092449
false
false
false
false
vasarhelyia/swift-persist
SwiftStorageTest/SwiftStorageTest/PersistentStorage.swift
1
2417
// // PersistentStorage.swift // SwiftStorageTest // // Created by Ágnes Vásárhelyi on 31/08/14. // Copyright (c) 2014 Ágnes Vásárhelyi. All rights reserved. // import Foundation private var Instance = PersistentStorage() private let StorageName = "MyAppStorage" //Replace with yours class PersistentStorage : NSObject { /* Always call self.save() in property's didSet: didSet { self.save() } */ var userName: String = "" { didSet { self.save() } } var numberOfAppLaunches: Int32 = 0 { didSet { if numberOfAppLaunches > 0 { self.save() } } } class var sharedInstance : PersistentStorage { return Instance } override init() { super.init() } override class func initialize() { let userDefaults = NSUserDefaults.standardUserDefaults() if let storageData = userDefaults.dataForKey(StorageName) { let unarchiver = NSKeyedUnarchiver(forReadingWithData: storageData) Instance = unarchiver.decodeObject() as! PersistentStorage } else { Instance = PersistentStorage() } } required init(coder aDecoder: NSCoder) { /* Call aDecoder.decodeObjectForKey(key:) for every property */ if let userName = aDecoder.decodeObjectForKey("userName") as? String { self.userName = userName } else { self.userName = "" } self.numberOfAppLaunches = aDecoder.decodeIntForKey("numberOfAppLaunches") } func encodeWithCoder(aCoder: NSCoder) { /* Call aCoder.encodeObject(objv:, forKey:) for every property */ aCoder.encodeObject(self.userName, forKey: "userName") aCoder.encodeInt(self.numberOfAppLaunches, forKey: "numberOfAppLaunches") } func save() { let lock = NSLock() lock.lock() let userDefaults = NSUserDefaults.standardUserDefaults() let storageData = NSMutableData() let archiver = NSKeyedArchiver(forWritingWithMutableData: storageData) archiver.encodeObject(Instance) archiver.finishEncoding() userDefaults.setObject(storageData, forKey: StorageName) userDefaults.synchronize() lock.unlock() } }
mit
29570873f945b41d31ad6788fc40372a
26.101124
82
0.600995
4.940574
false
false
false
false
welbesw/BigcommerceApi
Pod/Classes/Utility.swift
1
913
// // Utility.swift // BigcommerceApi // // Created by William Welbes on 4/5/19. // import Foundation class Utility { static let errorDomain = "com.technomagination.BigCommerceApi" static func error(_ message: String, code: Int = 0) -> NSError { let customError = NSError(domain: errorDomain, code: code, userInfo: [ NSLocalizedDescriptionKey: message, ]) return customError } static func percentEscapeString(_ string: String) -> String { var characterSet = CharacterSet.alphanumerics characterSet.insert(charactersIn: "-._* ") guard let escapedString = string.addingPercentEncoding(withAllowedCharacters: characterSet)?.replacingOccurrences(of: " ", with: "+", options: [], range: nil) else { return string } return escapedString } }
mit
4b515f960a36f3b16e44a471ccb76f12
25.085714
173
0.607886
4.989071
false
false
false
false
JackVaughn23/pingit
Pingit/DispatchTimer.swift
1
7974
// // DispatchTimer.swift // AmbientUPNP // // Created by Taras Vozniuk on 7/11/15. // Copyright (c) 2015 ambientlight. All rights reserved. // import Foundation public class DispatchTimer: Equatable { public enum Status { case NotStarted case Active case Paused case Done case Invalidated } private var _timerSource:dispatch_source_t private var _isInvalidating:Bool = false //either startDate or lastFire or lastResume date private var _lastActiveDateº:NSDate? private var _elapsedAccumulatedTime: Double = Double(0) //MARK: PROPERTIES public private(set) var remainingFireCount:UInt public private(set) var status:DispatchTimer.Status = .NotStarted public private(set) var startDateº:NSDate? public let queue:dispatch_queue_t public let isFinite:Bool public let fireCount:UInt public let interval:UInt public let invocationBlock:(timer:DispatchTimer) -> Void public var completionHandlerº:((timer:DispatchTimer) -> Void)? public var userInfoº:Any? public var valid:Bool { return (self.status != .Done || self.status != .Invalidated) } public var started:Bool { return (self.status != .NotStarted) } public var startAbsoluteTimeº:Double? { return (startDateº != nil) ? self.startDateº!.timeIntervalSince1970 : nil } //all parameters are in milliseconds private func _setupTimerSource(timeInterval:UInt, startOffset:UInt, leeway: UInt) { dispatch_source_set_timer(_timerSource, dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(startOffset) * NSEC_PER_MSEC)), UInt64(timeInterval) * NSEC_PER_MSEC, UInt64(leeway) * NSEC_PER_MSEC) dispatch_source_set_event_handler(_timerSource) { self._elapsedAccumulatedTime = 0 self._lastActiveDateº = NSDate() self.invocationBlock(timer: self) if(self.isFinite){ self.remainingFireCount-- if(self.remainingFireCount == 0){ dispatch_source_cancel(self._timerSource) } } } dispatch_source_set_cancel_handler(_timerSource){ if(self._isInvalidating){ self.status = .Invalidated self._isInvalidating = false } else { self.status = .Done } self.completionHandlerº?(timer: self) } } //MARK: public init(milliseconds:UInt, startOffset:Int, tolerance:UInt, queue: dispatch_queue_t, isFinite:Bool, fireCount:UInt, userInfoº:Any?, completionHandlerº:((timer:DispatchTimer) -> Void)?,invocationBlock: (timer:DispatchTimer) -> Void) { self.queue = queue self.userInfoº = userInfoº self.isFinite = isFinite self.fireCount = fireCount; self.remainingFireCount = self.fireCount self.userInfoº = userInfoº self.completionHandlerº = completionHandlerº self.invocationBlock = invocationBlock self.interval = milliseconds _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) let offset:Int = ( (startOffset < 0) && (abs(startOffset) > Int(self.interval)) ) ? -Int(self.interval) : startOffset _setupTimerSource(self.interval, startOffset: UInt( Int(self.interval) + offset), leeway: tolerance) } public class func timerWithTimeInterval(milliseconds milliseconds: UInt, queue: dispatch_queue_t, repeats: Bool, invocationBlock: (timer:DispatchTimer) -> Void) -> DispatchTimer { let timer = DispatchTimer(milliseconds: milliseconds, startOffset: 0, tolerance: 0, queue: queue, isFinite: !repeats, fireCount: (repeats) ? 0 : 1, userInfoº: nil, completionHandlerº:nil, invocationBlock: invocationBlock) return timer } public class func timerWithTimeInterval(milliseconds milliseconds: UInt, queue: dispatch_queue_t, fireCount: UInt, invocationBlock: (timer:DispatchTimer) -> Void) -> DispatchTimer { let timer = DispatchTimer(milliseconds: milliseconds, startOffset: 0, tolerance: 0, queue: queue, isFinite: true, fireCount: fireCount, userInfoº: nil, completionHandlerº:nil, invocationBlock: invocationBlock) return timer } public class func scheduledTimerWithTimeInterval(milliseconds milliseconds: UInt, queue: dispatch_queue_t, repeats: Bool, invocationBlock: (timer:DispatchTimer) -> Void) -> DispatchTimer { let timer = DispatchTimer(milliseconds: milliseconds, startOffset: 0, tolerance: 0, queue: queue, isFinite: !repeats, fireCount: (repeats) ? 0 : 1, userInfoº: nil, completionHandlerº:nil, invocationBlock: invocationBlock) timer.start() return timer } public class func scheduledTimerWithTimeInterval(milliseconds milliseconds: UInt, queue: dispatch_queue_t, fireCount: UInt, invocationBlock: (timer:DispatchTimer) -> Void) -> DispatchTimer { let timer = DispatchTimer(milliseconds: milliseconds, startOffset: 0, tolerance: 0, queue: queue, isFinite: true, fireCount: fireCount, userInfoº: nil, completionHandlerº:nil, invocationBlock: invocationBlock) timer.start() return timer } public class func scheduledTimerWithTimeInterval(milliseconds milliseconds:UInt, startOffset:Int, tolerance:UInt, queue: dispatch_queue_t, isFinite:Bool, fireCount:UInt, userInfoº:Any?, completionHandlerº:((timer:DispatchTimer) -> Void)?, invocationBlock: (timer:DispatchTimer) -> Void) -> DispatchTimer { let timer = DispatchTimer(milliseconds: milliseconds, startOffset: startOffset, tolerance: tolerance, queue: queue, isFinite: isFinite, fireCount: fireCount, userInfoº: userInfoº, completionHandlerº:completionHandlerº, invocationBlock: invocationBlock) timer.start() return timer } //MARK: METHODS public func start(){ if (!self.started){ dispatch_resume(_timerSource) self.startDateº = NSDate() _lastActiveDateº = self.startDateº self.status = .Active } } public func pause(){ if (self.status == .Active){ dispatch_source_set_cancel_handler(_timerSource){ } dispatch_source_cancel(_timerSource) self.status = .Paused let pauseDate = NSDate() _elapsedAccumulatedTime += (pauseDate.timeIntervalSince1970 - _lastActiveDateº!.timeIntervalSince1970) * 1000 //NSLog("%ld milliseconds elapsed", UInt(_elapsedAccumulatedTime)) } } public func resume(){ if (self.status == .Paused){ //NSLog("%ld milliseconds left till fire", self.interval - UInt(_elapsedAccumulatedTime)) _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) _setupTimerSource(self.interval, startOffset: self.interval - UInt(_elapsedAccumulatedTime), leeway: 0) dispatch_resume(_timerSource) _lastActiveDateº = NSDate() self.status = .Active } } public func invalidate(handlerº:((timer:DispatchTimer)-> Void)? = nil){ _isInvalidating = true; // reassigning completionHandler if has been passed(non-nil) if let handler = completionHandlerº { self.completionHandlerº = handler } dispatch_source_cancel(_timerSource) } } //MARK: Equatable public func ==(lhs: DispatchTimer, rhs: DispatchTimer) -> Bool { return (lhs._timerSource === rhs._timerSource) }
mit
3e024df523b68c2dea2cbb96dd0e0686
38.477612
309
0.638059
4.695266
false
false
false
false
minimoog/filters
filters/CarnivalMirror.swift
1
3486
// // CarnivalMirror.swift // filters // // Created by Toni Jovanoski on 2/14/17. // Copyright © 2017 Antonie Jovanoski. All rights reserved. // import Foundation import CoreImage class CarnivalMirror: CIFilter { var inputImage: CIImage? var inputHorWavelength: CGFloat = 10 var inputHorAmount: CGFloat = 20 var inputVerWavelength: CGFloat = 10 var inputVerAmount: CGFloat = 20 override func setDefaults() { inputHorWavelength = 10 inputHorAmount = 20 inputVerWavelength = 10 inputVerAmount = 20 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Carnival Mirror", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputHorizontalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Horizontal Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputHorizontalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Horizontal Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Vertical Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Vertical Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } let carnivalMirrorKernel = CIWarpKernel(string: "kernel vec2 carnivalMirror(float xWavelength, float xAmount, float yWavelength, float yAmount)" + "{" + " float y = destCoord().y + sin(destCoord().y / yWavelength) * yAmount; " + " float x = destCoord().x + sin(destCoord().x / xWavelength) * xAmount; " + " return vec2(x, y);" + "}") override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = carnivalMirrorKernel else { return nil } let arguments = [inputHorWavelength, inputHorAmount, inputVerWavelength, inputVerAmount] let extent = inputImage.extent return kernel.apply(withExtent: extent, roiCallback: { (index, rect) -> CGRect in return rect }, inputImage: inputImage, arguments: arguments) } }
mit
bc1bdc38089ccd3fd17f23b901095f5c
35.302083
106
0.584505
5.675896
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/OpacitableSpec.swift
1
1511
// // OpacitableSpec.swift // SwiftyEcharts // // Created by Pluto Y on 25/06/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble import SwiftyEcharts class OpacitableSpec: QuickSpec { private class OpacitableClass: Opacitable { var opacity: Float? } override func spec() { describe("For Opacitable") { let opacitableInstance = OpacitableClass() it("needs to check the validate function") { opacitableInstance.opacity = 0.0 expect(opacitableInstance.validateOpacity()).to(equal(true)) expect(opacitableInstance.opacity).to(equal(0.0)) opacitableInstance.opacity = -0.01 expect(opacitableInstance.validateOpacity()).to(equal(false)) expect(opacitableInstance.opacity).to(equal(0.0)) opacitableInstance.opacity = 0.99 expect(opacitableInstance.validateOpacity()).to(equal(true)) expect(opacitableInstance.opacity).to(equal(0.99)) opacitableInstance.opacity = 1.0 expect(opacitableInstance.validateOpacity()).to(equal(true)) expect(opacitableInstance.opacity).to(equal(1.0)) opacitableInstance.opacity = 1.01 expect(opacitableInstance.validateOpacity()).to(equal(false)) expect(opacitableInstance.opacity).to(equal(1.0)) } } } }
mit
e7f292d68a69e7a5049fcd50f6bd7049
34.952381
77
0.60596
3.994709
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift
52
3485
// // Skip.swift // RxSwift // // Created by Krunoslav Zaher on 6/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // count version class SkipCountSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipCount<ElementType> typealias Element = ElementType let parent: Parent var remaining: Int init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent self.remaining = parent.count super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if remaining <= 0 { forwardOn(.next(value)) } else { remaining -= 1 } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } } class SkipCount<Element>: Producer<Element> { let source: Observable<Element> let count: Int init(source: Observable<Element>, count: Int) { self.source = source self.count = count } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) let subscription = source.subscribe(sink) return (sink: sink, subscription: subscription) } } // time version class SkipTimeSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipTime<ElementType> typealias Element = ElementType let parent: Parent // state var open = false init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if open { forwardOn(.next(value)) } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } func tick() { open = true } func run() -> Disposable { let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { self.tick() return Disposables.create() } let disposeSubscription = parent.source.subscribe(self) return Disposables.create(disposeTimer, disposeSubscription) } } class SkipTime<Element>: Producer<Element> { let source: Observable<Element> let duration: RxTimeInterval let scheduler: SchedulerType init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) { self.source = source self.scheduler = scheduler self.duration = duration } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
6700efa8964551d8cb58f781d877472b
26.21875
145
0.5907
4.67651
false
false
false
false
Lightstreamer/Lightstreamer-example-MPNStockList-client-ios
Shared/StockListViewController.swift
1
24494
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/ // // StockListViewController.swift // StockList Demo for iOS // // Copyright (c) Lightstreamer Srl // // 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 LightstreamerClient class StockListViewController: UITableViewController, SubscriptionDelegate, UIPopoverControllerDelegate, UINavigationControllerDelegate { let lockQueue = DispatchQueue(label: "lightstreamer.StockListViewController") var stockListView: StockListView? var subscribed = false var subscription: Subscription? var selectedRow: IndexPath? // Multiple-item data structures: each item has a second-level dictionary. // They store fields data and which fields have been updated var itemUpdated = [UInt : [String: Bool]]() var itemData = [UInt : [String : String?]]() // List of rows marked to be reloaded by the table var rowsToBeReloaded = Set<IndexPath>() var infoButton: UIBarButtonItem? var popoverInfoController: UIPopoverController? var statusButton: UIBarButtonItem? var popoverStatusController: UIPopoverController? var detailController: DetailViewController? // MARK: - // MARK: User actions // MARK: - // MARK: Lightstreamer connection status management // MARK: - // MARK: Internals // MARK: - // MARK: Initialization override init(style: UITableView.Style) { super.init(style: style) title = "Lightstreamer Stock List" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) title = "Lightstreamer Stock List" } required init?(coder: NSCoder) { super.init(coder: coder) title = "Lightstreamer Stock List" } // MARK: - // MARK: User actions @objc func infoTapped() { if DEVICE_IPAD { // If the Info popover is open close it if popoverInfoController != nil { popoverInfoController?.dismiss(animated: true) popoverInfoController = nil return } // If the Status popover is open close it if popoverStatusController != nil { popoverStatusController?.dismiss(animated: true) popoverStatusController = nil } // Open the Info popover let infoController = InfoViewController() popoverInfoController = UIPopoverController(contentViewController: infoController) popoverInfoController?.contentSize = CGSize(width: INFO_IPAD_WIDTH, height: INFO_IPAD_HEIGHT) popoverInfoController?.delegate = self if let rightBarButtonItem = navigationItem.rightBarButtonItem { popoverInfoController?.present(from: rightBarButtonItem, permittedArrowDirections: .any, animated: true) } } else { let infoController = InfoViewController() navigationController?.pushViewController(infoController, animated: true) } } @objc func statusTapped() { if DEVICE_IPAD { // If the Status popover is open close it if popoverStatusController != nil { popoverStatusController?.dismiss(animated: true) popoverStatusController = nil return } // If the Info popover is open close it if popoverInfoController != nil { popoverInfoController?.dismiss(animated: true) popoverInfoController = nil } // Open the Status popover let statusController = StatusViewController() popoverStatusController = UIPopoverController(contentViewController: statusController) popoverStatusController?.contentSize = CGSize(width: STATUS_IPAD_WIDTH, height: STATUS_IPAD_HEIGHT) popoverStatusController?.delegate = self if let leftBarButtonItem = navigationItem.leftBarButtonItem { popoverStatusController?.present(from: leftBarButtonItem, permittedArrowDirections: .any, animated: true) } } else { let statusController = StatusViewController() navigationController?.pushViewController(statusController, animated: true) } } // MARK: - // MARK: Methods of UIViewController override func loadView() { let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListView"), owner: self, options: nil) stockListView = niblets?.last as? StockListView tableView = stockListView?.table view = stockListView infoButton = UIBarButtonItem(image: UIImage(named: "Info"), style: .plain, target: self, action: #selector(infoTapped)) infoButton?.tintColor = UIColor.white navigationItem.rightBarButtonItem = infoButton statusButton = UIBarButtonItem(image: UIImage(named: "Icon-disconnected"), style: .plain, target: self, action: #selector(statusTapped)) statusButton?.tintColor = UIColor.white navigationItem.leftBarButtonItem = statusButton navigationController?.delegate = self if DEVICE_IPAD { // On the iPad we preselect the first row, // since the detail view is always visible selectedRow = IndexPath(row: 0, section: 0) detailController = (UIApplication.shared.delegate as? AppDelegate_iPad)?.detailController } // We use the notification center to know when the // connection changes status NotificationCenter.default.addObserver(self, selector: #selector(connectionStatusChanged), name: NOTIFICATION_CONN_STATUS, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(connectionEnded), name: NOTIFICATION_CONN_ENDED, object: nil) // We use the notification center also to know when the app wakes up NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) // Start connection (executes in background) Connector.shared().connect() } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if DEVICE_IPAD { return .landscape } else { return .portrait } } // MARK: - // MARK: Methods of UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return NUMBER_OF_ITEMS } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Prepare the table cell var cell = tableView.dequeueReusableCell(withIdentifier: "StockListCell") as? StockListCell if cell == nil { let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListCell"), owner: self, options: nil) cell = niblets?.last as? StockListCell } // Retrieve the item's data structures var item: [String : String?]! = nil var updated: [String : Bool]! = nil lockQueue.sync { item = itemData[UInt(indexPath.row)] updated = itemUpdated[UInt(indexPath.row)] } if let item = item { // Update the cell appropriately let colorName = item["color"] as? String var color: UIColor? = nil if colorName == "green" { color = GREEN_COLOR } else if colorName == "orange" { color = ORANGE_COLOR } else { color = UIColor.white } cell?.nameLabel?.text = item["stock_name"] as? String if updated?["stock_name"] ?? false { if !stockListView!.table!.isDragging { SpecialEffects.flash(cell?.nameLabel, with: color) } updated?["stock_name"] = false } cell?.lastLabel?.text = item["last_price"] as? String if updated?["last_price"] ?? false { if !stockListView!.table!.isDragging { SpecialEffects.flash(cell?.lastLabel, with: color) } updated?["last_price"] = false } cell?.timeLabel?.text = item["time"] as? String if updated?["time"] ?? false { if !stockListView!.table!.isDragging { SpecialEffects.flash(cell?.timeLabel, with: color) } updated?["time"] = false } let pctChange = Double((item["pct_change"] ?? "0") ?? "0") ?? 0.0 if pctChange > 0.0 { cell?.dirImage?.image = UIImage(named: "Arrow-up") } else if pctChange < 0.0 { cell?.dirImage?.image = UIImage(named: "Arrow-down") } else { cell?.dirImage?.image = nil } if let object = item["pct_change"] { cell?.changeLabel?.text = String(format: "%@%%", object!) } cell?.changeLabel?.textColor = (Double((item["pct_change"] ?? "0") ?? "0") ?? 0.0 >= 0.0) ? DARK_GREEN_COLOR : RED_COLOR if updated?["pct_change"] ?? false { if !stockListView!.table!.isDragging { SpecialEffects.flashImage(cell?.dirImage, with: color) SpecialEffects.flash(cell?.changeLabel, with: color) } updated?["pct_change"] = false } } // Update the cell text colors appropriately if indexPath == selectedRow { cell?.nameLabel?.textColor = SELECTED_TEXT_COLOR cell?.lastLabel?.textColor = SELECTED_TEXT_COLOR cell?.timeLabel?.textColor = SELECTED_TEXT_COLOR } else { cell?.nameLabel?.textColor = DEFAULT_TEXT_COLOR cell?.lastLabel?.textColor = DEFAULT_TEXT_COLOR cell?.timeLabel?.textColor = DEFAULT_TEXT_COLOR } return cell! } // MARK: - // MARK: Methods of UITableViewDelegate override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { // Mark the row to be reloaded lockQueue.sync { if selectedRow != nil { rowsToBeReloaded.insert(selectedRow!) } rowsToBeReloaded.insert(indexPath) } selectedRow = indexPath // Update the table view reloadTableRows() // On the iPhone the Detail View Controller is created on demand and pushed with // the navigation controller if detailController == nil { detailController = DetailViewController() // Ensure the view is loaded detailController?.view } // Update the item on the detail controller detailController?.changeItem(TABLE_ITEMS[indexPath.row]) if !DEVICE_IPAD { // On the iPhone the detail view controller may be already visible if // we are handling an MPN, if it is not just push it if (navigationController?.viewControllers.count ?? 0) == 1 { if let detailController = detailController { navigationController?.pushViewController(detailController, animated: true) } } } return nil } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("StockListSection"), owner: self, options: nil) return niblets?.last as? UIView } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath == selectedRow { cell.backgroundColor = SELECTED_ROW_COLOR } else if indexPath.row % 2 == 0 { cell.backgroundColor = LIGHT_ROW_COLOR } else { cell.backgroundColor = DARK_ROW_COLOR } } // MARK: - // MARK: Methods of UIPopoverControllerDelegate func popoverControllerDidDismissPopover(_ popoverController: UIPopoverController) { if popoverController == popoverInfoController { popoverInfoController = nil } else if popoverController == popoverStatusController { popoverStatusController = nil } } // MARK: - // MARK: Methods of UINavigationControllerDelegate func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if !DEVICE_IPAD { // Remove selection when coming back from detail view if viewController == self { // Mark the row to be reloaded lockQueue.sync { if selectedRow != nil { rowsToBeReloaded.insert(selectedRow!) } } selectedRow = nil // Update the table view reloadTableRows() } } } // MARK: - // MARK: Lighstreamer connection status management @objc func connectionStatusChanged() { // This method is always called from a background thread // Check if we need to subscribe let needsSubscription = !subscribed && Connector.shared().connected let needsMPNUnsubscription = Connector.shared().connected DispatchQueue.main.async(execute: { [self] in // Update connection status icon if Connector.shared().connectionStatus.hasPrefix("DISCONNECTED") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-disconnected") } else if Connector.shared().connectionStatus.hasPrefix("CONNECTING") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-connecting") } else if Connector.shared().connectionStatus.hasPrefix("STALLED") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-stalled") } else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("POLLING") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-polling") } else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("WS-STREAMING") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-WS-streaming") } else if Connector.shared().connectionStatus.hasPrefix("CONNECTED") && Connector.shared().connectionStatus.hasSuffix("HTTP-STREAMING") { navigationItem.leftBarButtonItem?.image = UIImage(named: "Icon-HTTP-streaming") } // If the detail controller is visible, set the item on the detail view controller, // so that it can do its own subscription if needsSubscription && (DEVICE_IPAD || ((navigationController?.viewControllers.count ?? 0) > 1)) { detailController?.changeItem(TABLE_ITEMS[selectedRow?.row ?? 0]) } }) // Check if we need to subscribe if needsSubscription { subscribed = true print("StockListViewController: subscribing table...") // The LSLightstreamerClient will reconnect and resubscribe automatically subscription = Subscription(subscriptionMode: .MERGE, items: TABLE_ITEMS, fields: LIST_FIELDS) subscription?.dataAdapter = DATA_ADAPTER subscription?.requestedSnapshot = .yes subscription?.addDelegate(self) Connector.shared().subscribe(subscription!) } // Check if we need to unsubscribe triggered MPNs if needsMPNUnsubscription && Connector.shared().mpnEnabled { print("StockListViewController: unsubscribing triggered MPNs...") Connector.shared().unsubscribeTriggeredMPNs() } } @objc func connectionEnded() { // This method is always called from a background thread // Connection was forcibly closed by the server, // prepare for a new subscription subscribed = false subscription = nil // Start a new connection (executes in background) Connector.shared().connect() } // MARK: - // MARK: Communication with App delegate @objc func handleMPN(_ mpn: [AnyHashable : Any]?) { // This method is always called from the main thread // Extract MPN content let item = mpn?["item"] as? String let aps = mpn?["aps"] as? [AnyHashable : Any] let alert = aps?["alert"] as? [AnyHashable : Any] let body = alert?["body"] as? String // Skip extraneous MPN notifications let index = TABLE_ITEMS.firstIndex(of: item ?? "") ?? NSNotFound if index == NSNotFound { return } // Check if we are watching this item or another one let itemIsSelected = selectedRow != nil && (selectedRow?.row == index) if itemIsSelected { // Reload thresholds: if we are already watching this item this avoids a // call to a changeItem on the detail controller, which would clear the chart detailController?.updateViewForMPNStatus() } // Add View and Skip buttons if the item is not currently selected let alertBox = UIAlertController( title: "MPN Notification", message: body, preferredStyle: UIAlertController.Style.alert) if itemIsSelected { alertBox.addAction(UIAlertAction( title: "Ok", style: UIAlertAction.Style.cancel, handler: nil)) } else { alertBox.addAction(UIAlertAction( title: "View", style: UIAlertAction.Style.default, handler: { _ in // Replicate the effect of a user tap on the appropriate cell, // will end up in a call to changeItem on the detail controller if let table = self.stockListView?.table { self.tableView(table, willSelectRowAt: IndexPath(row: index, section: 0)) } })) alertBox.addAction(UIAlertAction( title: "Skip", style: UIAlertAction.Style.cancel, handler: nil)) } self.present(alertBox, animated: true, completion: nil) } // MARK: - // MARK: Internals func reloadTableRows() { // This method is always called from the main thread var rows: [IndexPath]? = nil lockQueue.sync { rows = [IndexPath]() for indexPath in self.rowsToBeReloaded { rows?.append(indexPath) } self.rowsToBeReloaded.removeAll() } // Ask the table to reload the marked rows if let rows = rows { stockListView?.table?.reloadRows(at: rows, with: .none) } } @objc func appDidBecomeActive() { // This method is always called from the main thread // Check if there's a selection and the detail controller is visible if selectedRow != nil && (DEVICE_IPAD || ((navigationController?.viewControllers.count ?? 0) > 1)) { // Reload thresholds on detail controller, // they may have been changed in the background detailController?.updateViewForMPNStatus() } } // MARK: - // MARK: Methods of SubscriptionDelegate func subscription(_ subscription: Subscription, didClearSnapshotForItemName itemName: String?, itemPos: UInt) {} func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forCommandSecondLevelItemWithKey key: String) {} func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?, forCommandSecondLevelItemWithKey key: String) {} func subscription(_ subscription: Subscription, didEndSnapshotForItemName itemName: String?, itemPos: UInt) {} func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forItemName itemName: String?, itemPos: UInt) {} func subscriptionDidRemoveDelegate(_ subscription: Subscription) {} func subscriptionDidAddDelegate(_ subscription: Subscription) {} func subscriptionDidSubscribe(_ subscription: Subscription) {} func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?) {} func subscriptionDidUnsubscribe(_ subscription: Subscription) {} func subscription(_ subscription: Subscription, didReceiveRealFrequency frequency: RealMaxFrequency?) {} func subscription(_ subscription: Subscription, didUpdateItem itemUpdate: ItemUpdate) { // This method is always called from a background thread let itemPosition = UInt(itemUpdate.itemPos) // Check and prepare the item's data structures var item: [String : String?]! = nil var updated: [String : Bool]! = nil lockQueue.sync { item = itemData[itemPosition - 1] if item == nil { item = [String : String?](minimumCapacity: NUMBER_OF_LIST_FIELDS) itemData[itemPosition - 1] = item } updated = self.itemUpdated[itemPosition - 1] if updated == nil { updated = [String : Bool](minimumCapacity: NUMBER_OF_LIST_FIELDS) itemUpdated[itemPosition - 1] = updated } } var previousLastPrice = 0.0 for fieldName in LIST_FIELDS { // Save previous last price to choose blink color later if fieldName == "last_price" { previousLastPrice = Double((item[fieldName] ?? "0") ?? "0") ?? 0.0 } // Store the updated field in the item's data structures let value = itemUpdate.value(withFieldName: fieldName) if value != "" { item?[fieldName] = value } else { item?[fieldName] = nil } if itemUpdate.isValueChanged(withFieldName: fieldName) { updated?[fieldName] = true } } // Evaluate the update color and store it in the item's data structures let currentLastPrice = Double(itemUpdate.value(withFieldName: "last_price") ?? "0") ?? 0 if currentLastPrice >= previousLastPrice { item?["color"] = "green" } else { item?["color"] = "orange" } lockQueue.sync { itemData[itemPosition - 1] = item itemUpdated[itemPosition - 1] = updated } // Mark rows to be reload lockQueue.sync { rowsToBeReloaded.insert(IndexPath(row: Int(itemPosition) - 1, section: 0)) } DispatchQueue.main.async(execute: { [self] in // Update the table view reloadTableRows() }) } } // MARK: - // MARK: StockListViewController extension // MARK: - // MARK: StockListViewController implementation
apache-2.0
9efa2cac7f2d41b517ff098bf95642d9
37.39185
155
0.604638
5.292567
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/LayoutManager.swift
1
16948
// // LayoutManager.swift // // CotEditor // https://coteditor.com // // Created by nakamuxu on 2005-01-10. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // 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 // // https://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 Combine import Cocoa class LayoutManager: NSLayoutManager, InvisibleDrawing, ValidationIgnorable, LineRangeCacheable { // MARK: Protocol Properties var showsControls = false var invisiblesDefaultsObserver: AnyCancellable? var ignoresDisplayValidation = false var string: NSString { self.attributedString().string as NSString } var lineRangeCache = LineRangeCache() // MARK: Public Properties var usesAntialias = true var textFont: NSFont = .systemFont(ofSize: 0) { // store text font to avoid the issue where the line height can be inconsistent by using a fallback font // -> DO NOT use `self.firstTextView?.font`, because when the specified font doesn't support // the first character of the text view content, it returns a fallback font for the first one. didSet { // cache metric values self.defaultLineHeight = self.defaultLineHeight(for: textFont) self.defaultBaselineOffset = self.defaultBaselineOffset(for: textFont) self.boundingBoxForControlGlyph = self.boundingBoxForControlGlyph(for: textFont) self.spaceWidth = textFont.width(of: " ") } } var showsInvisibles = false { didSet { guard showsInvisibles != oldValue else { return } self.invalidateInvisibleDisplay() } } var invisiblesColor: NSColor = .disabledControlTextColor var showsIndentGuides = false var tabWidth = 0 private(set) var spaceWidth: CGFloat = 0 // MARK: Private Properties private var defaultLineHeight: CGFloat = 1.0 private var defaultBaselineOffset: CGFloat = 0 private var boundingBoxForControlGlyph: NSRect = .zero private var indentGuideObserver: AnyCancellable? // MARK: - // MARK: Lifecycle override init() { super.init() self.indentGuideObserver = UserDefaults.standard.publisher(for: .showIndentGuides) .sink { [weak self] _ in guard let self = self, self.showsInvisibles else { return } self.invalidateDisplay(forCharacterRange: self.attributedString().range) } self.delegate = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Layout Manager Methods /// adjust rect of last empty line override func setExtraLineFragmentRect(_ fragmentRect: NSRect, usedRect: NSRect, textContainer container: NSTextContainer) { // -> The height of the extra line fragment should be the same as other normal fragments that are likewise customized in the delegate. var fragmentRect = fragmentRect fragmentRect.size.height = self.lineHeight var usedRect = usedRect usedRect.size.height = self.lineHeight super.setExtraLineFragmentRect(fragmentRect, usedRect: usedRect, textContainer: container) } /// draw glyphs override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint) { NSGraphicsContext.saveGraphicsState() if NSGraphicsContext.currentContextDrawingToScreen() { NSGraphicsContext.current?.shouldAntialias = self.usesAntialias } if self.showsIndentGuides { self.drawIndentGuides(forGlyphRange: glyphsToShow, at: origin, color: self.invisiblesColor, tabWidth: self.tabWidth) } if self.showsInvisibles { self.drawInvisibles(forGlyphRange: glyphsToShow, at: origin, baselineOffset: self.baselineOffset(for: .horizontal), color: self.invisiblesColor, types: UserDefaults.standard.showsInvisible) } super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin) NSGraphicsContext.restoreGraphicsState() } /// fill background rectangles with a color override func fillBackgroundRectArray(_ rectArray: UnsafePointer<NSRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: NSColor) { // modify selected highlight color when the window is inactive // -> Otherwise, `.unemphasizedSelectedContentBackgroundColor` will be used forcibly and text becomes unreadable // when the window appearance and theme are inconsistent. if color == .unemphasizedSelectedContentBackgroundColor, // check if inactive let textContainer = self.textContainer(forGlyphAt: self.glyphIndexForCharacter(at: charRange.location), effectiveRange: nil, withoutAdditionalLayout: true), let theme = (textContainer.textView as? any Themable)?.theme, let secondarySelectionColor = theme.secondarySelectionColor { secondarySelectionColor.setFill() } super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color) } /// invalidate display for the given character range override func invalidateDisplay(forCharacterRange charRange: NSRange) { // ignore display validation during applying temporary attributes continuously // -> See `SyntaxParser.apply(highlights:range:)` for the usage of this option. (2018-12) if self.ignoresDisplayValidation { return } super.invalidateDisplay(forCharacterRange: charRange) } override func setGlyphs(_ glyphs: UnsafePointer<CGGlyph>, properties props: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes charIndexes: UnsafePointer<Int>, font aFont: NSFont, forGlyphRange glyphRange: NSRange) { // fix the width of whitespaces when the base font is fixed pitch. let newProps = UnsafeMutablePointer(mutating: props) if self.textFont.isFixedPitch { for index in 0..<glyphRange.length { newProps[index].subtract(.elastic) } } super.setGlyphs(glyphs, properties: newProps, characterIndexes: charIndexes, font: aFont, forGlyphRange: glyphRange) } override func processEditing(for textStorage: NSTextStorage, edited editMask: NSTextStorageEditActions, range newCharRange: NSRange, changeInLength delta: Int, invalidatedRange invalidatedCharRange: NSRange) { if editMask.contains(.editedCharacters) { self.invalidateLineRanges(in: newCharRange, changeInLength: delta) } super.processEditing(for: textStorage, edited: editMask, range: newCharRange, changeInLength: delta, invalidatedRange: invalidatedCharRange) } // MARK: Invisible Drawing Methods func isInvalidInvisible(_ invisible: Invisible, at characterIndex: Int) -> Bool { switch invisible { case .newLine: return (self.firstTextView?.window?.windowController?.document as? Document)?.lineEndingScanner.isInvalidLineEnding(at: characterIndex) == true default: return false } } // MARK: Public Methods /// Fixed line height to avoid having different line height by composite font. var lineHeight: CGFloat { let multiple = self.firstTextView?.defaultParagraphStyle?.lineHeightMultiple ?? 1.0 return multiple * self.defaultLineHeight } /// Fixed baseline offset to place glyphs vertically in the middle of a line. /// /// - Parameter layoutOrientation: The text layout orientation. /// - Returns: The baseline offset. func baselineOffset(for layoutOrientation: TextLayoutOrientation) -> CGFloat { switch layoutOrientation { case .vertical: return self.lineHeight / 2 default: // remove the space above to make glyphs visually center let diff = self.textFont.ascender - self.textFont.capHeight return (self.lineHeight + self.defaultBaselineOffset - diff) / 2 } } } extension LayoutManager: NSLayoutManagerDelegate { /// adjust line height to be all the same func layoutManager(_ layoutManager: NSLayoutManager, shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<NSRect>, lineFragmentUsedRect: UnsafeMutablePointer<NSRect>, baselineOffset: UnsafeMutablePointer<CGFloat>, in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool { // avoid inconsistent line height by a composite font // -> The line height by normal input keeps consistant when overriding the related methods in NSLayoutManager. // but then, the drawing won't be update properly when the font or line hight is changed. // -> NSParagraphStyle's `.lineheightMultiple` can also control the line height, // but it causes an issue when the first character of the string uses a fallback font. lineFragmentRect.pointee.size.height = self.lineHeight lineFragmentUsedRect.pointee.size.height = self.lineHeight // vertically center the glyphs in the line fragment baselineOffset.pointee = self.baselineOffset(for: textContainer.layoutOrientation) return true } /// treat control characers as whitespace to draw replacement glyphs func layoutManager(_ layoutManager: NSLayoutManager, shouldUse action: NSLayoutManager.ControlCharacterAction, forControlCharacterAt charIndex: Int) -> NSLayoutManager.ControlCharacterAction { // -> Then, the glyph width can be modified in `layoutManager(_:boundingBoxForControlGlyphAt:...)`. return self.showsControlCharacter(at: charIndex, proposedAction: action) ? .whitespace : action } /// make a blank space to draw the replacement glyph in `drawGlyphs(forGlyphRange:at:)` later func layoutManager(_ layoutManager: NSLayoutManager, boundingBoxForControlGlyphAt glyphIndex: Int, for textContainer: NSTextContainer, proposedLineFragment proposedRect: NSRect, glyphPosition: NSPoint, characterIndex charIndex: Int) -> NSRect { return self.boundingBoxForControlGlyph } /// avoid soft wrapping just after indent func layoutManager(_ layoutManager: NSLayoutManager, shouldBreakLineByWordBeforeCharacterAt charIndex: Int) -> Bool { // check if the character is the first non-whitespace character after indent let string = self.attributedString().string as NSString for index in stride(from: charIndex - 1, through: 0, by: -1) { switch string.character(at: index) { case 0x9, 0x20: // tab, space continue case 0xA, 0xD, 0x85, 0x2028, 0x2029: // newlines return index == charIndex - 1 default: return true } } return true } /// apply sytax highlighing on printing also func layoutManager(_ layoutManager: NSLayoutManager, shouldUseTemporaryAttributes attrs: [NSAttributedString.Key: Any] = [:], forDrawingToScreen toScreen: Bool, atCharacterIndex charIndex: Int, effectiveRange effectiveCharRange: NSRangePointer?) -> [NSAttributedString.Key: Any]? { return attrs } } // MARK: Private Extension private extension NSLayoutManager { /// Draw indent guides at every given indent width. /// /// - Parameters: /// - glyphsToShow: The range of glyphs that are drawn. /// - origin: The position of the text container in the coordinate system of the currently focused view. /// - color: The color of guides. /// - tabWidth: The number of spaces for an indent. func drawIndentGuides(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint, color: NSColor, tabWidth: Int) { guard tabWidth > 0 else { return assertionFailure() } // calculate characterRange to seek let string = self.attributedString().string as NSString let charactersToShow = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil) let lineStartIndex = string.lineStartIndex(at: charactersToShow.location) let characterRange = NSRange(location: lineStartIndex, length: charactersToShow.upperBound - lineStartIndex) // find indent indexes var indentIndexes: [(lineRange: NSRange, indexes: [Int])] = [] string.enumerateSubstrings(in: characterRange, options: [.byLines, .substringNotRequired]) { (_, range, _, _) in var indexes: [Int] = [] var spaceCount = 0 loop: for characterIndex in range.lowerBound..<range.upperBound { let isIndentLevel = spaceCount.isMultiple(of: tabWidth) && spaceCount > 0 switch string.character(at: characterIndex) { case 0x0020: // space spaceCount += 1 case 0x0009: // tab spaceCount += tabWidth - (spaceCount % tabWidth) default: break loop } if isIndentLevel { indexes.append(characterIndex) } } guard !indexes.isEmpty else { return } indentIndexes.append((range, indexes)) } guard !indentIndexes.isEmpty else { return } NSGraphicsContext.saveGraphicsState() color.set() let lineWidth: CGFloat = 0.5 let scaleFactor = NSGraphicsContext.current?.cgContext.ctm.a ?? 1 // draw guides logical line by logical line for (lineRange, indexes) in indentIndexes { // calculate vertical area to draw lines let glyphIndex = self.glyphIndexForCharacter(at: lineRange.location) var effectiveRange: NSRange = .notFound let lineFragment = self.lineFragmentRect(forGlyphAt: glyphIndex, effectiveRange: &effectiveRange) let guideLength: CGFloat = { guard !effectiveRange.contains(lineRange.upperBound - 1) else { return lineFragment.height } let lastGlyphIndex = self.glyphIndexForCharacter(at: lineRange.upperBound - 1) let lastLineFragment = self.lineFragmentRect(forGlyphAt: lastGlyphIndex, effectiveRange: nil) // check whether hanging indent is enabled guard lastLineFragment.minX != lineFragment.minX else { return lineFragment.height } return lastLineFragment.maxY - lineFragment.minY }() let guideSize = NSSize(width: lineWidth, height: guideLength) // draw lines for index in indexes { let glyphIndex = self.glyphIndexForCharacter(at: index) let glyphLocation = self.location(forGlyphAt: glyphIndex) let guideOrigin = lineFragment.origin.offset(by: origin).offsetBy(dx: glyphLocation.x).aligned(scale: scaleFactor) let guideRect = NSRect(origin: guideOrigin, size: guideSize) guideRect.fill() } } NSGraphicsContext.restoreGraphicsState() } } private extension CGPoint { /// Make the point pixel-perfect with the desired scale. /// /// - Parameter scale: The scale factor in which the receiver to be pixel-perfect. /// - Returns: An adjusted point. func aligned(scale: CGFloat = 1) -> Self { return Self(x: (self.x * scale).rounded() / scale, y: (self.y * scale).rounded() / scale) } }
apache-2.0
231094003c70cddb4f07cb4cda493fe9
39.347619
309
0.63903
5.298937
false
false
false
false
motoom/ios-apps
DragView/DragView/ViewController.swift
1
2034
// // ViewController.swift // DragView // // Created by User on 2016-02-14. // Copyright © 2016 motoom. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var fieldView: FieldView! @IBOutlet weak var dragView: DragView! @IBOutlet weak var dragLabel: UILabel! @IBOutlet var tap: UITapGestureRecognizer! var dragging: Int? // hashValue of UITouch dragging the view var dragoffset: CGPoint = CGPoint() override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { if dragView == touch.view { dragging = touch.hashValue dragLabel.text = String(touch.hashValue) dragoffset = touch.locationInView(dragView) } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { if touch.hashValue == dragging { let x = touch.locationInView(fieldView).x - dragoffset.x let y = touch.locationInView(fieldView).y - dragoffset.y dragView.frame.origin = CGPoint(x: x, y: y) let middle = CGPoint(x: dragView.center.x, y: dragView.center.y) let snapped = gridsnap(middle, CGPoint(x: 2, y: 2), CGPoint(x: 30, y: 30)) fieldView.registerPoint(snapped) fieldView.setNeedsDisplay() } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { if touch.hashValue == dragging { dragLabel.text = "" dragging = nil } } } override func viewDidLoad() { super.viewDidLoad() tap.cancelsTouchesInView = false } @IBAction func tapped(sender: UITapGestureRecognizer) { fieldView.reset() fieldView.setNeedsDisplay() } }
mit
465d54b8f5829d1c64b8b427ab4561d3
29.343284
90
0.580423
4.706019
false
false
false
false
ymkjp/NewsPlayer
NewsPlayer/VideoTableViewCell.swift
1
2220
// // VideoTableViewCell.swift // NewsPlayer // // Created by YAMAMOTOKenta on 9/19/15. // Copyright © 2015 ymkjp. All rights reserved. // import UIKit import FLAnimatedImage class VideoTableViewCell: UITableViewCell { @IBOutlet weak var thumbnail: UIImageView! @IBOutlet weak var abstract: UILabel! @IBOutlet weak var indicator: UIView! let animatedImageView = FLAnimatedImageView() 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 } // :param: index Let them know the indexPath.row, cell does not remember wchich indexPath it belongs func render(index: Int) -> VideoTableViewCell { if let video = ChannelModel.sharedInstance.getVideoByIndex(index) { abstract?.numberOfLines = 0 abstract?.text = "\(video.title)\n\(video.description)" thumbnail?.sd_setImageWithURL(NSURL(string: video.thumbnail.url)) } else { abstract.text = "textLabel #\(index)" } return self } func addPlayingIndicator() { indicator?.addSubview(createIndicationView()) } func removeAllIndicator() { guard let subviews = indicator?.subviews else { return } for subview in subviews { subview.removeFromSuperview() } } func startPlayingAnimation() { animatedImageView.startAnimating() } func stopPlayingAnimation() { animatedImageView.stopAnimating() } private func createIndicationView() -> UIImageView { let path = NSBundle.mainBundle().pathForResource("equalizer", ofType: "gif")! let url = NSURL(fileURLWithPath: path) let animatedImage = FLAnimatedImage(animatedGIFData: NSData(contentsOfURL: url)) animatedImageView.animatedImage = animatedImage animatedImageView.frame = indicator.bounds animatedImageView.contentMode = UIViewContentMode.ScaleAspectFit return animatedImageView } }
mit
3dd4dbbab722f13cbf469170f8455bb7
29.39726
104
0.653898
5.258294
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteAuth/model.Role200Entity.swift
1
1390
import OpenbuildExtensionPerfect public class ModelRole200Entity: ResponseModel200Entity, DocumentationProtocol { public var descriptions = [ "error": "An error has occurred, will always be false", "message": "Will always be 'Successfully created/fetched the entity.'", "entity": "Object describing the role." ] public init(entity: ModelRole) { super.init(entity: entity) } public static func describeRAML() -> [String] { if let docs = ResponseDocumentation.getRAML(key: "RouteAuth.ModelRole200Entity") { return docs } else { let entity = ModelRole(role_id: 1, role: "RoleExample") let model = ModelRole200Entity(entity: entity) let aMirror = Mirror(reflecting: model) let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions) ResponseDocumentation.setRAML(key: "RouteAuth.ModelRole200Entity", lines: docs) return docs } } } extension ModelRole200Entity: CustomReflectable { open var customMirror: Mirror { return Mirror( self, children: [ "error": self.error, "message": self.message, "entity": self.entity ], displayStyle: Mirror.DisplayStyle.class ) } }
gpl-2.0
62d1e38b02d52301c92738e8b128d8e4
25.75
103
0.609353
4.744027
false
false
false
false
KVTaniguchi/KTCarousel
Example/KTCarousel/BaseDestinationViewController.swift
1
1267
// // BaseDestinationViewController.swift // KTCarousel // // Created by Kevin Taniguchi on 6/13/16. // Copyright © 2016 Kevin Taniguchi. All rights reserved. // import UIKit import KTCarousel typealias EmptyHandler = () -> Void class BaseDestinationViewController: UIViewController, KTSynchronizingDelegate { let destinationCollectionView: UICollectionView var exampleData = UIImage.testingImages() var selectedPath: IndexPath? var dismissCallback: EmptyHandler? init() { let layout = KTHorizontalPagedFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 1.0 layout.minimumLineSpacing = 1.0 destinationCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK Sync Delegate func sourceIndexPath() -> IndexPath? { guard let path = selectedPath else { return IndexPath(item: 0, section: 0) } return path } func toCollectionView() -> UICollectionView? { return destinationCollectionView } }
mit
6bd6142c3eb4c228d8763dc264a8f810
27.772727
102
0.680885
4.888031
false
false
false
false
douglasak/automation
Send AC Code.swift
1
1982
func sendACCode(id: String) { var modeCode: Int var tempAdj: Int var tempCode: Int = 0 switch modeSelect { case Mode.Cold: modeCode = 0x8820 * 256 case Mode.Fan: modeCode = 0x8822 * 256 case Mode.Dry: modeCode = 0x8821 * 256 case Mode.Saver: modeCode = 0x8826 * 256 } switch fanSelect { case FanSpeed.Low: tempAdj = 0 case FanSpeed.Medium: tempAdj = 2 case FanSpeed.High: tempAdj = 4 } if (tempSelect >= 60 && tempSelect < 75) { tempCode = 16 * (tempSelect - 60 + 1) } else if (tempSelect > 74 && tempSelect <= 86) { tempCode = 16 * (tempSelect - 75 + 1) - 8 } let sum = modeCode + tempCode + tempAdj var sumString = String(sum, radix: 16).uppercaseString var checkSum = 0 for i in 0 ..< sumString.characters.count { let index = sumString.startIndex.advancedBy(i) let char = sumString[index] let hex = "0x" + String(char) let value = Int(strtoul(hex, nil, 16)) checkSum += value } let hexCheckSum = String(checkSum, radix: 16).uppercaseString if let lastChar = hexCheckSum.characters.last { sumString += String(lastChar) sendCode(id, arg: sumString) } } func sendCode(id: String, arg: String) { var urlString = "http://" + id + ".local/" urlString += "code?ac" + "=" + arg print(urlString) let url = NSURL(string: urlString) let urlRequest = NSMutableURLRequest(URL: url!) let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.timeoutIntervalForRequest = 5 let session = NSURLSession(configuration: configuration) let dataSession = session.dataTaskWithRequest(urlRequest) dataSession.resume() }
mit
a947dc7bd3bc34461821ec3f5f59405d
22.329412
79
0.565086
4.262366
false
true
false
false
russbishop/swift
stdlib/public/SDK/Foundation/NSStringAPI.swift
1
69167
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: @noescape (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } func _toNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange( location: r.lowerBound._utf16Index, length: r.upperBound._utf16Index - r.lowerBound._utf16Index) } func _countFormatSpecifiers(_ a: String) -> Int { // The implementation takes advantage of the fact that internal // representation of String is UTF-16. Because we only care about the ASCII // percent character, we don't need to decode UTF-16. let percentUTF16 = UTF16.CodeUnit(("%" as UnicodeScalar).value) let notPercentUTF16: UTF16.CodeUnit = 0 var lastChar = notPercentUTF16 // anything other than % would work here var count = 0 for c in a.utf16 { if lastChar == percentUTF16 { if c == percentUTF16 { // a "%" following this one should not be taken as literal lastChar = notPercentUTF16 } else { count += 1 lastChar = c } } else { lastChar = c } } return count } // 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: @noescape (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } extension String { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. var _ns: NSString { return self as NSString } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _index(_ utf16Index: Int) -> Index { return Index(_base: String.UnicodeScalarView.Index(utf16Index, _core)) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _range(_ r: NSRange) -> Range<Index> { return _index(r.location)..<_index(r.location + r.length) } /// 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 _range(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: @noescape (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = self._index(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: @noescape (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._range(nsRange) return result } //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// Returns an Array of the encodings string objects 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; /// Returns 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 a given encoding. 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 *)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 { return NSString.path(withComponents: components) } //===--------------------------------------------------------------------===// // 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 /// Produces a string created by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let ns = NSString(utf8String: bytes) { self = ns as String } else { return nil } } //===--- 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 a given encoding without loss of /// information. public func canBeConverted(to encoding: Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// Produce a string with the first character from each word changed /// to the corresponding uppercase value. public var capitalized: String { return _ns.capitalized as String } // @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(OSX 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) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare(_ aString: String) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString) } //===--- 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 the `String` and a /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix( with aString: String, options: CompareOptions = []) -> String { return _ns.commonPrefix(with: aString, 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( _ aString: String, options mask: 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. return locale != nil ? _ns.compare( aString, options: mask, range: _toNSRange( range ?? self.characters.startIndex..<self.characters.endIndex ), locale: locale ) : range != nil ? _ns.compare( aString, options: mask, range: _toNSRange(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 { 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 = AutoreleasingUnsafeMutablePointer<NSString?>( UnsafeMutablePointer<NSString>(outputName) ) let outputNonOptionalArray = AutoreleasingUnsafeMutablePointer<NSArray?>( UnsafeMutablePointer<NSArray>(outputArray) ) 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 } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the `String` /// that have been divided by characters in a given set. public func components(separatedBy separator: CharacterSet) -> [String] { // FIXME: two steps due to <rdar://16971181> let nsa = _ns.components(separatedBy: separator) as NSArray // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion return nsa as! [String] } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the `String` /// that have been divided by a given separator. public func components(separatedBy separator: String) -> [String] { let nsa = _ns.components(separatedBy: separator) as NSArray // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion return nsa as! [String] } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` as a C string /// using a given encoding. public func cString(using encoding: 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: Encoding, allowLossyConversion: Bool = false ) -> Data? { return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } // @property NSString* decomposedStringWithCanonicalMapping; /// Returns a string made by normalizing the `String`'s /// contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// Returns a string made 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(_ body: (line: String, stop: inout Bool) -> ()) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line: line, stop: &stop_) if stop_ { UnsafeMutablePointer<ObjCBool>(stop).pointee = true } } } // - (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( in range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> () ) { _ns.enumerateLinguisticTags( in: _toNSRange(range), scheme: tagScheme, options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } // - (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. public func enumerateSubstrings( in range: Range<Index>, options opts: EnumerationOptions = [], _ body: ( substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool ) -> () ) { _ns.enumerateSubstrings(in: _toNSRange(range), options: opts) { var stop_ = false body(substring: $0, substringRange: self._range($1), enclosingRange: self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } // @property NSStringEncoding fastestEncoding; /// Returns the fastest encoding to which the `String` may be /// converted without loss of information. public var fastestEncoding: Encoding { return Encoding(rawValue: _ns.fastestEncoding) } // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { return _persistCString(_ns.fileSystemRepresentation)! } //===--- 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` iff some characters were converted. /// /// - 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( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: Encoding, options: EncodingConversionOptions = [], range: Range<Index>, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toNSRange(range), remaining: $0) } } // - (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: Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (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 { return _ns.getFileSystemRepresentation( &buffer, maxLength: min(buffer.count, maxLength)) } // - (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( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: Range<Index> ) { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toNSRange(range)) } } } } // - (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( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: Range<Index> ) { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toNSRange(range)) } } } } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Produces an initialized `NSString` object equivalent to the given /// `bytes` interpreted in the given `encoding`. public init? <S: Sequence>(bytes: S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = ns as String } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Produces an initialized `String` object that contains a /// given number of bytes from a given buffer of bytes interpreted /// in a given encoding, and optionally frees the buffer. WARNING: /// this initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = ns as String } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Returns an initialized `String` object that contains a /// given number of characters from a given array of Unicode /// characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = NSString(characters: utf16CodeUnits, length: count) as String } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Returns an initialized `String` object that contains a given /// number of characters from a given array of UTF-16 Code Units public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = NSString( charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag) as String } //===--- 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: String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = ns as String } // - (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: String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = ns as String } public init( contentsOfFile path: String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = ns as String } // - (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: URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = ns as String } // - (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: URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = ns as String } public init( contentsOf url: URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = ns as String } // - (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 let ns = NSString(cString: cString, encoding: enc.rawValue) { self = ns as String } 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: Data, encoding: Encoding) { guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = s as String } // - (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: 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: String, arguments: [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: String, locale: 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: String, locale: Locale?, arguments: [CVarArg]) { _precondition( _countFormatSpecifiers(format) <= arguments.count, "Too many format specifiers (%<letter>) provided for the argument list" ) self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } } //===--- 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 //===--- 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 { return _ns.lastPathComponent } //===--- 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 { return _ns.length } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange(for aRange: Range<Index>) -> Range<Index> { return _range(_ns.lineRange(for: _toNSRange(aRange))) } // - (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( in range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] { var nsTokenRanges: NSArray? = nil let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toNSRange(range), scheme: tagScheme, options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if nsTokenRanges != nil { tokenRanges?.pointee = (nsTokenRanges! as [AnyObject]).map { self._range($0.rangeValue) } } return result as! [String] } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and a given string using a /// case-insensitive, localized, comparison. public func localizedCaseInsensitiveCompare(_ aString: String) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and a given string using a localized /// comparison. public func localizedCompare(_ aString: String) -> ComparisonResult { return _ns.localizedCompare(aString) } /// Compares strings as sorted by the Finder. public func localizedStandardCompare(_ string: String) -> ComparisonResult { return _ns.localizedStandardCompare(string) } //===--- 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(OSX 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: Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange(for aRange: Range<Index>) -> Range<Index> { return _range(_ns.paragraphRange(for: _toNSRange(aRange))) } // @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] { return _ns.pathComponents } // @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 { return _ns.pathExtension } // @property NSString* precomposedStringWithCanonicalMapping; /// Returns a string made by normalizing the `String`'s /// contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// Returns a string made by normalizing the `String`'s /// contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } // - (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() -> AnyObject { 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] } // - (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: CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toNSRange( aRange ?? self.characters.startIndex..<self.characters.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 _range( _ns.rangeOfComposedCharacterSequence(at: anIndex._utf16Index)) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences( for range: Range<Index> ) -> Range<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 _range( _ns.rangeOfComposedCharacterSequences(for: _toNSRange(range))) } // - (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( of aString: String, options mask: CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toNSRange( searchRange ?? self.characters.startIndex..<self.characters.endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns `true` if `self` contains `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(OSX 10.11, iOS 9.0, *) public func localizedStandardContains(_ string: String) -> Bool { return _ns.localizedStandardContains(string) } // - (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(OSX 10.11, iOS 9.0, *) public func localizedStandardRange(of string: String) -> Range<Index>? { return _optionalRange(_ns.localizedStandardRange(of: string)) } // @property NSStringEncoding smallestEncoding; /// Returns the smallest encoding to which the `String` can /// be converted without loss of information. public var smallestEncoding: Encoding { return Encoding(rawValue: _ns.smallestEncoding) } // @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 { return _ns.abbreviatingWithTildeInPath } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string made from the `String` by replacing /// all characters 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 *) // 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(*, deprecated, 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: Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string made by appending to the `String` a /// string constructed from a given format string and the following /// arguments. public func appendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format, arguments: arguments)) } // - (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 { return _ns.appendingPathComponent(aString) } // - (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? { // FIXME: This method can return nil in practice, for example when self is // an empty string. OTOH, this is not documented, documentation says that // it always returns a string. // // <rdar://problem/17902469> -[NSString stringByAppendingPathExtension] can // return nil return _ns.appendingPathExtension(ext) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string made by appending a given string to /// the `String`. public func appending(_ aString: String) -> String { return _ns.appending(aString) } // @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 { return _ns.deletingLastPathComponent } // @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 { return _ns.deletingPathExtension } // @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 { return _ns.expandingTildeInPath } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: CompareOptions = [], locale: Locale? ) -> String { return folding(options: options, locale: locale) } /// Returns a string with the given character folding options /// applied. public func folding( options: 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( toLength newLength: Int, withPad padString: String, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// Returns 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( in range: Range<Index>, with replacement: String ) -> String { return _ns.replacingCharacters(in: _toNSRange(range), with: replacement) } // - (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( of target: String, with replacement: String, options: CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toNSRange( searchRange ?? self.characters.startIndex..<self.characters.endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } // - (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(*, deprecated, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } // @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 { return _ns.resolvingSymlinksInPath } // @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 { return _ns.standardizingPath } // - (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) } // - (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("This function is not available") } // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. public func substring(from index: Index) -> String { return _ns.substring(from: index._utf16Index) } // - (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. public func substring(to index: Index) -> String { return _ns.substring(to: index._utf16Index) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toNSRange(aRange)) } // @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(OSX 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase as String } // - (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( toFile path: String, atomically useAuxiliaryFile:Bool, encoding enc: Encoding ) throws { try self._ns.write( toFile: path, 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: Encoding ) throws { try self._ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); /// Perform string transliteration. @available(OSX 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } //===--- 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` iff `other` is non-empty and contained within /// `self` by case-sensitive, non-literal search. /// /// Equivalent to `self.rangeOfString(other) != nil` public func contains(_ other: String) -> Bool { let r = self.range(of: other) != nil if #available(OSX 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.contains(other)) } return r } /// Returns `true` iff `other` is non-empty and contained within /// `self` 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 /// `rangeOfString(_:options:_, range:_locale:_)`. /// /// Equivalent to /// /// self.rangeOf( /// other, options: .CaseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains(_ other: String) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(OSX 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.localizedCaseInsensitiveContains(other)) } return r } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: 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") } @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: 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: 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: "componentsSeparated(by:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } @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) -> () ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: EnumerationOptions = [], _ body: ( substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool ) -> () ) { 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: Encoding, options: 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: 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") } @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") } @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: 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: 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: 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: 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: CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: 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: 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: Encoding ) throws { fatalError("unavailable function can't be called") } }
apache-2.0
fc54355b45a6c8df6e2005764d8ca53e
33.809763
303
0.673515
4.771783
false
false
false
false
sunlijian/sinaBlog_repository
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/Controller/IWComposeViewController.swift
1
10893
// // IWComposeViewController.swift // sinaBlog_sunlijian // // Created by sunlijian on 15/10/20. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit import SVProgressHUD import AFNetworking //图片整体 view let COMPOSE_PHOTOS_VIEW_MARGIN: CGFloat = 10 class IWComposeViewController: UIViewController, UITextViewDelegate, IWComposeToolBarDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() //设置导航 setNav() //设置view setView() //添加通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionButtonDidSelected:", name: IWEmotionButtonDidSelectedNotification, object: nil) //添加删除字符的通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionDeleteButtonClick", name: "IWEmotionDeleteButtonDidSelectedNotification", object: nil) } //设置导航 private func setNav(){ //左边 item navigationItem.leftBarButtonItem = UIBarButtonItem.item("", title: "取消", target: self, action: "cancel") //右边 item navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) navigationItem.rightBarButtonItem?.enabled = false //中间的 titleView navigationItem.titleView = titleView } //设置view private func setView(){ //添加 textView textView.size = CGSizeMake(SCREEN_W, SCREEN_H) //添加的时候 textView 的y 会以 navgationBar 的高度决定 view.addSubview(textView) //配图控件 composePhotosView.x = COMPOSE_PHOTOS_VIEW_MARGIN composePhotosView.y = 100 composePhotosView.addButtonClickBlock = { //闭包内容 self.selectPictureButtonClick() } textView.addSubview(composePhotosView) //添加底部 toolBar toolBar.y = SCREEN_H - toolBar.height view.addSubview(toolBar) //监听键盘 NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } //加载完 textView 的时候弹出键盘 override func viewWillAppear(animated: Bool) { textView.becomeFirstResponder() } //调整位置 //左边 item @objc private func cancel(){ dismissViewControllerAnimated(true, completion: nil) } //右边 item @objc private func sendMessage(){ } //titleView懒加载 private lazy var titleView: UILabel = { let label = UILabel() //设置字体 label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center // if let name = IWUserAccount.loadAccount()?.name { label.text = "发微博\n\(name)" //初始化一个带有属性的文字 var attr = NSMutableAttributedString(string: label.text!) //名字在 label 上的位置 let range = (label.text! as NSString).rangeOfString(name) //添加属性 attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range:range) attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range) // label.attributedText = attr }else{ label.text = "写微博" } label.sizeToFit() return label }() //右边懒加载 private lazy var rightButton: UIButton = { let button = UIButton() //设置 button 的文字颜色 button.setTitle("发送", forState: UIControlState.Normal) button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled) //设置 button 的背景色 button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted) button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled) button.size = CGSizeMake(44, 30) button.titleLabel?.font = UIFont.systemFontOfSize(14) //添加点击事件 button.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside) return button }() //textView 的懒加载 private lazy var textView: IWEmotionTextView = { let textView = IWEmotionTextView() textView.placeHoldLableText = "label.text = 听说下雪天,吃冰棍特别2B哦" textView.font = UIFont.systemFontOfSize(16) textView.alwaysBounceVertical = true textView.delegate = self return textView }() //textView的delegate func textViewDidChange(textView: UITextView) { navigationItem.rightBarButtonItem?.enabled = textView.hasText() } //当向下拉拽屏幕的时候 func scrollViewDidScroll(scrollView: UIScrollView) { textView.resignFirstResponder() } //textView 里的显示图片的懒加载 private lazy var composePhotosView :IWComposePhotosView = { let view = IWComposePhotosView() let viewHW = SCREEN_W - 2 * COMPOSE_PHOTOS_VIEW_MARGIN view.size = CGSizeMake(viewHW, viewHW) return view }() //添加键盘 private lazy var keyboard: IWEmotionKeyboard = { let keyboard = IWEmotionKeyboard() keyboard.size = CGSizeMake(SCREEN_W, 258) return keyboard }() //底部 toolBar 的懒加载 private lazy var toolBar: IWComposeToolBar = { let toolBar = IWComposeToolBar() toolBar.size = CGSizeMake(SCREEN_W, 44) toolBar.delegate = self return toolBar }() //监听键盘通知 @objc private func keyboardWillChangeFrame(notify: NSNotification){ print(notify) //取出动画执行的时间 let duration = (notify.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue //取出键盘的最终位置 let rect = (notify.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue() //执行动画 UIView.animateWithDuration(duration) { () -> Void in self.toolBar.y = rect.origin.y - self.toolBar.height } } //添加字符 @objc private func emotionButtonDidSelected(notify: NSNotification){ //取出 emotion let emotion = notify.userInfo!["IWEmotionNotifyKey"] as! IWEmotion //设置 emotion 表情到 IWEmotionTextView 上 textView.insertEmotion(emotion) } //删除字符 @objc private func emotionDeleteButtonClick(){ textView.deleteBackward() } //发送 @objc private func send(){ //判断是否有图片 if composePhotosView.images.count > 0 { sendPicStatus(textView.text, image: composePhotosView.images.first!) }else{ //是文字 sendTextStatus(textView.emotionText) } } //发送文字 private func sendTextStatus(text: String){ let url = "https://api.weibo.com/2/statuses/update.json" let params = [ "status": text, "access_token": IWUserAccount.loadAccount()!.access_token! ] IWNetWorkTools.request(.POST, url: url, paramters: params, success: { (result) -> () in // SVProgressHUD.showSuccessWithStatus("发送成功") }) { (error) -> () in // SVProgressHUD.showErrorWithStatus("发送失败") } } //发送带图的微博 private func sendPicStatus(text: String, image:UIImage){ let url = "https://upload.api.weibo.com/2/statuses/upload.json" let params = [ "status": text, "access_token": IWUserAccount.loadAccount()!.access_token! ] let manager = AFHTTPSessionManager() manager.POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in let data = UIImageJPEGRepresentation(image, 1) formData.appendPartWithFileData(data!, name: "pic", fileName: "hiahia.jepg", mimeType: "image/jpeg") }, success: { (dataTask, result) -> Void in SVProgressHUD.showSuccessWithStatus("发送成功") }) { (dataTask, error) -> Void in SVProgressHUD.showErrorWithStatus("发送失败") } } //IWComposeToolBar的 delegate方法 func composeToolBarButtonDidClick(toolBar: IWComposeToolBar, type: ButtonType){ switch type { case .Picture: selectPictureButtonClick() case .Mention: print("@") case .Trend: print("话题") case .Emotion: switchKeyboard() case .Add: print("添加") } } //点击选择图片按钮 private func selectPictureButtonClick(){ //创建一个图片选择器 let imagePicker = UIImagePickerController() //指定图片来源 imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary //设置当前控制器为代理 imagePicker.delegate = self //弹出选择器 presentViewController(imagePicker, animated: true) { () -> Void in } } //选择键盘 private func switchKeyboard(){ textView.resignFirstResponder() //设置 textView 的输入 view textView.inputView = textView.inputView == nil ? self.keyboard : nil dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in textView.becomeFirstResponder() } } //图片选择器的代理方法 func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { composePhotosView.addImage(image.scale(300)) //选择完图片后 dismiss 控制器 picker.dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } //删除通知 deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } }
apache-2.0
80c9d74c333fbf43dc92a26355c4cfb5
32.377049
167
0.623969
4.920251
false
false
false
false
externl/ice
swift/test/Ice/stream/Client.swift
1
22867
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import TestCommon public class Client: TestHelperI { public override func run(args: [String]) throws { var writer = getWriter() writer.write("testing primitive types... ") var initData = Ice.InitializationData() initData.properties = try createTestProperties(args) initData.classResolverPrefix = ["IceStrem"] let communicator = try initialize(initData) defer { communicator.destroy() } try communicator.getValueFactoryManager().add( factory: { Ice.InterfaceByValue(id: $0) }, id: "::Test::MyInterface" ) var inS: Ice.InputStream var outS: Ice.OutputStream do { let data = Data() inS = Ice.InputStream(communicator: communicator, bytes: data) } do { outS = Ice.OutputStream(communicator: communicator) outS.startEncapsulation() outS.write(true) outS.endEncapsulation() let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) try inS.startEncapsulation() var value: Bool = try inS.read() try test(value) inS = Ice.InputStream(communicator: communicator, bytes: data) try inS.startEncapsulation() value = try inS.read() try test(value) } do { inS = Ice.InputStream(communicator: communicator, bytes: Data()) do { _ = try inS.read() as Bool try test(false) } catch {} } do { outS = Ice.OutputStream(communicator: communicator) outS.write(true) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Bool = try inS.read() try test(value) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(UInt8(1)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: UInt8 = try inS.read() try test(value == 1) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(Int16(2)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Int16 = try inS.read() try test(value == 2) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(Int32(3)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Int32 = try inS.read() try test(value == 3) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(Int64(4)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Int64 = try inS.read() try test(value == 4) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(Float(5.0)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Float = try inS.read() try test(value == 5.0) } do { outS = Ice.OutputStream(communicator: communicator) outS.write(Double(6.0)) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: Double = try inS.read() try test(value == 6.0) } do { outS = Ice.OutputStream(communicator: communicator) outS.write("hello world") let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let value: String = try inS.read() try test(value == "hello world") } writer.writeLine("ok") writer.write("testing constructed types... ") do { outS = Ice.OutputStream(communicator: communicator) outS.write(MyEnum.enum3) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let e: MyEnum = try inS.read() try test(e == MyEnum.enum3) } do { outS = Ice.OutputStream(communicator: communicator) var s = SmallStruct() s.bo = true s.by = 1 s.sh = 2 s.i = 3 s.l = 4 s.f = 5.0 s.d = 6.0 s.str = "7" s.e = MyEnum.enum2 s.p = uncheckedCast(prx: try communicator.stringToProxy("test:default")!, type: MyInterfacePrx.self) outS.write(s) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let s2: SmallStruct = try inS.read() try test(s2.bo == true) try test(s2.by == 1) try test(s2.sh == 2) try test(s2.i == 3) try test(s2.l == 4) try test(s2.f == 5.0) try test(s2.d == 6.0) try test(s2.str == "7") try test(s2.e == MyEnum.enum2) try test(s2.p == s.p) } do { outS = Ice.OutputStream(communicator: communicator) let o = OptionalClass() o.bo = true o.by = 5 o.sh = 4 o.i = 3 outS.write(o) outS.writePendingValues() let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) var o2: OptionalClass? try inS.read(OptionalClass.self) { o2 = $0 } try inS.readPendingValues() try test(o2!.bo == o.bo) try test(o2!.by == o.by) if communicator.getProperties().getProperty("Ice.Default.EncodingVersion") == "1.0" { try test(o2!.sh == nil) try test(o2!.i == nil) } else { try test(o2!.sh == o.sh) try test(o2!.i == o.i) } } do { outS = Ice.OutputStream(communicator: communicator, encoding: Ice.Encoding_1_0) let o = OptionalClass() o.bo = true o.by = 5 o.sh = 4 o.i = 3 outS.write(o) outS.writePendingValues() let data = outS.finished() inS = Ice.InputStream(communicator: communicator, encoding: Ice.Encoding_1_0, bytes: data) var o2: OptionalClass? try inS.read(OptionalClass.self) { o2 = $0 } try inS.readPendingValues() try test(o2!.bo == o.bo) try test(o2!.by == o.by) try test(o2!.sh == nil) try test(o2!.i == nil) } do { let arr = [true, false, true, false] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Bool] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) BoolSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S: [[Bool]] = try BoolSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr = ByteSeq([0x01, 0x11, 0x12, 0x22]) outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: ByteSeq = try inS.read() try test(arr2 == arr) let arrS = [arr, ByteSeq(), arr] outS = Ice.OutputStream(communicator: communicator) ByteSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try ByteSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [Int16] = [0x01, 0x11, 0x12, 0x22] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Int16] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) ShortSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try ShortSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [Int32] = [0x01, 0x11, 0x12, 0x22] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Int32] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) IntSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try IntSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [Int64] = [0x01, 0x11, 0x12, 0x22] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Int64] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) LongSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try LongSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [Float] = [1, 2, 3, 4] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Float] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) FloatSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try FloatSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [Double] = [1, 2, 3, 4] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [Double] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) DoubleSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try DoubleSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [String] = ["string1", "string2", "string3", "string4"] outS = Ice.OutputStream(communicator: communicator) outS.write(arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [String] = try inS.read() try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) StringSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try StringSSHelper.read(from: inS) try test(arr2S == arrS) } do { let arr: [MyEnum] = [MyEnum.enum3, MyEnum.enum2, MyEnum.enum1, MyEnum.enum2] outS = Ice.OutputStream(communicator: communicator) MyEnumSHelper.write(to: outS, value: arr) var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [MyEnum] = try MyEnumSHelper.read(from: inS) try test(arr2 == arr) let arrS = [arr, [], arr] outS = Ice.OutputStream(communicator: communicator) MyEnumSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try MyEnumSSHelper.read(from: inS) try test(arr2S == arrS) } var smallStructArray = [SmallStruct]() for i in 0 ..< 3 { smallStructArray.append(SmallStruct()) smallStructArray[i].bo = true smallStructArray[i].by = 1 smallStructArray[i].sh = 2 smallStructArray[i].i = 3 smallStructArray[i].l = 4 smallStructArray[i].f = 5.0 smallStructArray[i].d = 6.0 smallStructArray[i].str = "7" smallStructArray[i].e = MyEnum.enum2 smallStructArray[i].p = uncheckedCast(prx: try communicator.stringToProxy("test:default")!, type: MyInterfacePrx.self) } var myClassArray = [MyClass]() for i in 0 ..< 4 { myClassArray.append(MyClass()) myClassArray[i].c = myClassArray[i] myClassArray[i].o = myClassArray[i] myClassArray[i].s = SmallStruct() myClassArray[i].s.e = MyEnum.enum2 myClassArray[i].seq1 = [true, false, true, false] myClassArray[i].seq2 = ByteSeq([1, 2, 3, 4]) myClassArray[i].seq3 = [1, 2, 3, 4] myClassArray[i].seq4 = [1, 2, 3, 4] myClassArray[i].seq5 = [1, 2, 3, 4] myClassArray[i].seq6 = [1, 2, 3, 4] myClassArray[i].seq7 = [1, 2, 3, 4] myClassArray[i].seq8 = ["string1", "string2", "string3", "string4"] myClassArray[i].seq9 = [MyEnum.enum3, MyEnum.enum2, MyEnum.enum1] myClassArray[i].seq10 = [nil, nil, nil, nil] myClassArray[i].d = ["hi": myClassArray[i]] } var myInterfaceArray = [Ice.Value]() for _ in 0 ..< 4 { myInterfaceArray.append(Ice.InterfaceByValue(id: "::Test::MyInterface")) } do { outS = Ice.OutputStream(communicator: communicator) MyClassSHelper.write(to: outS, value: myClassArray) outS.writePendingValues() var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2: [MyClass?] = try MyClassSHelper.read(from: inS) try inS.readPendingValues() try test(myClassArray.count == arr2.count) for i in 0 ..< myClassArray.count { try test(arr2[i] != nil) try test(arr2[i]!.c === arr2[i]) try test(arr2[i]!.o === arr2[i]) try test(arr2[i]!.s.e == MyEnum.enum2) try test(arr2[i]!.seq1 == myClassArray[i].seq1) try test(arr2[i]!.seq2 == myClassArray[i].seq2) try test(arr2[i]!.seq3 == myClassArray[i].seq3) try test(arr2[i]!.seq4 == myClassArray[i].seq4) try test(arr2[i]!.seq5 == myClassArray[i].seq5) try test(arr2[i]!.seq6 == myClassArray[i].seq6) try test(arr2[i]!.seq7 == myClassArray[i].seq7) try test(arr2[i]!.seq8 == myClassArray[i].seq8) try test(arr2[i]!.seq9 == myClassArray[i].seq9) try test(arr2[i]!.d["hi"]! === arr2[i]) } let arrS = [myClassArray, [], myClassArray] outS = Ice.OutputStream(communicator: communicator) MyClassSSHelper.write(to: outS, value: arrS) outS.writePendingValues() data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try MyClassSSHelper.read(from: inS) try test(arr2S.count == arrS.count) try test(arr2S[0].count == arrS[0].count) try test(arr2S[1].count == arrS[1].count) try test(arr2S[2].count == arrS[2].count) } do { outS = Ice.OutputStream(communicator: communicator) MyInterfaceSHelper.write(to: outS, value: myInterfaceArray) outS.writePendingValues() var data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2 = try MyInterfaceSHelper.read(from: inS) try inS.readPendingValues() try test(arr2.count == myInterfaceArray.count) let arrS = [myInterfaceArray, [], myInterfaceArray] outS = Ice.OutputStream(communicator: communicator) MyInterfaceSSHelper.write(to: outS, value: arrS) data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let arr2S = try MyInterfaceSSHelper.read(from: inS) try test(arr2S.count == arrS.count) try test(arr2S[0].count == arrS[0].count) try test(arr2S[1].count == arrS[1].count) try test(arr2S[2].count == arrS[2].count) } do { outS = Ice.OutputStream(communicator: communicator) let ex = MyException() let c = MyClass() c.c = c c.o = c c.s.e = MyEnum.enum2 c.seq1 = [true, false, true, false] c.seq2 = ByteSeq([1, 2, 3, 4]) c.seq3 = [1, 2, 3, 4] c.seq4 = [1, 2, 3, 4] c.seq5 = [1, 2, 3, 4] c.seq6 = [1, 2, 3, 4] c.seq7 = [1, 2, 3, 4] c.seq8 = ["string1", "string2", "string3", "string4"] c.seq9 = [MyEnum.enum3, MyEnum.enum2, MyEnum.enum1] c.seq10 = [nil, nil, nil, nil] c.d = ["hi": c] ex.c = c outS.write(ex) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) do { try inS.throwException() } catch let ex1 as MyException { try test(ex1.c!.s.e == c.s.e) try test(ex1.c!.seq1 == c.seq1) try test(ex1.c!.seq2 == c.seq2) try test(ex1.c!.seq3 == c.seq3) try test(ex1.c!.seq4 == c.seq4) try test(ex1.c!.seq5 == c.seq5) try test(ex1.c!.seq6 == c.seq6) try test(ex1.c!.seq7 == c.seq7) try test(ex1.c!.seq8 == c.seq8) try test(ex1.c!.seq9 == c.seq9) } catch is Ice.UserException { try test(false) } } do { outS = Ice.OutputStream(communicator: communicator) let dict: ByteBoolD = [4: true, 1: false] ByteBoolDHelper.write(to: outS, value: dict) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let dict2 = try ByteBoolDHelper.read(from: inS) try test(dict == dict2) } do { outS = Ice.OutputStream(communicator: communicator) let dict: ShortIntD = [1: 9, 4: 8] ShortIntDHelper.write(to: outS, value: dict) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let dict2 = try ShortIntDHelper.read(from: inS) try test(dict == dict2) } do { let dict: LongFloatD = [123_809_828: 0.5, 123_809_829: 0.6] outS = Ice.OutputStream(communicator: communicator) LongFloatDHelper.write(to: outS, value: dict) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let dict2 = try LongFloatDHelper.read(from: inS) try test(dict == dict2) } do { let dict: StringStringD = ["key1": "value1", "key2": "value2"] outS = Ice.OutputStream(communicator: communicator) StringStringDHelper.write(to: outS, value: dict) let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let dict2 = try StringStringDHelper.read(from: inS) try test(dict2 == dict) } do { var dict = StringMyClassD() var c = MyClass() c.s = SmallStruct() c.s.e = MyEnum.enum2 dict["key1"] = c c = MyClass() c.s = SmallStruct() c.s.e = MyEnum.enum3 dict["key2"] = c outS = Ice.OutputStream(communicator: communicator) StringMyClassDHelper.write(to: outS, value: dict) outS.writePendingValues() let data = outS.finished() inS = Ice.InputStream(communicator: communicator, bytes: data) let dict2: StringMyClassD = try StringMyClassDHelper.read(from: inS) try inS.readPendingValues() try test(dict2.count == dict.count) try test(dict2["key1"]!!.s.e == MyEnum.enum2) try test(dict2["key2"]!!.s.e == MyEnum.enum3) } writer.writeLine("ok") } }
gpl-2.0
9da08976b613366e1ad0949a5c3b7572
37.82343
103
0.522893
4.145577
false
true
false
false
mluisbrown/iCalendar
Tests/iCalendarTests/ParserSpec.swift
1
4388
// ParserSpec.swift // iCalendar // // Created by Michael Brown on 20/05/2017. // Copyright © 2017 iCalendar. All rights reserved. import Foundation import Result import Nimble import Quick @testable import iCalendar class ParserSpec: QuickSpec { override func spec() { describe("lines") { it("should split the input into unfolded lines") { let lines = Parser.lines(ics: "Line1 Part One\r\n Part Two\r\nLine2 Hello") expect(lines.count).to(equal(2)) expect(lines[0]).to(equal("Line1 Part One Part Two")) expect(lines[1]).to(equal("Line2 Hello")) } it("should unfold when only an LF terminates the line") { let lines = Parser.lines(ics: "Line1 Part One\n Part Two\r\nLine2 Hello") expect(lines.count).to(equal(2)) expect(lines[0]).to(equal("Line1 Part One Part Two")) expect(lines[1]).to(equal("Line2 Hello")) } it("should unfold when folded line starts with a tab") { let lines = Parser.lines(ics: "Line1 Part One\r\n\t Part Two\r\nLine2 Hello") expect(lines.count).to(equal(2)) expect(lines[0]).to(equal("Line1 Part One Part Two")) expect(lines[1]).to(equal("Line2 Hello")) } it("should not unfold lines that don't start with whitespace") { let lines = Parser.lines(ics: "Line1\r\nLine2\r\nLine3 Hello") expect(lines.count).to(equal(3)) expect(lines[0]).to(equal("Line1")) expect(lines[1]).to(equal("Line2")) expect(lines[2]).to(equal("Line3 Hello")) } } describe("unescape") { it("should unescape escaped characters") { let unescaped = Parser.unescape("Newline: \\n Comma: \\, Semicolon: \\; Backslash \\\\") expect(unescaped).to(equal("Newline: \n Comma: , Semicolon: ; Backslash \\")) } } describe("parseLineFromLine") { it("should split a line into key, params and a value") { let result = Parser.parse(line: "DTEND;VALUE=DATE:20160614") expect(result.value).toNot(beNil()) let kpv = result.value! expect(kpv.key).to(equal("DTEND")) expect(kpv.params?["VALUE"]).to(equal("DATE")) expect(kpv.value).to(equal("20160614")) } it("should parse multiple params") { let result = Parser.parse(line: "DTEND;VALUE=DATE;FOO=BAR:20160614") expect(result.value).toNot(beNil()) let kpv = result.value! expect(kpv.params?["VALUE"]).to(equal("DATE")) expect(kpv.params?["FOO"]).to(equal("BAR")) expect(kpv.key).to(equal("DTEND")) expect(kpv.value).to(equal("20160614")) } it("should handle no params") { let result = Parser.parse(line: "BEGIN:VEVENT") expect(result.value).toNot(beNil()) let kpv = result.value! expect(kpv.key).to(equal("BEGIN")) expect(kpv.value).to(equal("VEVENT")) expect(kpv.params).to(beNil()) } } describe("parse airbnb") { it("should parse an airbnb calendar correctly") { guard let ics = testResource(from: "airbnb.ics") else { fail("unable to load resource") return } let result = Parser.parse(ics: ics) expect(result.value).toNot(beNil()) let calendar = result.value! expect(calendar.events.count).to(equal(3)) } } describe("parse wimdu") { it("should parse a wimdu calendar correctly") { guard let ics = testResource(from: "wimdu.ics") else { fail("unable to load resource") return } let result = Parser.parse(ics: ics) expect(result.value).toNot(beNil()) let calendar = result.value! expect(calendar.events.count).to(equal(3)) } } } }
mit
02f39e4b4628868bb50ebf1fa90aed2d
36.177966
104
0.513107
4.146503
false
false
false
false
lilongcnc/Swift-weibo2015
ILWEIBO04/ILWEIBO04/Classes/UI/Compose/Emoticons.swift
1
8340
// // Emoticons.swift // ILWEIBO04 // // Created by 李龙 on 15/3/12. // Copyright (c) 2015年 Lauren. All rights reserved. // import Foundation /// 表情图像数组,单例,专供查询使用 class EmoticonList { /// 单例 private static let instance = EmoticonList() class var sharedEmoticonList : EmoticonList { return instance } /// 所有自定义的表情的数组,便于查询 var emoticons : [Emoticon] init() { //实例化表情数组 emoticons = [Emoticon]() //填充数据 //1.加载 分组表情中 的全部数据 let sections = EmoticonsSection.loadEmoticons() // 2. 合并数组(提示:TODO 这里可以优化,把 emoji 去掉,因为emoji没有图片) for sec in sections { //TODO ? 这个可以合并数组???? emoticons += sec.emoticons } } } /** 这个模型类,我们不用字典转模型。因为嵌套的比较深,我们用字典转模型的话,会比自己手动赋值多写。刀哥验证的,我自己没验证 这里要注意,emoji表情和浪小花表情是不一样的,一个是图片,一个是字符串 */ //表情分组类 emtioncons.plist class EmoticonsSection { //如果我们在构造函数当中给对象属性设置初始值,属性就不用 ? //分组名称 var name : String var type : String var path : String /// 表情符号的数组(每一个 section中应该包含21个表情符号,这样界面处理是最方便的) /// 然后21个表情符号中,最后一个删除(就不能使用plist中的数据) var emoticons : [Emoticon] /** 使用字典实例化对象 构造函数,能够给对象直接设置初始数值,凡事设置过的属性,都可以是必选项 在构造函数中,不需要 super,直接给属性分配空间&初始化 */ init(dict : NSDictionary) { //使用字典 name = dict["emoticon_group_name"] as! String type = dict["emoticon_group_type"] as! String path = dict["emoticon_group_path"] as! String //初始化符号数组 emoticons = [Emoticon]() } /** 下边这三个函数逐层解析 loadEmoticons() -> [EmoticonsSection] loadEmoticons(dict : NSDictionary) -> [EmoticonsSection] loadEmoticons(list : NSArray, _ dict : NSDictionary) -> [EmoticonsSection] */ /// 获取表情字符串数据数组,里边的所有的表情数据都详细加载 class func loadEmoticons() -> [EmoticonsSection]{ //1.获取路径,创建数组 let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/emoticons.plist") let path1 = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil) var array = NSArray(contentsOfFile: path)! //2.按照type,对数组进行排序,返回新的数组 array = array.sortedArrayUsingComparator({ (dict1, dict2) -> NSComparisonResult in //获取比较的数据 let type1 = dict1["emoticon_group_type"] as! String let type2 = dict2["emoticon_group_type"] as! String //返回比较的结果 return type1.compare(type2) }) //3.遍历array模型数组,把array指代的具体的模型数据拆开赋值 var result = [EmoticonsSection]() for dict in array as! [NSDictionary] { //MARK: 进入 group_path 对应的目录进一步加载数据 result += loadEmoticons(dict) } return result } //从info.plist 中的字典中获取 表情符号数组 class func loadEmoticons(dict : NSDictionary) -> [EmoticonsSection]{ // 1. 根据 dict 中的 group_path 加载不同目录中的 info.plist let group_path = dict["emoticon_group_path"] as! String let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/\(group_path)/info.plist") // 2. 加载info.plist var infoDict = NSDictionary(contentsOfFile: path)! // 3. 从 infoDict 的 emoticon_group_emoticons 中提取表情符号数组 let list = infoDict["emoticon_group_emoticons"] as! NSArray // 4. 遍历 list 数组,加载具体的表情符号 var result = loadEmoticons(list, dict) return result } /// 从 info.plist 的表情数组中,加载真正的具体的表情数据 // 从 emoticon_group_emoticons 返回表情数组的数组,每一个数组 都 包含 21 个表情(最后一个是空的) class func loadEmoticons(list : NSArray, _ dict : NSDictionary) -> [EmoticonsSection]{ // 1.生成EmoticonsSection 对象数组,每20个就生成一个EmoticonsSection 对象 let emoticonCount = 20 // 2. 计算总共需要多个 [EmoticonsSection] let objCount = (list.count - 1) / emoticonCount + 1 println("对象个数\(objCount)") //记录存储结果的中间数组 var result = [EmoticonsSection]() //3. 循环遍历所有的对象,利用双重for循环,达到20个就存到[EmoticonsSection]中的一个数组中 for i in 0..<objCount { //3.1 MARK: 创建表情数组对象!!!!!!!!!!!!!!!!! var emoticon = EmoticonsSection(dict: dict) // 3.2 填充对象内部的表情符号数据 // 遍历数组,把80个数据按照 0~19, 20~39, 40~69....填充到第 i 个 数组表情对象中 for count in 0..<20 { //20个 // 1.数组中下标序号 let j = count + i * emoticonCount // 2. 向数组中添加元素,如果内,那么 // MARK: 特别注意,最后不够20个一组的,不够的部分也要赋值为nil var tempDict : NSDictionary? = nil if j < list.count { //在list范围内就 实例化表情符号对象 tempDict = list[j] as? NSDictionary } //初始化 一个 表情符号元素 let em = Emoticon(dict: tempDict, path: emoticon.path) //添加到表情数组对象中的emoticons数组属性中 emoticon.emoticons.append(em) } //MARK: 这里添加第21个删除按钮 let em = Emoticon(dict: nil, path: nil) //添加标示符,判定该位置是删除按钮 em.isDeleteButton = true //添加到表情数组对象中的emoticons数组属性中 emoticon.emoticons.append(em) //把完整数组加入到结果集 result.append(emoticon) } return result } } //表情符号类 class Emoticon { /// emoji 的16进制字符串 var code: String? /// emoji 字符串 var emoji: String? /// 类型 var type: String? /// 表情符号的文本 - 发送给服务器的文本 var chs: String? /// 表情符号的图片 - 本地做图文混排使用的图片 var png: String? /// 图像的完整路径 var imagePath: String? /// 删除按钮的属性 var isDeleteButton = false //构造函数初始时候给属性赋值 init(dict: NSDictionary?, path : String?) { code = dict?["code"] as? String type = dict?["type"] as? String chs = dict?["chs"] as? String png = dict?["png"] as? String if path != nil && png != nil { imagePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/\(path!)/\(png!)") } //计算emoji //把16进制的emoji字符串 转化为字符串可以显示,固定写法 if code != nil { let scnner = NSScanner(string: code!) var value : UInt32 = 0 //传递指针,用var,不要用let scnner.scanHexInt(&value) emoji = "\(Character(UnicodeScalar(value)))" } } }
mit
2403d27cc8f0d4e1a1268e4a75f5d26f
27.705357
120
0.56283
3.789039
false
false
false
false
kagurazakayashi/choosephoto
choosephoto/ViewController.swift
1
17824
// // ViewController.swift // choosephoto // // Created by 神楽坂雅詩 on 2017/7/21. // Copyright © 2017年 KagurazakaYashi. All rights reserved. // import UIKit import AVFoundation import QuartzCore public let 全局主题颜色:[CGColor] = [UIColor(red: 0, green: 158/255, blue: 212/255, alpha: 1).cgColor,UIColor(red: 39/255, green: 224/255, blue: 36/255, alpha: 1).cgColor,UIColor(red: 241/255, green: 158/255, blue: 194/255, alpha: 1).cgColor] public let 全局故事板:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, UIAlertViewDelegate, UITabBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var 图像列表框: UICollectionView! @IBOutlet weak var 实时预览框: UIImageView! @IBOutlet weak var 底部工具栏: UITabBar! var 摄像头权限: AVAuthorizationStatus! var 视频捕获预览: AVCaptureVideoPreviewLayer! var 视频捕获会话: AVCaptureSession! var 视频捕获输入: AVCaptureDeviceInput! var 视频捕获输出: AVCaptureVideoDataOutput! var 视频捕获设备:AVCaptureDevice? = nil var 视频捕获启动:Bool = false var 正在复位底部工具栏:Bool = false var 列表数据:[UIImage] = [UIImage]() var 正在使用后摄像头 = false var 缩略图布局 = UICollectionViewFlowLayout() var 可以暂存的图片数量:Int = 100 let 设置:Settings = Settings() override func viewDidAppear(_ animated: Bool) { if 检查是否有摄像头权限() == false { print("没有权限访问摄像头") } } override func viewDidLoad() { super.viewDidLoad() 设置.载入设置() 初始化外观() // NotificationCenter.default.addObserver(self, selector: Selector(收到通知()), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) 底部工具栏.delegate = self if 设置.默认摄像头 == 1 { 正在使用后摄像头 = true } 视频捕获会话 = AVCaptureSession() 视频捕获输出 = AVCaptureVideoDataOutput() if 前后摄像头切换() == false { print("摄像头获取失败") return } if (初始化照相机() == false) { print("照相机初始化失败") return } 视频捕获会话.startRunning() } func 收到通知() { print("收到通知") } func 初始化外观() { 实时预览框.layer.borderWidth = 1 实时预览框.layer.borderColor = 全局主题颜色[2] // 图像列表框.collectionViewLayout = 缩略图布局 // 缩略图布局.itemSize = CGSize(width: 图像列表框.frame.width / 设置.每行显示, height: 图像列表框.frame.height / 设置.每行显示) // 缩略图布局.minimumLineSpacing = 10.0 //上下间隔 // 缩略图布局.minimumInteritemSpacing = 1.0 //左右间隔 } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { // if (正在复位底部工具栏 == true) { // 正在复位底部工具栏 = false // return // } if tabBar.tag == 1000 { switch item.tag { case 1001: //清空 列表数据.removeAll() 图像列表框.reloadData() break case 1002: //拍摄 缓存照片() break case 1003: //设置 打开系统设置页面() break case 1004: //补光 补光() break case 1005: //前后摄像头切换 if (前后摄像头切换() == false) { print("切换失败或设备没有前摄像头") } break default: break } } // 正在复位底部工具栏 = true } func 缓存照片() { if 列表数据.count > 可以暂存的图片数量 { print("一次只能临时保存\(可以暂存的图片数量)张。") } else if (实时预览框.image != nil) { 列表数据.append(实时预览框.image!) 设置内容块(大小: nil) 图像列表框.reloadData() if (设置.快门音效) { AudioServicesPlaySystemSound(1108) } } } func 补光() { if !正在使用后摄像头 { print("前置摄像头没有闪光灯") return } if 视频捕获设备 == nil { print("没有找到闪光灯。") return } if 视频捕获设备!.torchMode == AVCaptureDevice.TorchMode.off{ do { try 视频捕获设备!.lockForConfiguration() } catch { return } 视频捕获设备!.torchMode = .on 视频捕获设备!.unlockForConfiguration() } else { do { try 视频捕获设备!.lockForConfiguration() } catch { return } 视频捕获设备!.torchMode = .off 视频捕获设备!.unlockForConfiguration() } } func 前后摄像头切换() -> Bool { // 断开摄像头连接() if 正在使用后摄像头 { 视频捕获设备 = 获得摄像头(摄像头位置: AVCaptureDevice.Position.front) } else { 视频捕获设备 = 获得摄像头(摄像头位置: AVCaptureDevice.Position.back) } 正在使用后摄像头 = !正在使用后摄像头 if (视频捕获设备 == nil) { print("没能启动视频捕获设备") return false } 视频捕获会话.beginConfiguration() if 视频捕获启动 { 视频捕获会话.removeInput(视频捕获输入) } do{ try 视频捕获输入 = AVCaptureDeviceInput(device: 视频捕获设备!) } catch let error as NSError { print("视频捕获失败: ",error) return false } if(视频捕获会话.canAddInput(视频捕获输入)){ 视频捕获会话.addInput(视频捕获输入) } else { print("视频捕获输入设置失败!") return false } 视频捕获会话.commitConfiguration() return true } func 断开摄像头连接() { if 视频捕获启动 { 视频捕获会话.beginConfiguration() 视频捕获会话.removeInput(视频捕获输入) 视频捕获会话.removeOutput(视频捕获输出) 视频捕获会话.commitConfiguration() } 视频捕获会话 = nil 视频捕获输入 = nil 视频捕获输出 = nil 视频捕获设备 = nil 实时预览框.image = nil 视频捕获启动 = false } func 获得摄像头(摄像头位置:AVCaptureDevice.Position) -> AVCaptureDevice? { let 视频设备会话:AVCaptureDevice.DiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: 摄像头位置) let 视频设备列表 = 视频设备会话.devices for 视频设备:AVCaptureDevice in 视频设备列表 { if 视频设备.position == 摄像头位置 { return 视频设备 } } return nil } func 设置内容块(大小:CGSize?) { let 图像:UIImage? = 实时预览框.image if 图像 == nil { return } var 列宽度:CGFloat var 列高度:CGFloat if 大小 != nil { 列宽度 = (大小?.width)! / 设置.每行显示 if UIDevice.current.orientation.isPortrait == true { 列高度 = 图像!.size.width / 图像!.size.height * 列宽度 } else { 列高度 = 图像!.size.height / 图像!.size.width * 列宽度 } } else { 列宽度 = self.view.frame.size.width / 设置.每行显示 列高度 = 图像!.size.height / 图像!.size.width * 列宽度 } let 内容块:UICollectionViewFlowLayout = UICollectionViewFlowLayout() 内容块.itemSize = CGSize(width: 列宽度, height: 列高度) 内容块.minimumInteritemSpacing = 0; //水平间距 内容块.minimumLineSpacing = 0; //垂直间距 图像列表框.collectionViewLayout = 内容块 图像列表框.reloadData() } //<代理> func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 列表数据.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let 列表项:ImgCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imgcell", for: indexPath) as! ImgCollectionViewCell let 图片:UIImage = 列表数据[indexPath.row] // let 列宽度:CGFloat = self.view.frame.size.width / 设置.每行显示 // let 列高度:CGFloat = 图片.size.height / 图片.size.width * 列宽度 // 列表项.frame = CGRect(x: 列表项.frame.origin.x, y: 列表项.frame.origin.y, width: 列宽度, height: 列高度)//CGSize(width: 列宽度, height: 列高度) 列表项.设置缩略图(图片: 图片) return 列表项 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let 图片浏览器:ImgViewController = 全局故事板.instantiateViewController(withIdentifier: "ImgViewController") as! ImgViewController self.present(图片浏览器, animated: true) { //print("打开图片浏览器") } if (indexPath.row < 列表数据.count) { 图片浏览器.装入图片(图片: 列表数据[indexPath.row]) } else { print("无效图片请求",indexPath.row,列表数据.count) } } //</代理>r func 打开系统设置页面() { let 系统设置页面地址:URL = URL(string: UIApplicationOpenSettingsURLString)! if UIApplication.shared.canOpenURL(系统设置页面地址) { if #available(iOS 10, *) { UIApplication.shared.open(系统设置页面地址, options: [:], completionHandler: { (success) in }) } else { UIApplication.shared.openURL(系统设置页面地址) } } } func 检查是否有摄像头权限() -> Bool { 摄像头权限 = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) if 摄像头权限 == AVAuthorizationStatus.notDetermined { AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in if(granted){ self.摄像头权限 = AVAuthorizationStatus.authorized } else { self.摄像头权限 = AVAuthorizationStatus.restricted } }) } if 摄像头权限 == AVAuthorizationStatus.authorized { //已获得相关权限 return true } if ( 摄像头权限 == AVAuthorizationStatus.denied || 摄像头权限 == AVAuthorizationStatus.restricted ) { let 摄像头权限申请提示框:UIAlertController = UIAlertController(title: "需要摄像头权限", message: "你需要在系统设置中允许我访问摄像头,要现在跳转到设置吗?", preferredStyle: UIAlertControllerStyle.alert) 摄像头权限申请提示框.addAction(UIAlertAction(title: "进入设置", style: UIAlertActionStyle.default, handler: { (此摄像头权限申请提示框:UIAlertAction) in self.打开系统设置页面() })) 摄像头权限申请提示框.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (此摄像头权限申请提示框:UIAlertAction) in //N })) self.present(摄像头权限申请提示框, animated: true, completion: nil) } return false } func 初始化照相机() -> Bool { 视频捕获会话.beginConfiguration() 视频捕获会话.sessionPreset = 设置.拍摄品质 let 视频像素模式K = kCVPixelBufferPixelFormatTypeKey as String let 视频像素模式V = 设置.色彩格式 // let 视频像素宽度K = kCVPixelBufferWidthKey as String // let 视频像素宽度V = NSNumber(value: 1280) // let 视频像素高度K = kCVPixelBufferHeightKey as String // let 视频像素高度V = NSNumber(value: 720) 视频捕获输出.videoSettings = [视频像素模式K:视频像素模式V] //, 视频像素宽度K:视频像素宽度V, 视频像素高度K:视频像素高度V] if(视频捕获会话.canAddOutput(视频捕获输出)){ 视频捕获会话.addOutput(视频捕获输出) } else { print("视频捕获输出设置失败!") return false } let 视频捕获线程 = DispatchQueue(label: "cameraQueue") 视频捕获输出.setSampleBufferDelegate(self, queue: 视频捕获线程) // 视频捕获预览 = AVCaptureVideoPreviewLayer(session: 视频捕获会话) // 视频捕获预览.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) // 视频捕获预览.videoGravity = AVLayerVideoGravity.resizeAspectFill // self.view.layer.addSublayer(视频捕获预览) 视频捕获会话.commitConfiguration() 视频捕获启动 = true return true } func 从数据流创建图片(缓冲区:CMSampleBuffer!) -> CGImage? { let 图片缓冲区:CVImageBuffer? = CMSampleBufferGetImageBuffer(缓冲区) if (图片缓冲区 == nil) { print("缓冲区中没有数据!") return nil } CVPixelBufferLockBaseAddress(图片缓冲区!, CVPixelBufferLockFlags(rawValue: 0)) let 逐行大小:size_t = CVPixelBufferGetBytesPerRow(图片缓冲区!) let 宽度:size_t = CVPixelBufferGetWidth(图片缓冲区!) let 高度:size_t = CVPixelBufferGetHeight(图片缓冲区!) let 安全点:UnsafeMutableRawPointer = CVPixelBufferGetBaseAddress(图片缓冲区!)! let 位图信息:UInt32 = CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue let 色彩空间: CGColorSpace = CGColorSpaceCreateDeviceRGB() let 画布:CGContext = CGContext(data: 安全点, width: 宽度, height: 高度, bitsPerComponent: 8, bytesPerRow: 逐行大小, space: 色彩空间, bitmapInfo: 位图信息)! let 取出图片: CGImage = 画布.makeImage()! CVPixelBufferUnlockBaseAddress(图片缓冲区!, CVPixelBufferLockFlags(rawValue: 0)) return 取出图片 } func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { if (视频捕获启动 == false) { return } let 当前图片:CGImage? = 从数据流创建图片(缓冲区: sampleBuffer) DispatchQueue.main.async() { () -> Void in self.输出预览图像(当前图片: 当前图片) } } func 输出预览图像(当前图片:CGImage?) { var 图片旋转方向:UIImageOrientation = UIImageOrientation.right switch UIDevice.current.orientation { // case UIDeviceOrientation.portrait: // 图片旋转方向 = .right // break case UIDeviceOrientation.portraitUpsideDown: 图片旋转方向 = .down break case UIDeviceOrientation.landscapeLeft: 图片旋转方向 = .up break case UIDeviceOrientation.landscapeRight: 图片旋转方向 = .down break // case UIDeviceOrientation.faceUp: // 图片旋转方向 = .right // break default: break } if 当前图片 == nil { self.实时预览框.image = nil } else { self.实时预览框.image = UIImage(cgImage: 当前图片!, scale: 1, orientation: 图片旋转方向) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { 设置内容块(大小: size) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { 视频捕获会话.stopRunning() super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() 可以暂存的图片数量 = 列表数据.count print("发生内存不足。一次将只能临时保存\(可以暂存的图片数量)张。") } }
mit
91d62c873abcd62bad123635246cf90f
34.477723
236
0.573641
4.129358
false
false
false
false
tichise/MaterialDesignSymbol
Sources/MaterialDesignSymbol/MaterialDesignIcon3.swift
1
20717
// // MaterialDesignIcon3 // // Created by tichise on 2015/5/7 15/05/07. // Copyright (c) 2015 tichise. All rights reserved. // import UIKit /** * マテリアルデザインアイコンのコードを返すクラス */ extension MaterialDesignIcon { public static let borderColor18px = "\u{e91e}" public static let borderColor24px = "\u{e91f}" public static let borderColor48px = "\u{e920}" public static let borderHorizontal18px = "\u{e921}" public static let borderHorizontal24px = "\u{e922}" public static let borderHorizontal48px = "\u{e923}" public static let borderInner18px = "\u{e924}" public static let borderInner24px = "\u{e925}" public static let borderInner48px = "\u{e926}" public static let borderLeft18px = "\u{e927}" public static let borderLeft24px = "\u{e928}" public static let borderLeft48px = "\u{e929}" public static let borderOuter18px = "\u{e92a}" public static let borderOuter24px = "\u{e92b}" public static let borderOuter48px = "\u{e92c}" public static let borderRight18px = "\u{e92d}" public static let borderRight24px = "\u{e92e}" public static let borderRight48px = "\u{e92f}" public static let borderStyle18px = "\u{e930}" public static let borderStyle24px = "\u{e931}" public static let borderStyle48px = "\u{e932}" public static let borderTop18px = "\u{e933}" public static let borderTop24px = "\u{e934}" public static let borderTop48px = "\u{e935}" public static let borderVertical18px = "\u{e936}" public static let borderVertical24px = "\u{e937}" public static let borderVertical48px = "\u{e938}" public static let formatAlignCenter18px = "\u{e939}" public static let formatAlignCenter24px = "\u{e93a}" public static let formatAlignCenter48px = "\u{e93b}" public static let formatAlignJustify18px = "\u{e93c}" public static let formatAlignJustify24px = "\u{e93d}" public static let formatAlignJustify48px = "\u{e93e}" public static let formatAlignLeft18px = "\u{e93f}" public static let formatAlignLeft24px = "\u{e940}" public static let formatAlignLeft48px = "\u{e941}" public static let formatAlignRight18px = "\u{e942}" public static let formatAlignRight24px = "\u{e943}" public static let formatAlignRight48px = "\u{e944}" public static let formatBold18px = "\u{e945}" public static let formatBold24px = "\u{e946}" public static let formatBold48px = "\u{e947}" public static let formatClear18px = "\u{e948}" public static let formatClear24px = "\u{e949}" public static let formatClear48px = "\u{e94a}" public static let formatColorFill18px = "\u{e94b}" public static let formatColorFill24px = "\u{e94c}" public static let formatColorFill48px = "\u{e94d}" public static let formatColorReset18px = "\u{e94e}" public static let formatColorReset24px = "\u{e94f}" public static let formatColorReset48px = "\u{e950}" public static let formatColorText18px = "\u{e951}" public static let formatColorText24px = "\u{e952}" public static let formatColorText48px = "\u{e953}" public static let formatIndentDecrease18px = "\u{e954}" public static let formatIndentDecrease24px = "\u{e955}" public static let formatIndentDecrease48px = "\u{e956}" public static let formatIndentIncrease18px = "\u{e957}" public static let formatIndentIncrease24px = "\u{e958}" public static let formatIndentIncrease48px = "\u{e959}" public static let formatItalic18px = "\u{e95a}" public static let formatItalic24px = "\u{e95b}" public static let formatItalic48px = "\u{e95c}" public static let formatLineSpacing18px = "\u{e95d}" public static let formatLineSpacing24px = "\u{e95e}" public static let formatLineSpacing48px = "\u{e95f}" public static let formatListBulleted18px = "\u{e960}" public static let formatListBulleted24px = "\u{e961}" public static let formatListBulleted48px = "\u{e962}" public static let formatListNumbered18px = "\u{e963}" public static let formatListNumbered24px = "\u{e964}" public static let formatListNumbered48px = "\u{e965}" public static let formatPaint18px = "\u{e966}" public static let formatPaint24px = "\u{e967}" public static let formatPaint48px = "\u{e968}" public static let formatQuote18px = "\u{e969}" public static let formatQuote24px = "\u{e96a}" public static let formatQuote48px = "\u{e96b}" public static let formatSize18px = "\u{e96c}" public static let formatSize24px = "\u{e96d}" public static let formatSize48px = "\u{e96e}" public static let formatStrikethrough18px = "\u{e96f}" public static let formatStrikethrough24px = "\u{e970}" public static let formatStrikethrough48px = "\u{e971}" public static let formatTextdirectionLToR18px = "\u{e972}" public static let formatTextdirectionLToR24px = "\u{e973}" public static let formatTextdirectionLToR48px = "\u{e974}" public static let formatTextdirectionRToL18px = "\u{e975}" public static let formatTextdirectionRToL24px = "\u{e976}" public static let formatTextdirectionRToL48px = "\u{e977}" public static let formatUnderline18px = "\u{e978}" public static let formatUnderline24px = "\u{e979}" public static let formatUnderline48px = "\u{e97a}" public static let functions18px = "\u{e97b}" public static let functions24px = "\u{e97c}" public static let functions48px = "\u{e97d}" public static let insertChart18px = "\u{e97e}" public static let insertChart24px = "\u{e97f}" public static let insertChart48px = "\u{e980}" public static let insertComment18px = "\u{e981}" public static let insertComment24px = "\u{e982}" public static let insertComment48px = "\u{e983}" public static let insertDriveFile18px = "\u{e984}" public static let insertDriveFile24px = "\u{e985}" public static let insertDriveFile48px = "\u{e986}" public static let insertEmoticon18px = "\u{e987}" public static let insertEmoticon24px = "\u{e988}" public static let insertEmoticon48px = "\u{e989}" public static let insertInvitation18px = "\u{e98a}" public static let insertInvitation24px = "\u{e98b}" public static let insertInvitation48px = "\u{e98c}" public static let insertLink18px = "\u{e98d}" public static let insertLink24px = "\u{e98e}" public static let insertLink48px = "\u{e98f}" public static let insertPhoto18px = "\u{e990}" public static let insertPhoto24px = "\u{e991}" public static let insertPhoto48px = "\u{e992}" public static let mergeType18px = "\u{e993}" public static let mergeType24px = "\u{e994}" public static let mergeType48px = "\u{e995}" public static let modeComment18px = "\u{e996}" public static let modeComment24px = "\u{e997}" public static let modeComment48px = "\u{e998}" public static let modeEdit18px = "\u{e999}" public static let modeEdit24px = "\u{e99a}" public static let modeEdit48px = "\u{e99b}" public static let publish18px = "\u{e99c}" public static let publish24px = "\u{e99d}" public static let publish48px = "\u{e99e}" public static let verticalAlignBottom18px = "\u{e99f}" public static let verticalAlignBottom24px = "\u{e9a0}" public static let verticalAlignBottom48px = "\u{e9a1}" public static let verticalAlignCenter18px = "\u{e9a2}" public static let verticalAlignCenter24px = "\u{e9a3}" public static let verticalAlignCenter48px = "\u{e9a4}" public static let verticalAlignTop18px = "\u{e9a5}" public static let verticalAlignTop24px = "\u{e9a6}" public static let verticalAlignTop48px = "\u{e9a7}" public static let wrapText18px = "\u{e9a8}" public static let wrapText24px = "\u{e9a9}" public static let wrapText48px = "\u{e9aa}" public static let attachment18px = "\u{e9ab}" public static let attachment24px = "\u{e9ac}" public static let attachment48px = "\u{e9ad}" public static let cloud24px = "\u{e9ae}" public static let cloud48px = "\u{e9af}" public static let cloudCircle18px = "\u{e9b0}" public static let cloudCircle24px = "\u{e9b1}" public static let cloudCircle48px = "\u{e9b2}" public static let cloudDone24px = "\u{e9b3}" public static let cloudDone48px = "\u{e9b4}" public static let cloudDownload24px = "\u{e9b5}" public static let cloudDownload48px = "\u{e9b6}" public static let cloudOff24px = "\u{e9b7}" public static let cloudOff48px = "\u{e9b8}" public static let cloudQueue24px = "\u{e9b9}" public static let cloudQueue48px = "\u{e9ba}" public static let cloudUpload24px = "\u{e9bb}" public static let cloudUpload48px = "\u{e9bc}" public static let fileDownload24px = "\u{e9bd}" public static let fileDownload48px = "\u{e9be}" public static let fileUpload24px = "\u{e9bf}" public static let fileUpload48px = "\u{e9c0}" public static let folder18px = "\u{e9c1}" public static let folder24px = "\u{e9c2}" public static let folder48px = "\u{e9c3}" public static let folderOpen18px = "\u{e9c4}" public static let folderOpen24px = "\u{e9c5}" public static let folderOpen48px = "\u{e9c6}" public static let folderShared18px = "\u{e9c7}" public static let folderShared24px = "\u{e9c8}" public static let folderShared48px = "\u{e9c9}" public static let cast24px = "\u{e9ca}" public static let cast48px = "\u{e9cb}" public static let castConnected24px = "\u{e9cc}" public static let castConnected48px = "\u{e9cd}" public static let computer24px = "\u{e9ce}" public static let computer48px = "\u{e9cf}" public static let desktopMac24px = "\u{e9d0}" public static let desktopMac48px = "\u{e9d1}" public static let desktopWindows24px = "\u{e9d2}" public static let desktopWindows48px = "\u{e9d3}" public static let dock24px = "\u{e9d4}" public static let dock48px = "\u{e9d5}" public static let gamepad24px = "\u{e9d6}" public static let gamepad48px = "\u{e9d7}" public static let headset24px = "\u{e9d8}" public static let headset48px = "\u{e9d9}" public static let headsetMic24px = "\u{e9da}" public static let headsetMic48px = "\u{e9db}" public static let keyboard24px = "\u{e9dc}" public static let keyboard48px = "\u{e9dd}" public static let keyboardAlt24px = "\u{e9de}" public static let keyboardAlt48px = "\u{e9df}" public static let keyboardArrowDown24px = "\u{e9e0}" public static let keyboardArrowDown48px = "\u{e9e1}" public static let keyboardArrowLeft24px = "\u{e9e2}" public static let keyboardArrowLeft48px = "\u{e9e3}" public static let keyboardArrowRight24px = "\u{e9e4}" public static let keyboardArrowRight48px = "\u{e9e5}" public static let keyboardArrowUp24px = "\u{e9e6}" public static let keyboardArrowUp48px = "\u{e9e7}" public static let keyboardBackspace24px = "\u{e9e8}" public static let keyboardBackspace48px = "\u{e9e9}" public static let keyboardCapslock24px = "\u{e9ea}" public static let keyboardCapslock48px = "\u{e9eb}" public static let keyboardControl24px = "\u{e9ec}" public static let keyboardControl48px = "\u{e9ed}" public static let keyboardHide24px = "\u{e9ee}" public static let keyboardHide48px = "\u{e9ef}" public static let keyboardReturn24px = "\u{e9f0}" public static let keyboardReturn48px = "\u{e9f1}" public static let keyboardTab24px = "\u{e9f2}" public static let keyboardTab48px = "\u{e9f3}" public static let keyboardVoice24px = "\u{e9f4}" public static let keyboardVoice48px = "\u{e9f5}" public static let laptop24px = "\u{e9f6}" public static let laptop48px = "\u{e9f7}" public static let laptopChromebook24px = "\u{e9f8}" public static let laptopChromebook48px = "\u{e9f9}" public static let laptopMac24px = "\u{e9fa}" public static let laptopMac48px = "\u{e9fb}" public static let laptopWindows24px = "\u{e9fc}" public static let laptopWindows48px = "\u{e9fd}" public static let memory24px = "\u{e9fe}" public static let memory48px = "\u{e9ff}" public static let mouse24px = "\u{ea00}" public static let mouse48px = "\u{ea01}" public static let phoneAndroid24px = "\u{ea02}" public static let phoneAndroid48px = "\u{ea03}" public static let phoneIphone24px = "\u{ea04}" public static let phoneIphone48px = "\u{ea05}" public static let phonelink24px = "\u{ea06}" public static let phonelink48px = "\u{ea07}" public static let phonelinkOff24px = "\u{ea08}" public static let phonelinkOff48px = "\u{ea09}" public static let security24px = "\u{ea0a}" public static let security48px = "\u{ea0b}" public static let simCard24px = "\u{ea0c}" public static let simCard48px = "\u{ea0d}" public static let smartphone24px = "\u{ea0e}" public static let smartphone48px = "\u{ea0f}" public static let speaker24px = "\u{ea10}" public static let speaker48px = "\u{ea11}" public static let tablet24px = "\u{ea12}" public static let tablet48px = "\u{ea13}" public static let tabletAndroid24px = "\u{ea14}" public static let tabletAndroid48px = "\u{ea15}" public static let tabletMac24px = "\u{ea16}" public static let tabletMac48px = "\u{ea17}" public static let tv24px = "\u{ea18}" public static let tv48px = "\u{ea19}" public static let watch24px = "\u{ea1a}" public static let watch48px = "\u{ea1b}" public static let addToPhotos24px = "\u{ea1c}" public static let addToPhotos48px = "\u{ea1d}" public static let adjust24px = "\u{ea1e}" public static let adjust48px = "\u{ea1f}" public static let assistantPhoto24px = "\u{ea20}" public static let assistantPhoto48px = "\u{ea21}" public static let audiotrack24px = "\u{ea22}" public static let audiotrack48px = "\u{ea23}" public static let blurCircular24px = "\u{ea24}" public static let blurCircular48px = "\u{ea25}" public static let blurLinear24px = "\u{ea26}" public static let blurLinear48px = "\u{ea27}" public static let blurOff24px = "\u{ea28}" public static let blurOff48px = "\u{ea29}" public static let blurOn24px = "\u{ea2a}" public static let blurOn48px = "\u{ea2b}" public static let brightness124px = "\u{ea2c}" public static let brightness148px = "\u{ea2d}" public static let brightness224px = "\u{ea2e}" public static let brightness248px = "\u{ea2f}" public static let brightness324px = "\u{ea30}" public static let brightness348px = "\u{ea31}" public static let brightness424px = "\u{ea32}" public static let brightness448px = "\u{ea33}" public static let brightness524px = "\u{ea34}" public static let brightness548px = "\u{ea35}" public static let brightness624px = "\u{ea36}" public static let brightness648px = "\u{ea37}" public static let brightness724px = "\u{ea38}" public static let brightness748px = "\u{ea39}" public static let brush24px = "\u{ea3a}" public static let brush48px = "\u{ea3b}" public static let camera24px = "\u{ea3c}" public static let camera48px = "\u{ea3d}" public static let cameraAlt24px = "\u{ea3e}" public static let cameraAlt48px = "\u{ea3f}" public static let cameraFront24px = "\u{ea40}" public static let cameraFront48px = "\u{ea41}" public static let cameraRear24px = "\u{ea42}" public static let cameraRear48px = "\u{ea43}" public static let cameraRoll24px = "\u{ea44}" public static let cameraRoll48px = "\u{ea45}" public static let centerFocusStrong24px = "\u{ea46}" public static let centerFocusStrong48px = "\u{ea47}" public static let centerFocusWeak24px = "\u{ea48}" public static let centerFocusWeak48px = "\u{ea49}" public static let collections24px = "\u{ea4a}" public static let collections48px = "\u{ea4b}" public static let colorLens24px = "\u{ea4c}" public static let colorLens48px = "\u{ea4d}" public static let colorize24px = "\u{ea4e}" public static let colorize48px = "\u{ea4f}" public static let compare24px = "\u{ea50}" public static let compare48px = "\u{ea51}" public static let controlPoint24px = "\u{ea52}" public static let controlPoint48px = "\u{ea53}" public static let controlPointDuplicate24px = "\u{ea54}" public static let controlPointDuplicate48px = "\u{ea55}" public static let crop3224px = "\u{ea56}" public static let crop3248px = "\u{ea57}" public static let crop5424px = "\u{ea58}" public static let crop5448px = "\u{ea59}" public static let crop7524px = "\u{ea5a}" public static let crop7548px = "\u{ea5b}" public static let crop16924px = "\u{ea5c}" public static let crop16948px = "\u{ea5d}" public static let crop24px = "\u{ea5e}" public static let crop48px = "\u{ea5f}" public static let cropDin24px = "\u{ea60}" public static let cropDin48px = "\u{ea61}" public static let cropFree24px = "\u{ea62}" public static let cropFree48px = "\u{ea63}" public static let cropLandscape24px = "\u{ea64}" public static let cropLandscape48px = "\u{ea65}" public static let cropOriginal24px = "\u{ea66}" public static let cropOriginal48px = "\u{ea67}" public static let cropPortrait24px = "\u{ea68}" public static let cropPortrait48px = "\u{ea69}" public static let cropSquare24px = "\u{ea6a}" public static let cropSquare48px = "\u{ea6b}" public static let dehaze24px = "\u{ea6c}" public static let dehaze48px = "\u{ea6d}" public static let details24px = "\u{ea6e}" public static let details48px = "\u{ea6f}" public static let edit24px = "\u{ea70}" public static let edit48px = "\u{ea71}" public static let exposure24px = "\u{ea72}" public static let exposure48px = "\u{ea73}" public static let exposureMinus124px = "\u{ea74}" public static let exposureMinus148px = "\u{ea75}" public static let exposureMinus224px = "\u{ea76}" public static let exposureMinus248px = "\u{ea77}" public static let exposurePlus124px = "\u{ea78}" public static let exposurePlus148px = "\u{ea79}" public static let exposurePlus224px = "\u{ea7a}" public static let exposurePlus248px = "\u{ea7b}" public static let exposureZero24px = "\u{ea7c}" public static let exposureZero48px = "\u{ea7d}" public static let filter124px = "\u{ea7e}" public static let filter148px = "\u{ea7f}" public static let filter224px = "\u{ea80}" public static let filter248px = "\u{ea81}" public static let filter324px = "\u{ea82}" public static let filter348px = "\u{ea83}" public static let filter424px = "\u{ea84}" public static let filter448px = "\u{ea85}" public static let filter524px = "\u{ea86}" public static let filter548px = "\u{ea87}" public static let filter624px = "\u{ea88}" public static let filter648px = "\u{ea89}" public static let filter724px = "\u{ea8a}" public static let filter748px = "\u{ea8b}" public static let filter824px = "\u{ea8c}" public static let filter848px = "\u{ea8d}" public static let filter924px = "\u{ea8e}" public static let filter948px = "\u{ea8f}" public static let filter9Plus24px = "\u{ea90}" public static let filter9Plus48px = "\u{ea91}" public static let filter24px = "\u{ea92}" public static let filter48px = "\u{ea93}" public static let filterBAndW24px = "\u{ea94}" public static let filterBAndW48px = "\u{ea95}" public static let filterCenterFocus24px = "\u{ea96}" public static let filterCenterFocus48px = "\u{ea97}" public static let filterDrama24px = "\u{ea98}" public static let filterDrama48px = "\u{ea99}" public static let filterFrames24px = "\u{ea9a}" public static let filterFrames48px = "\u{ea9b}" public static let filterHdr24px = "\u{ea9c}" public static let filterHdr48px = "\u{ea9d}" public static let filterNone24px = "\u{ea9e}" public static let filterNone48px = "\u{ea9f}" public static let filterTiltShift24px = "\u{eaa0}" public static let filterTiltShift48px = "\u{eaa1}" public static let filterVintage24px = "\u{eaa2}" public static let filterVintage48px = "\u{eaa3}" public static let flare24px = "\u{eaa4}" public static let flare48px = "\u{eaa5}" public static let flashAuto24px = "\u{eaa6}" public static let flashAuto48px = "\u{eaa7}" public static let flashOff24px = "\u{eaa8}" public static let flashOff48px = "\u{eaa9}" public static let flashOn24px = "\u{eaaa}" public static let flashOn48px = "\u{eaab}" public static let flip24px = "\u{eaac}" }
mit
47ea446bc54e0ed8c459d30e939f187f
49.050847
62
0.687969
3.27021
false
false
false
false
mogstad/Delta
tests/delta_spec.swift
1
12501
import Quick import Nimble @testable import Delta struct Section: DeltaSection, Equatable { let identifier: Int let items: [Model] var deltaIdentifier: Int { return self.identifier } init(identifier: Int, items: [Model]) { self.identifier = identifier self.items = items } } func ==(lhs: Section, rhs: Section) -> Bool { return lhs.identifier == rhs.identifier && lhs.items == rhs.items } class SectionedDeltaProcessorSpec: QuickSpec { override func spec() { describe("SectionedDeltaProcessor") { describe("#generate") { var records: [CollectionRecord]! describe("adding section") { beforeEach { let first = Section(identifier: 1, items: [ Model(identifier: 1) ]) let second = Section(identifier: 2, items: [ Model(identifier: 2) ]) records = generateRecordsForSections(from: [first], to: [first, second]) } it("works") { expect(records.count).to(equal(1)) let record = CollectionRecord.addSection(section: 1) expect(records[0]).to(equal(record)) } } describe("adding models in section") { beforeEach { let from = Section(identifier: 1, items: [ Model(identifier: 1) ]) let to = Section(identifier: 1, items: [ Model(identifier: 1), Model(identifier: 2) ]) records = generateRecordsForSections(from: [from], to: [to]) } it("works") { expect(records.count).to(equal(1)) let record = CollectionRecord.addItem(section: 0, index: 1) expect(records[0]).to(equal(record)) } } describe("reloading section") { beforeEach { let section = Section(identifier: 0, items: [Model(identifier: 123)]) let from = Section(identifier: 1, items: [ Model(identifier: 1) ]) let to = Section(identifier: 1, items: []) records = generateRecordsForSections(from: [section, from], to: [section, to]) } it("reloads section when its models is or was null") { expect(records.count).to(equal(1)) let record = CollectionRecord.reloadSection(section: 1) expect(records[0]).to(equal(record)) } } describe("empty") { beforeEach { records = generateRecordsForSections(from: Array<Section>(), to: Array<Section>()) } it("works") { expect(records.count).to(equal(0)) } } describe("Removing section") { beforeEach { let section = Section(identifier: 0, items: [Model(identifier: 123)]) let from = Section(identifier: 1, items: [ Model(identifier: 1) ]) records = generateRecordsForSections(from: [section, from], to: [section]) } it("removes section") { expect(records.count).to(equal(1)) let record = CollectionRecord.removeSection(section: 1) expect(records[0]).to(equal(record)) } } describe("Moving a section") { beforeEach { let section = Section(identifier: 0, items: [Model(identifier: 123)]) let from = Section(identifier: 1, items: [ Model(identifier: 1) ]) records = generateRecordsForSections(from: [section, from], to: [from, section]) } it("moves section") { expect(records.count).to(equal(1)) let record = CollectionRecord.moveSection(section: 1, from: 0) expect(records[0]).to(equal(record)) } } describe("Removing section and insert item") { beforeEach { let from = [ Section(identifier: 0, items: [Model(identifier: 128)]), Section(identifier: 1, items: [Model(identifier: 512)]), Section(identifier: 2, items: [Model(identifier: 1024)]), Section(identifier: 3, items: [Model(identifier: 2048)]), ] let to = [ Section(identifier: 1, items: [ Model(identifier: 512), Model(identifier: 4096) ]), Section(identifier: 2, items: [Model(identifier: 1024)]), Section(identifier: 3, items: [Model(identifier: 2048)]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("removes section") { let record = CollectionRecord.removeSection(section: 0) expect(records[1]).to(equal(record)) } it("adds item record") { let record = CollectionRecord.addItem(section: 0, index: 1) expect(records[0]).to(equal(record)) } } describe("Inserting section and item") { beforeEach { let from = [ Section(identifier: 1, items: [Model(identifier: 512)]) ] let to = [ Section(identifier: 0, items: [Model(identifier: 128)]), Section(identifier: 1, items: [ Model(identifier: 512), Model(identifier: 4096) ]) ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("adds section") { let record = CollectionRecord.addSection(section: 0) expect(records[1]).to(equal(record)) } it("adds item record") { let record = CollectionRecord.addItem(section: 1, index: 1) expect(records[0]).to(equal(record)) } } describe("Moving items and removing section") { beforeEach { let from = [ Section(identifier: 0, items: [Model(identifier: 128)]), Section(identifier: 1, items: [Model(identifier: 512), Model(identifier: 2048)]), Section(identifier: 2, items: [Model(identifier: 1024)]), ] let to = [ Section(identifier: 1, items: [ Model(identifier: 2048), Model(identifier: 512), ]), Section(identifier: 2, items: [Model(identifier: 1024)]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("removes section") { let record = CollectionRecord.removeSection(section: 0) expect(records[1]).to(equal(record)) } it("creates move record") { let record = CollectionRecord.moveItem( from: (section: 1, index: 0), to: (section: 0, index: 1)) expect(records[0]).to(equal(record)) } } describe("Change records with section changes") { beforeEach { let from = [ Section(identifier: 1, items: [ Model(identifier: 512, count: 2), ]) ] let to = [ Section(identifier: 0, items: [Model(identifier: 64)]), Section(identifier: 1, items: [ Model(identifier: 512, count: 4), ]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("adds section") { let record = CollectionRecord.addSection(section: 0) expect(records[1]).to(equal(record)) } it("creates change record") { let record = CollectionRecord.changeItem( from: (section: 0, index: 0), to: (section: 1, index: 0)) expect(records[0]).to(equal(record)) } } describe("Change records combined with remove item in same section") { beforeEach { let from = [ Section(identifier: 1, items: [ Model(identifier: 64), Model(identifier: 512, count: 2) ]) ] let to = [ Section(identifier: 1, items: [ Model(identifier: 512, count: 1) ]) ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("removes item") { let record = CollectionRecord.removeItem(section: 0, index: 0) expect(records[0]).to(equal(record)) } it("creates change record") { let record = CollectionRecord.changeItem( from: (section: 0, index: 1), to: (section: 0, index: 0)) expect(records[1]).to(equal(record)) } } describe("Adding section and removing item") { beforeEach { let from = [ Section(identifier: 1, items: [ Model(identifier: 512), Model(identifier: 2048) ]) ] let to = [ Section(identifier: 0, items: [Model(identifier: 64)]), Section(identifier: 1, items: [ Model(identifier: 512), ]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("created add section record") { let record = CollectionRecord.addSection(section: 0) expect(records[1]).to(equal(record)) } it("creates remove item record") { let record = CollectionRecord.removeItem(section: 0, index: 1) expect(records[0]).to(equal(record)) } } describe("Removing section and removing item") { beforeEach { let from = [ Section(identifier: 0, items: [Model(identifier: 64)]), Section(identifier: 1, items: [ Model(identifier: 512), Model(identifier: 2048) ]) ] let to = [ Section(identifier: 1, items: [ Model(identifier: 512), ]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("created add section record") { let record = CollectionRecord.removeSection(section: 0) expect(records[1]).to(equal(record)) } it("creates remove item record") { let record = CollectionRecord.removeItem(section: 1, index: 1) expect(records[0]).to(equal(record)) } } describe("Moving items and adding section") { beforeEach { let from = [ Section(identifier: 1, items: [ Model(identifier: 512), Model(identifier: 2048) ]) ] let to = [ Section(identifier: 0, items: [Model(identifier: 64)]), Section(identifier: 1, items: [ Model(identifier: 2048), Model(identifier: 512), ]), ] records = generateRecordsForSections(from: from, to: to) } it("generates records") { expect(records.count).to(equal(2)) } it("adds section") { let record = CollectionRecord.addSection(section: 0) expect(records[1]).to(equal(record)) } it("creates move record") { let record = CollectionRecord.moveItem( from: (section: 0, index: 0), to: (section: 1, index: 1)) expect(records[0]).to(equal(record)) } } } } } }
mit
4ec3e4f60153a05ab78f7ab202674d6d
30.488665
95
0.49676
4.6524
false
false
false
false
gregomni/swift
test/attr/open.swift
10
6697
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-module -c %S/Inputs/OpenHelpers.swift -o %t/OpenHelpers.swiftmodule // RUN: %target-typecheck-verify-swift -I %t import OpenHelpers /**** General structural limitations on open. ****/ open private class OpenIsNotCompatibleWithPrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open fileprivate class OpenIsNotCompatibleWithFilePrivate {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open internal class OpenIsNotCompatibleWithInternal {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open public class OpenIsNotCompatibleWithPublic {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open open class OpenIsNotCompatibleWithOpen {} // expected-error {{duplicate modifier}} expected-note{{modifier already specified here}} open typealias OpenIsNotAllowedOnTypeAliases = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open struct OpenIsNotAllowedOnStructs {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open enum OpenIsNotAllowedOnEnums_AtLeastNotYet {} // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} /**** Open entities are at least public. ****/ func foo(object: ExternalOpenClass) { object.openMethod() object.openProperty += 5 object[MarkerForOpenSubscripts()] += 5 } /**** Open classes. ****/ open class ClassesMayBeDeclaredOpen {} class ExternalSuperClassesMustBeOpen : ExternalNonOpenClass {} // expected-error {{cannot inherit from non-open class 'ExternalNonOpenClass' outside of its defining module}} class ExternalSuperClassesMayBeOpen : ExternalOpenClass {} class NestedClassesOfPublicTypesAreOpen : ExternalStruct.OpenClass {} // This one is hard to diagnose. class NestedClassesOfInternalTypesAreNotOpen : ExternalInternalStruct.OpenClass {} // expected-error {{cannot find type 'ExternalInternalStruct' in scope}} class NestedPublicClassesOfOpenClassesAreNotOpen : ExternalOpenClass.PublicClass {} // expected-error {{cannot inherit from non-open class 'ExternalOpenClass.PublicClass' outside of its defining module}} open final class ClassesMayNotBeBothOpenAndFinal {} // expected-error {{class cannot be declared both 'final' and 'open'}} public class NonOpenSuperClass {} // expected-note {{superclass is declared here}} open class OpenClassesMustHaveOpenSuperClasses : NonOpenSuperClass {} // expected-error {{superclass 'NonOpenSuperClass' of open class must be open}} /**** Open methods. ****/ open class AnOpenClass { open func openMethod() {} open var openVar: Int = 0 open typealias MyInt = Int // expected-error {{only classes and overridable class members can be declared 'open'; use 'public'}} open subscript(_: MarkerForOpenSubscripts) -> Int { return 0 } } internal class NonOpenClassesCanHaveOpenMembers { open var openVar: Int = 0; open func openMethod() {} } class SubClass : ExternalOpenClass { override func openMethod() {} override var openProperty: Int { get{return 0} set{} } override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } override func nonOpenMethod() {} // expected-error {{overriding non-open instance method outside of its defining module}} override var nonOpenProperty: Int { get{return 0} set{} } // expected-error {{overriding non-open property outside of its defining module}} override subscript(index: MarkerForNonOpenSubscripts) -> Int { // expected-error {{overriding non-open subscript outside of its defining module}} get { return 0 } set {} } } open class ValidOpenSubClass : ExternalOpenClass { public override func openMethod() {} public override var openProperty: Int { get{return 0} set{} } public override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } } open class InvalidOpenSubClass : ExternalOpenClass { internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-11=open}} internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding property must be as accessible as the declaration it overrides}} {{3-11=open}} internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-11=open}} get { return 0 } set {} } } open class OpenSubClassFinalMembers : ExternalOpenClass { final public override func openMethod() {} final public override var openProperty: Int { get{return 0} set{} } final public override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } } open class InvalidOpenSubClassFinalMembers : ExternalOpenClass { final internal override func openMethod() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{9-17=public}} final internal override var openProperty: Int { get{return 0} set{} } // expected-error {{overriding property must be as accessible as its enclosing type}} {{9-17=public}} final internal override subscript(index: MarkerForOpenSubscripts) -> Int { // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{9-17=public}} get { return 0 } set {} } } public class PublicSubClass : ExternalOpenClass { public override func openMethod() {} public override var openProperty: Int { get{return 0} set{} } public override subscript(index: MarkerForOpenSubscripts) -> Int { get { return 0 } set {} } } // The proposal originally made these invalid, but we changed our minds. open class OpenSuperClass { public func publicMethod() {} public var publicProperty: Int { return 0 } public subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 } } open class OpenSubClass : OpenSuperClass { open override func publicMethod() {} open override var publicProperty: Int { return 0 } open override subscript(index: MarkerForNonOpenSubscripts) -> Int { return 0 } } class InvalidOpenExtensionClass { } open extension InvalidOpenExtensionClass { // expected-error {{extensions cannot be declared 'open'; declare individual members as 'open' instead}} {{1-6=}} {{3-3=public }} {{3-3=public }} func C() { } // Insert public private func A() { } // OK var F: Int { 3 } // Insert public private var G: Int { 3 } // Okay }
apache-2.0
5ccd41e0bf424390ade2970971d6bf86
45.186207
203
0.742422
4.295702
false
false
false
false
arsonik/AKTrakt
Source/shared/Objects/TraktShow.swift
1
1883
// // TraktShow.swift // Arsonik // // Created by Florian Morello on 09/04/15. // Copyright (c) 2015 Florian Morello. All rights reserved. // import Foundation /// Represents a tv show public class TraktShow: TraktObject, Descriptable, Trending, Watchlist, Credits, Searchable, Recommandable { /// Production year public var year: UInt? /// Descriptable conformance public var title: String? /// Descriptable conformance public var overview: String? /// Seasons public var seasons: [TraktSeason] = [] /// Watchlist conformance public var watchlist: Bool? /** Digest data - parameter data: data */ override public func digest(data: JSONHash?) { super.digest(data) year = data?["year"] as? UInt ?? year if let sdata = data?["seasons"] as? [JSONHash] { seasons = sdata.flatMap { TraktSeason(data: $0) } } } /// list of non watched episodes public var notCompleted: [TraktEpisode] { return seasons.flatMap { $0.notCompleted.flatMap { $0 } } } /** Return a season byt its number - parameter number: season number - returns: seasons */ public func season(number: TraktSeasonNumber) -> TraktSeason? { return seasons.filter {$0.number == number} . first } /// next episode to watch public var nextEpisode: TraktEpisode? { return notCompleted.first } public static var listName: String { return "shows" } public static var objectName: String { return "show" } /// CustomStringConvertible conformance public override var description: String { return "TraktShow(\(title))" } public func extend(with: TraktShow) { super.extend(with) year = with.year ?? year } }
mit
656ccc4fc792c8ed430cd479d9e99cca
22.5375
108
0.602762
4.33871
false
false
false
false
hejunbinlan/Operations
Operations/Operations/UIOperation.swift
1
2687
// // UIOperation.swift // Operations // // Created by Daniel Thorpe on 30/08/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation // MARK: - UI public protocol PresentingViewController: class { func presentViewController(viewController: UIViewController, animated: Bool, completion: (() -> Void)?) @available(iOS 8.0, *) func showViewController(vc: UIViewController, sender: AnyObject?) @available(iOS 8.0, *) func showDetailViewController(vc: UIViewController, sender: AnyObject?) } extension UIViewController: PresentingViewController { } public enum ViewControllerDisplayStyle<ViewController: PresentingViewController> { case Show(ViewController) case ShowDetail(ViewController) case Present(ViewController) public var controller: ViewController { switch self { case .Show(let controller): return controller case .ShowDetail(let controller): return controller case .Present(let controller): return controller } } public func displayController<C where C: UIViewController>(controller: C, sender: AnyObject?, completion: (() -> Void)?) { switch self { case .Present(let from): if controller is UIAlertController { from.presentViewController(controller, animated: true, completion: completion) } else { let nav = UINavigationController(rootViewController: controller) from.presentViewController(nav, animated: true, completion: completion) } case .Show(let from): from.showViewController(controller, sender: sender) case .ShowDetail(let from): from.showDetailViewController(controller, sender: sender) } } } public enum UIOperationError: ErrorType { case PresentationViewControllerNotSet } public class UIOperation<C, From where C: UIViewController, From: PresentingViewController>: Operation { public let controller: C public let from: ViewControllerDisplayStyle<From> public let sender: AnyObject? let completion: (() -> Void)? public init(controller: C, displayControllerFrom from: ViewControllerDisplayStyle<From>, sender: AnyObject? = .None, completion: (() -> Void)? = .None) { self.controller = controller self.from = from self.sender = sender self.completion = completion } public override func execute() { dispatch_async(Queue.Main.queue) { self.from.displayController(self.controller, sender: self.sender, completion: self.completion) } } }
mit
06abe0d14f304fa3e26321fbe56adc84
29.522727
157
0.669025
5.029963
false
false
false
false
toggl/superday
teferi/UI/Modules/Timeline/TimeSlotDetail/Helper/Annotation.swift
1
5066
import Foundation import MapKit class Annotation: NSObject, MKAnnotation { private let category : Category private let locationEntity : LocationEntity var image : UIImage { return imageOfPointWithCategory(color: category.color, categoryImage: category.icon.image) } var title: String? { return category.description } var subtitle: String? { return nil } var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: locationEntity.latitude, longitude: locationEntity.longitude) } init(category: Category, locationEntity: LocationEntity) { self.category = category self.locationEntity = locationEntity } private func imageOfPointWithCategory(imageSize: CGSize = CGSize(width: 52, height: 52), color: UIColor, categoryImage: UIImage) -> UIImage { UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) drawPointWithCategory(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), color: color, categoryImage: categoryImage) let imageOfPointWithCategory = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return imageOfPointWithCategory } private func drawPointWithCategory(frame: CGRect, color: UIColor, categoryImage: UIImage) { //// General Declarations let context = UIGraphicsGetCurrentContext()! // This non-generic function dramatically improves compilation times of complex expressions. func fastFloor(_ x: CGFloat) -> CGFloat { return floor(x) } //// Subframes let group: CGRect = CGRect(x: frame.minX + 2, y: frame.minY, width: frame.width - 4, height: frame.height) //// Group //// Oval Drawing let ovalPath = UIBezierPath() ovalPath.move(to: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.45833 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 0.61132 * group.width, y: group.minY + 0.90527 * group.height), controlPoint1: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.67639 * group.height), controlPoint2: CGPoint(x: group.minX + 0.83388 * group.width, y: group.minY + 0.85888 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 0.50000 * group.width, y: group.minY + 1.00000 * group.height), controlPoint1: CGPoint(x: group.minX + 0.58584 * group.width, y: group.minY + 0.91058 * group.height), controlPoint2: CGPoint(x: group.minX + 0.50000 * group.width, y: group.minY + 1.00000 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 0.38342 * group.width, y: group.minY + 0.90414 * group.height), controlPoint1: CGPoint(x: group.minX + 0.50000 * group.width, y: group.minY + 1.00000 * group.height), controlPoint2: CGPoint(x: group.minX + 0.40868 * group.width, y: group.minY + 0.90967 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.45833 * group.height), controlPoint1: CGPoint(x: group.minX + 0.16351 * group.width, y: group.minY + 0.85600 * group.height), controlPoint2: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.67467 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 0.50000 * group.width, y: group.minY + 0.00000 * group.height), controlPoint1: CGPoint(x: group.minX + 0.00000 * group.width, y: group.minY + 0.20520 * group.height), controlPoint2: CGPoint(x: group.minX + 0.22386 * group.width, y: group.minY + 0.00000 * group.height)) ovalPath.addCurve(to: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.45833 * group.height), controlPoint1: CGPoint(x: group.minX + 0.77614 * group.width, y: group.minY + 0.00000 * group.height), controlPoint2: CGPoint(x: group.minX + 1.00000 * group.width, y: group.minY + 0.20520 * group.height)) ovalPath.close() color.setFill() ovalPath.fill() //// Rectangle Drawing let rectangleRect = CGRect(x: group.minX + fastFloor(group.width * 0.20833 + 0.5), y: group.minY + fastFloor(group.height * 0.19231 + 0.5), width: fastFloor(group.width * 0.79167 + 0.5) - fastFloor(group.width * 0.20833 + 0.5), height: fastFloor(group.height * 0.73077 + 0.5) - fastFloor(group.height * 0.19231 + 0.5)) let rectanglePath = UIBezierPath(rect: rectangleRect) context.saveGState() rectanglePath.addClip() context.translateBy(x: floor(rectangleRect.minX + 0.5 + ((rectangleRect.width - categoryImage.size.width) / 2)), y: floor(rectangleRect.minY + 0.5 + ((rectangleRect.height - categoryImage.size.height) / 2) )) context.scaleBy(x: 1, y: -1) context.translateBy(x: 0, y: -categoryImage.size.height) context.draw(categoryImage.cgImage!, in: CGRect(x: 0, y: 0, width: categoryImage.size.width, height: categoryImage.size.height)) context.restoreGState() } }
bsd-3-clause
a0024a7d3d779689201555bfcbe74f50
59.309524
326
0.667785
3.774963
false
false
false
false
Jackysonglanlan/Scripts
swift/xunyou_accelerator/Sources/srcLibs/SwifterSwift/stdlib/SignedIntegerExtensions.swift
2
2749
// // SignedIntegerExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/15/17. // Copyright © 2017 SwifterSwift // #if canImport(Foundation) import Foundation #endif // MARK: - Properties public extension SignedInteger { /// SwifterSwift: Absolute value of integer number. public var abs: Self { return Swift.abs(self) } /// SwifterSwift: Check if integer is positive. public var isPositive: Bool { return self > 0 } /// SwifterSwift: Check if integer is negative. public var isNegative: Bool { return self < 0 } /// SwifterSwift: Check if integer is even. public var isEven: Bool { return (self % 2) == 0 } /// SwifterSwift: Check if integer is odd. public var isOdd: Bool { return (self % 2) != 0 } /// SwifterSwift: String of format (XXh XXm) from seconds Int. public var timeString: String { guard self > 0 else { return "0 sec" } if self < 60 { return "\(self) sec" } if self < 3600 { return "\(self / 60) min" } let hours = self / 3600 let mins = (self % 3600) / 60 if hours != 0 && mins == 0 { return "\(hours)h" } return "\(hours)h \(mins)m" } } // MARK: - Methods public extension SignedInteger { // swiftlint:disable next identifier_name /// SwifterSwift: Greatest common divisor of integer value and n. /// /// - Parameter n: integer value to find gcd with. /// - Returns: greatest common divisor of self and n. public func gcd(of n: Self) -> Self { return n == 0 ? self : n.gcd(of: self % n) } // swiftlint:disable next identifier_name /// SwifterSwift: Least common multiple of integer and n. /// /// - Parameter n: integer value to find lcm with. /// - Returns: least common multiple of self and n. public func lcm(of n: Self) -> Self { return (self * n).abs / gcd(of: n) } #if canImport(Foundation) /// SwifterSwift: Ordinal representation of an integer. /// /// print((12).ordinalString()) // prints "12th" /// /// - Parameter locale: locale, default is .current. /// - Returns: string ordinal representation of number in specified locale language. E.g. input 92, output in "en": "92nd". @available(iOS 9.0, macOS 10.11, *) public func ordinalString(locale: Locale = .current) -> String? { let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = .ordinal guard let number = self as? NSNumber else { return nil } return formatter.string(from: number) } #endif }
unlicense
5ce9b207e0039a748a424d33e13b66a2
26.48
127
0.586245
4.176292
false
false
false
false
pccole/GitHubJobs-iOS
GitHubJobs/Extensions/Color+Extensions.swift
1
1061
// // Color+Extensions.swift // GitHubJobs // // Created by Phil Cole on 5/5/20. // Copyright © 2020 Cole LLC. All rights reserved. // import Foundation import SwiftUI extension Color { static let ghGrayLight = Color("gray-light") static let ghGray = Color("gray") static let ghGrayDark = Color("gray-dark") static let offWhite = Color(red: 217 / 255, green: 225 / 255, blue: 235 / 255) static let background = Color("background") static let ghBlueLight = Color("blue-light") static let ghBlue = Color("blue") static let darkBackground = Color("dark-background") } extension UIColor { static let ghGrayLight = UIColor(named: "gray-light")! static let ghGray = UIColor(named: "gray")! static let offWhite = UIColor(red: 217 / 255, green: 225 / 255, blue: 235 / 255, alpha: 1.0) static let background = UIColor(named: "background")! static let ghBlueLight = UIColor(named: "blue-light")! static let ghBlue = UIColor(named: "blue")! }
mit
2bd014c0a76bc074e7776e4a6dca9eff
23.651163
96
0.633019
3.882784
false
false
false
false
CryptoKitten/CryptoEssentials
Sources/Padding.swift
1
2741
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // 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. public protocol Padding { static func add(to data: [UInt8], blockSize:Int) -> [UInt8] static func remove(from data: [UInt8], blockSize:Int?) -> [UInt8] } public struct NoPadding: Padding { public static func add(to data: [UInt8], blockSize: Int) -> [UInt8] { return data; } public static func remove(from data: [UInt8], blockSize: Int?) -> [UInt8] { return data; } } public struct PKCS7: Padding { public enum Error: Swift.Error { case InvalidPaddingValue } public static func add(to bytes: [UInt8], blockSize:Int) -> [UInt8] { let padding = UInt8(blockSize - (bytes.count % blockSize)) var withPadding = bytes if (padding == 0) { // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added. for _ in 0..<blockSize { withPadding.append(contentsOf: [UInt8(blockSize)]) } } else { // The value of each added byte is the number of bytes that are added for _ in 0..<padding { withPadding.append(contentsOf: [UInt8(padding)]) } } return withPadding } public static func remove(from bytes: [UInt8], blockSize:Int?) -> [UInt8] { assert(bytes.count > 0, "Need bytes to remove padding") guard bytes.count > 0, let lastByte = bytes.last else { return bytes } let padding = Int(lastByte) // last byte let finalLength = bytes.count - padding if finalLength < 0 { return bytes } if padding >= 1 { return Array(bytes[0..<finalLength]) } return bytes } }
mit
596da6d0ca8d7bfb47ef45560a77d121
38.695652
216
0.638554
4.468189
false
false
false
false
eweill/Forge
Forge/Forge/MTLTexture+Array.swift
2
4442
/* Copyright (c) 2016-2017 M.I. Hollemans 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 Metal extension MTLTexture { /** Creates a new array of `Float`s and copies the texture's pixels into it. */ public func toFloatArray(width: Int, height: Int, featureChannels: Int) -> [Float] { return toArray(width: width, height: height, featureChannels: featureChannels, initial: Float(0)) } /** Creates a new array of `Float16`s and copies the texture's pixels into it. */ public func toFloat16Array(width: Int, height: Int, featureChannels: Int) -> [Float16] { return toArray(width: width, height: height, featureChannels: featureChannels, initial: Float16(0)) } /** Creates a new array of `UInt8`s and copies the texture's pixels into it. */ public func toUInt8Array(width: Int, height: Int, featureChannels: Int) -> [UInt8] { return toArray(width: width, height: height, featureChannels: featureChannels, initial: UInt8(0)) } /** Convenience function that copies the texture's pixel data to a Swift array. The type of `initial` determines the type of the output array. In the following example, the type of bytes is `[UInt8]`. let bytes = texture.toArray(width: 100, height: 100, featureChannels: 4, initial: UInt8(0)) - Parameters: - featureChannels: The number of color components per pixel: must be 1, 2, or 4. - initial: This parameter is necessary because we need to give the array an initial value. Unfortunately, we can't do `[T](repeating: T(0), ...)` since `T` could be anything and may not have an init that takes a literal value. */ func toArray<T>(width: Int, height: Int, featureChannels: Int, initial: T) -> [T] { assert(featureChannels != 3 && featureChannels <= 4, "channels must be 1, 2, or 4") var bytes = [T](repeating: initial, count: width * height * featureChannels) let region = MTLRegionMake2D(0, 0, width, height) getBytes(&bytes, bytesPerRow: width * featureChannels * MemoryLayout<T>.stride, from: region, mipmapLevel: 0) return bytes } } extension MTLDevice { /** Convenience function that makes a new texture from a Swift array. This method copies a Swift array into an MTLTexture that you can then turn into an MPSImage. However, this does not let you create an image with > 4 channels. (See the extension on MPSImage for that.) - Parameters: - channels: The number of color components per pixel: must be 1, 2 or 4. */ public func makeTexture<T>(array: [T], width: Int, height: Int, featureChannels: Int, pixelFormat: MTLPixelFormat) -> MTLTexture? { assert(featureChannels != 3 && featureChannels <= 4, "channels must be 1, 2, or 4") let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: pixelFormat, width: width, height: height, mipmapped: false) guard let texture = makeTexture(descriptor: textureDescriptor) else { return nil } let region = MTLRegionMake2D(0, 0, width, height) texture.replace(region: region, mipmapLevel: 0, withBytes: array, bytesPerRow: width * MemoryLayout<T>.stride * featureChannels) return texture } }
mit
ca61279a172bb8594e2115de874fa7d8
40.514019
99
0.680549
4.411122
false
false
false
false
LoopKit/LoopKit
LoopKit/InsulinKit/DoseType.swift
1
1805
// // DoseType.swift // LoopKit // // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation /// A general set of ways insulin can be delivered by a pump public enum DoseType: String, CaseIterable { case basal case bolus case resume case suspend case tempBasal public var localizedDescription: String { switch self { case .basal: return NSLocalizedString("Basal", comment: "Title for basal dose type") case .bolus: return NSLocalizedString("Bolus", comment: "Title for bolus dose type") case .tempBasal: return NSLocalizedString("Temp Basal", comment: "Title for temp basal dose type") case .suspend: return NSLocalizedString("Suspended", comment: "Title for suspend dose type") case .resume: return NSLocalizedString("Resumed", comment: "Title for resume dose type") } } } extension DoseType: Codable {} /// Compatibility transform to PumpEventType extension DoseType { public init?(pumpEventType: PumpEventType) { switch pumpEventType { case .basal: self = .basal case .bolus: self = .bolus case .resume: self = .resume case .suspend: self = .suspend case .tempBasal: self = .tempBasal case .alarm, .alarmClear, .prime, .rewind: return nil } } public var pumpEventType: PumpEventType { switch self { case .basal: return .basal case .bolus: return .bolus case .resume: return .resume case .suspend: return .suspend case .tempBasal: return .tempBasal } } }
mit
38057f917555fc373b03a6ff38da393d
24.771429
93
0.577605
4.915531
false
false
false
false
mrlegowatch/JSON-to-Swift-Converter
SharedSources/AppSettings.swift
1
4416
// // AppSettings.swift // JSON to Swift Converter // // Created by Brian Arnold on 2/22/17. // Copyright © 2018 Brian Arnold. All rights reserved. // import Foundation /// Persistence adapter for UserDefaults mapped to the settings required by this app. This also wraps the user defaults shared between the settings application and the Xcode app extension. public struct AppSettings { /// The default shared user defaults suite for the settings application and the Xcode app extension. public static let sharedUserDefaults = UserDefaults(suiteName: "JSON-to-Swift-Converter")! /// The internal settings. internal let userDefaults: UserDefaults /// The internal keys for the internal settings. internal struct Key { static let declaration = "Declaration" static let typeUnwrapping = "TypeUnwrapping" static let addDefaultValue = "AddDefaultValue" static let supportCodable = "SupportCodable" } /// Initializes to user defaults settings. Defaults to the shared user defaults. public init(_ userDefaults: UserDefaults = sharedUserDefaults) { self.userDefaults = userDefaults } /// Support for declaring a property as let or var. public enum Declaration: Int { case useLet = 0 case useVar = 1 } /// Accesses whether a property should be declared as let or var. Default is `.useLet` public var declaration: Declaration { get { guard userDefaults.object(forKey: Key.declaration) != nil else { return .useLet } return Declaration(rawValue: userDefaults.integer(forKey: Key.declaration))! } set { userDefaults.set(newValue.rawValue, forKey: Key.declaration) } } /// Support for type unwrapping of a property. public enum TypeUnwrapping: Int { case explicit = 0 case optional = 1 case required = 2 } /// Accesses whether a property type should be unwrapped (as ? optional or ! required) or not (explicit). /// Default is `.required` public var typeUnwrapping: TypeUnwrapping { get { guard userDefaults.object(forKey: Key.typeUnwrapping) != nil else { return .required } return TypeUnwrapping(rawValue: userDefaults.integer(forKey: Key.typeUnwrapping))! } set { userDefaults.set(newValue.rawValue, forKey: Key.typeUnwrapping) } } /// Accesses whether to add a default value for the property. Default is false. public var addDefaultValue: Bool { get { guard userDefaults.object(forKey: Key.addDefaultValue) != nil else { return false } return userDefaults.bool(forKey: Key.addDefaultValue) } set { userDefaults.set(newValue, forKey: Key.addDefaultValue) } } /// Accesses whether to add key declarations. Default is true. public var supportCodable: Bool { get { guard userDefaults.object(forKey: Key.supportCodable) != nil else { return true } return userDefaults.bool(forKey: Key.supportCodable) } set { userDefaults.set(newValue, forKey: Key.supportCodable) } } } extension AppSettings.TypeUnwrapping: CustomStringConvertible { /// Return the string representation for this type unwrapping. /// Returns an empty string if explicit, "?" if optional, "!" if required. public var description: String { let type: String switch self { case .explicit: type = "" case .optional: type = "?" case .required: type = "!" } return type } } extension AppSettings { /// For testing: encapsulate what it takes to do a full reset on settings. internal func reset() { // Note: Setting to plain 'nil' doesn't work; that causes a 'nil URL?' to be the default (weird). Radar'd. // Note: using setNilForKey doesn't work if the setting has already been set to NSNumber. let nilNSNumber: NSNumber? = nil userDefaults.set(nilNSNumber, forKey: Key.declaration) userDefaults.set(nilNSNumber, forKey: Key.typeUnwrapping) userDefaults.set(nilNSNumber, forKey: Key.supportCodable) userDefaults.set(nilNSNumber, forKey: Key.addDefaultValue) } }
mit
80f3ba51c491f760482c0b1657e91f98
34.894309
188
0.6453
4.977452
false
false
false
false
npu3pak/ios-lib-tableview-backgrounds
Example/TableViewBackgrounds/TableViewController.swift
1
1179
// // TableViewController.swift // TableViewBackgrounds // // Created by Evgeniy Safronov on 21.05.17. // Copyright © 2017 Evgeniy Safronov. All rights reserved. // import UIKit import TableViewBackgrounds class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() TableViewLoadingBackgroundView.appearance().backgroundColor = UIColor.yellow TableViewMessageBackgroundView.appearance().backgroundColor = UIColor.lightGray TableViewContentBackgroundView.appearance().backgroundColor = UIColor.cyan TableViewLoadingActivityIndicatorView.appearance().color = UIColor.red } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = false showContentBackground() } @IBAction func showLoading(_ sender: Any) { showLoadingBackground("Loading...") } @IBAction func showMessage(_ sender: Any) { showMessageBackground("Message", subtitle: "Description") } @IBAction func showContent(_ sender: Any) { showContentBackground() } }
mit
b6fd06c122805c775cf0233632041ce5
28.45
87
0.702037
5.40367
false
false
false
false
romansorochak/ParallaxHeader
Exmple/ItemDetailedImagesDataSourse.swift
1
3552
// // ItemDetailedImagesDataSourse.swift // ParallaxHeader // // Created by Roman Sorochak on 6/27/17. // Copyright © 2017 MagicLab. All rights reserved. // import UIKit import Reusable class ImagesDataSourse: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private (set) weak var collectionView: UICollectionView? { didSet { collectionView?.dataSource = self collectionView?.delegate = self } } private (set) var handler: ((_ item: IndexPath)->Void)? private (set) var images: [UIImage]? private (set) var selectedPicture: Int = 0 func setup( collectionView: UICollectionView, images: [UIImage]?, handler: ((_ item: IndexPath)->Void)? = nil ) { self.handler = handler self.images = images self.collectionView = collectionView } func selectCell(forIndexPath indexPath: IndexPath) { collectionView?.scrollToItem( at: indexPath, at: .centeredHorizontally, animated: true ) //deselect let prevIndexPath = IndexPath(item: selectedPicture, section: 0) if let prevCell = collectionView?.cellForItem(at: prevIndexPath) { prevCell.isSelected = false } //select if let cell = collectionView?.cellForItem(at: indexPath) as? ItemDetailedCell { cell.isSelected = true } selectedPicture = indexPath.row } func invalidateLayout() { collectionView?.collectionViewLayout.invalidateLayout() } func checkOnRightToLeftMode() { if UIApplication.isRTL { let indexPath = IndexPath(row: 0, section: 0) collectionView?.scrollToItem(at: indexPath, at: .right, animated: false) } } // MARK: CollectionView protocols func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 100, height: collectionView.frame.size.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets.zero } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueCell(for: indexPath) as ItemDetailedCell cell.isSelected = indexPath.item == selectedPicture cell.image = images?[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectCell(forIndexPath: indexPath) handler?(indexPath) } }
mit
1fb31efcf4c27d414dd58387eac1ddfa
32.186916
175
0.652211
5.76461
false
false
false
false
onionsapp/Onions-SwiftFramework
OnionsFramework/Session/OCSession.swift
1
6151
// // OCSession.swift // OnionsFramework // // Created by Benjamin Gordon on 12/14/15. // Copyright © 2015 subvertllc. All rights reserved. // import Foundation import Parse class OCSession: NSObject { // MARK: - Properties static var allOnions : [OCOnion] = [] static var username : String = "" static let maxTitleCharacterCount : Int = 30 static let maxInfoCharacterCount : Int = 2500 // MARK: - Initialize static func initializeOnions(appId: String, clientKey: String) -> Void { OCOnion.registerSubclass() Parse.setApplicationId(appId, clientKey: clientKey) } // MARK: - Login static func login(username: String, password: String, completion: SuccessClosure) -> Void { let stretchedUsername = OCSecurity.stretchedCredential(username) let stretchedPassword = OCSecurity.stretchedCredential(password + username) PFUser.logInWithUsernameInBackground(stretchedUsername, password: stretchedPassword, block: { (user, error) in self.username = username OCSecurity.setAccountEncryptionKey(password) completion(success: user != nil) }) } // MARK: - Logout static func logout(completion: SuccessClosure) -> Void { // Drop all data for onion in self.allOnions { onion.dropData() } self.allOnions = [] // Reset encryption key self.username = "" OCSecurity.setAccountEncryptionKey(nil) // Logout user PFUser.logOut() // Run completion completion(success: true) } // MARK: - Delete Account static func deleteAccount(completion: SuccessClosure) -> Void { PFObject.deleteAllInBackground(self.allOnions, block: { oSuccess, oError in if (!oSuccess) { print("OCSession->deleteAccount() - could not delete all onions tied to account. Proceeding to user.") } PFUser.currentUser()?.deleteInBackgroundWithBlock({ aSuccess, aError in if (!aSuccess) { print("OCSession->deleteAccount() - could not delete user.") } completion(success: aSuccess && oSuccess) }) }) } // MARK: - Register Account static func registerNewAccount(username: String, password: String, completion: SuccessClosure) -> Void { let stretchedUsername = OCSecurity.stretchedCredential(username) let stretchedPassword = OCSecurity.stretchedCredential(password + username) let user = PFUser() user.username = stretchedUsername user.password = stretchedPassword user.saveInBackgroundWithBlock({ success, error in self.username = username OCSecurity.setAccountEncryptionKey(password) completion(success: success) }) } // MARK: - Onions static func loadOnions(completion: SuccessClosure) -> Void { if let user = PFUser.currentUser() { if let userId = user.objectId { let query = OCOnion.query() query?.whereKey("userId", equalTo: userId).orderByAscending("createdAt") query?.findObjectsInBackgroundWithBlock( { objects, error in // Check error if (error != nil) { print("OCSession->loadOnions() failed while retrieving onions from the server.") completion(success: false) return } // Assign allOnions if it exists if let onions = objects as? [OCOnion] { self.allOnions = onions completion(success: true) return } }) } } // Something failed print("OCSession->loadOnions() failed - no current user.") completion(success: false) } static func decryptOnions(completion: SuccessClosure) -> Void { if let _ = PFUser.currentUser() { // Decrypt each onion, and determine if any have failed var hasFailed = false for onion in self.allOnions { if (!onion.decrypt()) { hasFailed = true } } completion(success: !hasFailed) } // Something failed print("OCSession->decryptOnions() failed - no current user.") completion(success: false) } static func createOnion(title: String?, info: String?, completion: SuccessClosure) -> Void { if let oTitle = title, oInfo = info { let onion = OCOnion() onion.onionTitle = oTitle onion.onionInfo = oInfo onion.saveOnion({ success in if (success) { self.allOnions.append(onion) } else { print("OCSession->createOnion() failed - saving onion failed.") } completion(success: success) }) } // Failed print("OCSession->createOnion() failed - title or info were blank") completion(success: false) } static func deleteOnion(atIndex: Int, completion: SuccessClosure) -> Void { if (self.allOnions.count > atIndex || atIndex < 0) { print("OCSession->deleteOnion() failed - index was not an accurate value.") completion(success: false) return } let onion = self.allOnions[atIndex] onion.deleteInBackgroundWithBlock({ success, error in if (success) { self.allOnions.removeAtIndex(atIndex) } else { print("OCSession->deleteOnion() failed - could not delete onion from server.") } completion(success: success) }) } }
mit
13e3d81d36c9c85990451732ccd7556d
34.142857
118
0.55122
5.137845
false
false
false
false
PeteShearer/SwiftNinja
015-REST API Basics/REST API Basics.playground/Contents.swift
1
1444
// NOTE: THIS IS NOT A GREAT WAY TO DO HTTP CALLS (WITH DICTIONARIES) TO REST ENDPOINTS ANY MORE. // CHECK OUT LESSON 035 - HTTP REQUESTS WITH CODABLE FOR SWIFT'S IMPROVEMENTS import UIKit import PlaygroundSupport // <-- This is just for the playground PlaygroundPage.current.needsIndefiniteExecution = true // <-- And so is this, so it will continue to execute so we can get our results back let url = "http://jsonplaceholder.typicode.com/posts/1" // If you want to test a failing URL, use the following line and comment out the one above // let url = "http://jsonplaceholder.typicodeooo.com/posts/1" let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) let session = URLSession.shared let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in if let jsonData = data { let options = JSONSerialization.ReadingOptions() let jsonArray = try! JSONSerialization.jsonObject(with: jsonData, options: options) as! [String:AnyObject] if let userId = jsonArray["userId"], let id = jsonArray["id"], let body = jsonArray["body"], let title = jsonArray["title"] { print("The id was \(id), the title was \(title), the body was \(body) and the userId associated was \(userId)") } else { print("Failed batch parsing") } } else { print ("We didn't get back data") } }) task.resume()
bsd-2-clause
71ddf29751aee2a7972c65c629a1f030
42.757576
139
0.684211
4.149425
false
false
false
false
alexktchen/ExchangeRate
Core/SwiftyJSON.swift
1
36198
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let error1 as NSError { error.memory = error1 self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case _ as NSString: _type = .String case _ as NSNull: _type = .Null case _ as [AnyObject]: _type = .Array case _ as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return (self.object as! [AnyObject]).count case .Dictionary: return (self.object as! [String : AnyObject]).count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator<(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return anyGenerator { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return anyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return anyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in Array(path.reverse()) { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: UInt? { get { return self.number?.unsignedIntegerValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: UInt { get { return self.numberValue.unsignedIntegerValue } } }
mit
331d81c8441b1d6bac4482e5b93d0d75
25.518681
264
0.527653
4.70654
false
false
false
false
krzyzanowskim/Natalie
Sources/natalie/SWXMLHash/SWXMLHash.swift
1
32707
// // SWXMLHash.swift // SWXMLHash // // Copyright (c) 2014 David Mohundro // // 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. // // swiftlint exceptions: // - Disabled file_length because there are a number of users that still pull the // source down as is and it makes pulling the code into a project easier. // swiftlint:disable file_length import Foundation let rootElementName = "SWXMLHash_Root_Element" /// Parser options public class SWXMLHashOptions { internal init() {} /// determines whether to parse the XML with lazy parsing or not public var shouldProcessLazily = false /// determines whether to parse XML namespaces or not (forwards to /// `XMLParser.shouldProcessNamespaces`) public var shouldProcessNamespaces = false /// Matching element names, element values, attribute names, attribute values /// will be case insensitive. This will not affect parsing (data does not change) public var caseInsensitive = false /// Encoding used for XML parsing. Default is set to UTF8 public var encoding = String.Encoding.utf8 /// Any contextual information set by the user for encoding public var userInfo = [CodingUserInfoKey: Any]() /// Detect XML parsing errors... defaults to false as this library will /// attempt to handle HTML which isn't always XML-compatible public var detectParsingErrors = false } /// Simple XML parser public class SWXMLHash { let options: SWXMLHashOptions private init(_ options: SWXMLHashOptions = SWXMLHashOptions()) { self.options = options } /** Method to configure how parsing works. - parameters: - configAction: a block that passes in an `SWXMLHashOptions` object with options to be set - returns: an `SWXMLHash` instance */ class public func config(_ configAction: (SWXMLHashOptions) -> Void) -> SWXMLHash { let opts = SWXMLHashOptions() configAction(opts) return SWXMLHash(opts) } /** Begins parsing the passed in XML string. - parameters: - xml: an XML string. __Note__ that this is not a URL but a string containing XML. - returns: an `XMLIndexer` instance that can be iterated over */ public func parse(_ xml: String) -> XMLIndexer { guard let data = xml.data(using: options.encoding) else { return .xmlError(.encoding) } return parse(data) } /** Begins parsing the passed in XML string. - parameters: - data: a `Data` instance containing XML - returns: an `XMLIndexer` instance that can be iterated over */ public func parse(_ data: Data) -> XMLIndexer { let parser: SimpleXmlParser = options.shouldProcessLazily ? LazyXMLParser(options) : FullXMLParser(options) return parser.parse(data) } /** Method to parse XML passed in as a string. - parameter xml: The XML to be parsed - returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(_ xml: String) -> XMLIndexer { return SWXMLHash().parse(xml) } /** Method to parse XML passed in as a Data instance. - parameter data: The XML to be parsed - returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(_ data: Data) -> XMLIndexer { return SWXMLHash().parse(data) } /** Method to lazily parse XML passed in as a string. - parameter xml: The XML to be parsed - returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func lazy(_ xml: String) -> XMLIndexer { return config { conf in conf.shouldProcessLazily = true }.parse(xml) } /** Method to lazily parse XML passed in as a Data instance. - parameter data: The XML to be parsed - returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func lazy(_ data: Data) -> XMLIndexer { return config { conf in conf.shouldProcessLazily = true }.parse(data) } } struct Stack<T> { var items = [T]() mutating func push(_ item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } mutating func drop() { _ = pop() } mutating func removeAll() { items.removeAll(keepingCapacity: false) } func top() -> T { return items[items.count - 1] } } protocol SimpleXmlParser { init(_ options: SWXMLHashOptions) func parse(_ data: Data) -> XMLIndexer } #if os(Linux) extension XMLParserDelegate { func parserDidStartDocument(_ parser: Foundation.XMLParser) { } func parserDidEndDocument(_ parser: Foundation.XMLParser) { } func parser(_ parser: Foundation.XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: Foundation.XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { } func parser(_ parser: Foundation.XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { } func parser(_ parser: Foundation.XMLParser, foundElementDeclarationWithName elementName: String, model: String) { } func parser(_ parser: Foundation.XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { } func parser(_ parser: Foundation.XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: Foundation.XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { } func parser(_ parser: Foundation.XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } func parser(_ parser: Foundation.XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { } func parser(_ parser: Foundation.XMLParser, didEndMappingPrefix prefix: String) { } func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) { } func parser(_ parser: Foundation.XMLParser, foundIgnorableWhitespace whitespaceString: String) { } func parser(_ parser: Foundation.XMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { } func parser(_ parser: Foundation.XMLParser, foundComment comment: String) { } func parser(_ parser: Foundation.XMLParser, foundCDATA CDATABlock: Data) { } func parser(_ parser: Foundation.XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? { return nil } func parser(_ parser: Foundation.XMLParser, parseErrorOccurred parseError: Error) { } func parser(_ parser: Foundation.XMLParser, validationErrorOccurred validationError: Error) { } } #endif /// The implementation of XMLParserDelegate and where the lazy parsing actually happens. class LazyXMLParser: NSObject, SimpleXmlParser, XMLParserDelegate { required init(_ options: SWXMLHashOptions) { root = XMLElement(name: rootElementName, options: options) self.options = options super.init() } let root: XMLElement var parentStack = Stack<XMLElement>() var elementStack = Stack<String>() var data: Data? var ops: [IndexOp] = [] let options: SWXMLHashOptions func parse(_ data: Data) -> XMLIndexer { self.data = data return XMLIndexer(self) } func startParsing(_ ops: [IndexOp]) { // clear any prior runs of parse... expected that this won't be necessary, // but you never know parentStack.removeAll() parentStack.push(root) self.ops = ops let parser = Foundation.XMLParser(data: data!) parser.shouldProcessNamespaces = options.shouldProcessNamespaces parser.delegate = self _ = parser.parse() } func parser(_ parser: Foundation.XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { elementStack.push(elementName) if !onMatch() { return } let currentNode = parentStack .top() .addElement(elementName, withAttributes: attributeDict, caseInsensitive: self.options.caseInsensitive) parentStack.push(currentNode) } func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) { if !onMatch() { return } let current = parentStack.top() current.addText(string) } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { if !onMatch() { return } if let cdataText = String(data: CDATABlock, encoding: String.Encoding.utf8) { let current = parentStack.top() current.addText(cdataText) } } func parser(_ parser: Foundation.XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let match = onMatch() elementStack.drop() if match { parentStack.drop() } } func onMatch() -> Bool { // we typically want to compare against the elementStack to see if it matches ops, *but* // if we're on the first element, we'll instead compare the other direction. if elementStack.items.count > ops.count { return elementStack.items.starts(with: ops.map { $0.key }) } else { return ops.map { $0.key }.starts(with: elementStack.items) } } } /// The implementation of XMLParserDelegate and where the parsing actually happens. class FullXMLParser: NSObject, SimpleXmlParser, XMLParserDelegate { required init(_ options: SWXMLHashOptions) { root = XMLElement(name: rootElementName, options: options) self.options = options super.init() } let root: XMLElement var parentStack = Stack<XMLElement>() let options: SWXMLHashOptions var parsingError: ParsingError? func parse(_ data: Data) -> XMLIndexer { // clear any prior runs of parse... expected that this won't be necessary, // but you never know parentStack.removeAll() parentStack.push(root) let parser = Foundation.XMLParser(data: data) parser.shouldProcessNamespaces = options.shouldProcessNamespaces parser.delegate = self _ = parser.parse() if options.detectParsingErrors, let err = parsingError { return XMLIndexer.parsingError(err) } else { return XMLIndexer(root) } } func parser(_ parser: Foundation.XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { let currentNode = parentStack .top() .addElement(elementName, withAttributes: attributeDict, caseInsensitive: self.options.caseInsensitive) parentStack.push(currentNode) } func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) { let current = parentStack.top() current.addText(string) } func parser(_ parser: Foundation.XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { parentStack.drop() } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { if let cdataText = String(data: CDATABlock, encoding: String.Encoding.utf8) { let current = parentStack.top() current.addText(cdataText) } } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { #if os(Linux) if let err = parseError as? NSError { parsingError = ParsingError(line: err.userInfo["NSXMLParserErrorLineNumber"] as? Int ?? 0, column: err.userInfo["NSXMLParserErrorColumn"] as? Int ?? 0) } #else let err = parseError as NSError parsingError = ParsingError(line: err.userInfo["NSXMLParserErrorLineNumber"] as? Int ?? 0, column: err.userInfo["NSXMLParserErrorColumn"] as? Int ?? 0) #endif } } /// Represents an indexed operation against a lazily parsed `XMLIndexer` public class IndexOp { var index: Int let key: String init(_ key: String) { self.key = key self.index = -1 } func toString() -> String { if index >= 0 { return key + " " + index.description } return key } } /// Represents a collection of `IndexOp` instances. Provides a means of iterating them /// to find a match in a lazily parsed `XMLIndexer` instance. public class IndexOps { var ops: [IndexOp] = [] let parser: LazyXMLParser init(parser: LazyXMLParser) { self.parser = parser } func findElements() -> XMLIndexer { parser.startParsing(ops) let indexer = XMLIndexer(parser.root) var childIndex = indexer for oper in ops { childIndex = childIndex[oper.key] if oper.index >= 0 { childIndex = childIndex[oper.index] } } ops.removeAll(keepingCapacity: false) return childIndex } func stringify() -> String { var ret = "" for oper in ops { ret += "[" + oper.toString() + "]" } return ret } } public struct ParsingError: Error { public let line: Int public let column: Int } /// Error type that is thrown when an indexing or parsing operation fails. public enum IndexingError: Error { case attribute(attr: String) case attributeValue(attr: String, value: String) case key(key: String) case index(idx: Int) case initialize(instance: AnyObject) case encoding case error // swiftlint:disable identifier_name // unavailable @available(*, unavailable, renamed: "attribute(attr:)") public static func Attribute(attr: String) -> IndexingError { fatalError("unavailable") } @available(*, unavailable, renamed: "attributeValue(attr:value:)") public static func AttributeValue(attr: String, value: String) -> IndexingError { fatalError("unavailable") } @available(*, unavailable, renamed: "key(key:)") public static func Key(key: String) -> IndexingError { fatalError("unavailable") } @available(*, unavailable, renamed: "index(idx:)") public static func Index(idx: Int) -> IndexingError { fatalError("unavailable") } @available(*, unavailable, renamed: "initialize(instance:)") public static func Init(instance: AnyObject) -> IndexingError { fatalError("unavailable") } @available(*, unavailable, renamed: "error") public static var Error: IndexingError { fatalError("unavailable") } // swiftlint:enable identifier_name } /// Returned from SWXMLHash, allows easy element lookup into XML data. public enum XMLIndexer { case element(XMLElement) case list([XMLElement]) case stream(IndexOps) case xmlError(IndexingError) case parsingError(ParsingError) // swiftlint:disable identifier_name // unavailable @available(*, unavailable, renamed: "element(_:)") public static func Element(_: XMLElement) -> XMLIndexer { fatalError("unavailable") } @available(*, unavailable, renamed: "list(_:)") public static func List(_: [XMLElement]) -> XMLIndexer { fatalError("unavailable") } @available(*, unavailable, renamed: "stream(_:)") public static func Stream(_: IndexOps) -> XMLIndexer { fatalError("unavailable") } @available(*, unavailable, renamed: "xmlError(_:)") public static func XMLError(_: IndexingError) -> XMLIndexer { fatalError("unavailable") } @available(*, unavailable, renamed: "withAttribute(_:_:)") public static func withAttr(_ attr: String, _ value: String) throws -> XMLIndexer { fatalError("unavailable") } // swiftlint:enable identifier_name /// The underlying XMLElement at the currently indexed level of XML. public var element: XMLElement? { switch self { case .element(let elem): return elem case .stream(let ops): let list = ops.findElements() return list.element default: return nil } } /// All elements at the currently indexed level public var all: [XMLIndexer] { return allElements.map { XMLIndexer($0) } } private var allElements: [XMLElement] { switch self { case .list(let list): return list case .element(let elem): return [elem] case .stream(let ops): let list = ops.findElements() return list.allElements default: return [] } } /// All child elements from the currently indexed level public var children: [XMLIndexer] { return childElements.map { XMLIndexer($0) } } private var childElements: [XMLElement] { var list = [XMLElement]() for elem in all.compactMap({ $0.element }) { for elem in elem.xmlChildren { list.append(elem) } } return list } @available(*, unavailable, renamed: "filterChildren(_:)") public func filter(_ included: (_ elem: XMLElement, _ index: Int) -> Bool) -> XMLIndexer { return filterChildren(included) } public func filterChildren(_ included: (_ elem: XMLElement, _ index: Int) -> Bool) -> XMLIndexer { let children = handleFilteredResults(list: childElements, included: included) if let current = self.element { let filteredElem = XMLElement(name: current.name, index: current.index, options: current.options) filteredElem.children = children.allElements return .element(filteredElem) } return .xmlError(IndexingError.error) } public func filterAll(_ included: (_ elem: XMLElement, _ index: Int) -> Bool) -> XMLIndexer { return handleFilteredResults(list: allElements, included: included) } private func handleFilteredResults(list: [XMLElement], included: (_ elem: XMLElement, _ index: Int) -> Bool) -> XMLIndexer { let results = zip(list.indices, list).filter { included($1, $0) }.map { $1 } if results.count == 1 { return .element(results.first!) } return .list(results) } public var userInfo: [CodingUserInfoKey: Any] { switch self { case .element(let elem): return elem.userInfo default: return [:] } } /** Allows for element lookup by matching attribute values. - parameters: - attr: should the name of the attribute to match on - value: should be the value of the attribute to match on - throws: an XMLIndexer.XMLError if an element with the specified attribute isn't found - returns: instance of XMLIndexer */ public func withAttribute(_ attr: String, _ value: String) throws -> XMLIndexer { switch self { case .stream(let opStream): let match = opStream.findElements() return try match.withAttribute(attr, value) case .list(let list): if let elem = list.first(where: { value.compare($0.attribute(by: attr)?.text, $0.caseInsensitive) }) { return .element(elem) } throw IndexingError.attributeValue(attr: attr, value: value) case .element(let elem): if value.compare(elem.attribute(by: attr)?.text, elem.caseInsensitive) { return .element(elem) } throw IndexingError.attributeValue(attr: attr, value: value) default: throw IndexingError.attribute(attr: attr) } } /** Initializes the XMLIndexer - parameter _: should be an instance of XMLElement, but supports other values for error handling - throws: an Error if the object passed in isn't an XMLElement or LaxyXMLParser */ public init(_ rawObject: AnyObject) throws { switch rawObject { case let value as XMLElement: self = .element(value) case let value as LazyXMLParser: self = .stream(IndexOps(parser: value)) default: throw IndexingError.initialize(instance: rawObject) } } /** Initializes the XMLIndexer - parameter _: an instance of XMLElement */ public init(_ elem: XMLElement) { self = .element(elem) } init(_ stream: LazyXMLParser) { self = .stream(IndexOps(parser: stream)) } /** Find an XML element at the current level by element name - parameter key: The element name to index by - returns: instance of XMLIndexer to match the element (or elements) found by key - throws: Throws an XMLIndexingError.Key if no element was found */ public func byKey(_ key: String) throws -> XMLIndexer { switch self { case .stream(let opStream): let oper = IndexOp(key) opStream.ops.append(oper) return .stream(opStream) case .element(let elem): let match = elem.xmlChildren.filter({ $0.name.compare(key, $0.caseInsensitive) }) if !match.isEmpty { if match.count == 1 { return .element(match[0]) } else { return .list(match) } } throw IndexingError.key(key: key) default: throw IndexingError.key(key: key) } } /** Find an XML element at the current level by element name - parameter key: The element name to index by - returns: instance of XMLIndexer to match the element (or elements) found by */ public subscript(key: String) -> XMLIndexer { do { return try self.byKey(key) } catch let error as IndexingError { return .xmlError(error) } catch { return .xmlError(IndexingError.key(key: key)) } } /** Find an XML element by index within a list of XML Elements at the current level - parameter index: The 0-based index to index by - throws: XMLIndexer.XMLError if the index isn't found - returns: instance of XMLIndexer to match the element (or elements) found by index */ public func byIndex(_ index: Int) throws -> XMLIndexer { switch self { case .stream(let opStream): opStream.ops[opStream.ops.count - 1].index = index return .stream(opStream) case .list(let list): if index < list.count { return .element(list[index]) } return .xmlError(IndexingError.index(idx: index)) case .element(let elem): if index == 0 { return .element(elem) } return .xmlError(IndexingError.index(idx: index)) default: return .xmlError(IndexingError.index(idx: index)) } } /** Find an XML element by index - parameter index: The 0-based index to index by - returns: instance of XMLIndexer to match the element (or elements) found by index */ public subscript(index: Int) -> XMLIndexer { do { return try byIndex(index) } catch let error as IndexingError { return .xmlError(error) } catch { return .xmlError(IndexingError.index(idx: index)) } } } /// XMLIndexer extensions extension XMLIndexer: CustomStringConvertible { /// The XML representation of the XMLIndexer at the current level public var description: String { switch self { case .list(let list): return list.reduce("", { $0 + $1.description }) case .element(let elem): if elem.name == rootElementName { return elem.children.reduce("", { $0 + $1.description }) } return elem.description default: return "" } } } extension IndexingError: CustomStringConvertible { /// The description for the `IndexingError`. public var description: String { switch self { case .attribute(let attr): return "XML Attribute Error: Missing attribute [\"\(attr)\"]" case .attributeValue(let attr, let value): return "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]" case .key(let key): return "XML Element Error: Incorrect key [\"\(key)\"]" case .index(let index): return "XML Element Error: Incorrect index [\"\(index)\"]" case .initialize(let instance): return "XML Indexer Error: initialization with Object [\"\(instance)\"]" case .encoding: return "String Encoding Error" case .error: return "Unknown Error" } } } /// Models content for an XML doc, whether it is text or XML public protocol XMLContent: CustomStringConvertible { } /// Models a text element public class TextElement: XMLContent { /// The underlying text value public let text: String init(text: String) { self.text = text } } public struct XMLAttribute { public let name: String public let text: String init(name: String, text: String) { self.name = name self.text = text } } /// Models an XML element, including name, text and attributes public class XMLElement: XMLContent { /// The name of the element public let name: String /// Whether the element is case insensitive or not public var caseInsensitive: Bool { return options.caseInsensitive } var userInfo: [CodingUserInfoKey: Any] { return options.userInfo } /// All attributes public var allAttributes = [String: XMLAttribute]() /// Find an attribute by name public func attribute(by name: String) -> XMLAttribute? { if caseInsensitive { return allAttributes.first(where: { $0.key.compare(name, true) })?.value } return allAttributes[name] } /// The inner text of the element, if it exists public var text: String { return children.reduce("", { if let element = $1 as? TextElement { return $0 + element.text } return $0 }) } /// The inner text of the element and its children public var recursiveText: String { return children.reduce("", { if let textElement = $1 as? TextElement { return $0 + textElement.text } else if let xmlElement = $1 as? XMLElement { return $0 + xmlElement.recursiveText } else { return $0 } }) } public var innerXML: String { return children.reduce("", { return $0.description + $1.description }) } /// All child elements (text or XML) public var children = [XMLContent]() var count: Int = 0 var index: Int let options: SWXMLHashOptions var xmlChildren: [XMLElement] { return children.compactMap { $0 as? XMLElement } } /** Initialize an XMLElement instance - parameters: - name: The name of the element to be initialized - index: The index of the element to be initialized - options: The SWXMLHash options */ init(name: String, index: Int = 0, options: SWXMLHashOptions) { self.name = name self.index = index self.options = options } /** Adds a new XMLElement underneath this instance of XMLElement - parameters: - name: The name of the new element to be added - withAttributes: The attributes dictionary for the element being added - returns: The XMLElement that has now been added */ func addElement(_ name: String, withAttributes attributes: [String: String], caseInsensitive: Bool) -> XMLElement { let element = XMLElement(name: name, index: count, options: options) count += 1 children.append(element) for (key, value) in attributes { element.allAttributes[key] = XMLAttribute(name: key, text: value) } return element } func addText(_ text: String) { let elem = TextElement(text: text) children.append(elem) } } extension TextElement: CustomStringConvertible { /// The text value for a `TextElement` instance. public var description: String { return text } } extension XMLAttribute: CustomStringConvertible { /// The textual representation of an `XMLAttribute` instance. public var description: String { return "\(name)=\"\(text)\"" } } extension XMLElement: CustomStringConvertible { /// The tag, attributes and content for a `XMLElement` instance (<elem id="foo">content</elem>) public var description: String { let attributesString = allAttributes.reduce("", { $0 + " " + $1.1.description }) if !children.isEmpty { var xmlReturn = [String]() xmlReturn.append("<\(name)\(attributesString)>") for child in children { xmlReturn.append(child.description) } xmlReturn.append("</\(name)>") return xmlReturn.joined(separator: "") } return "<\(name)\(attributesString)>\(text)</\(name)>" } } // Workaround for "'XMLElement' is ambiguous for type lookup in this context" error on macOS. // // On macOS, `XMLElement` is defined in Foundation. // So, the code referencing `XMLElement` generates above error. // Following code allow to using `SWXMLhash.XMLElement` in client codes. extension SWXMLHash { public typealias XMLElement = SWXMLHashXMLElement } public typealias SWXMLHashXMLElement = XMLElement fileprivate extension String { func compare(_ str2: String?, _ insensitive: Bool) -> Bool { guard let str2 = str2 else { return false } let str1 = self if insensitive { return str1.caseInsensitiveCompare(str2) == .orderedSame } return str1 == str2 } }
mit
8775dce452fcdb8a29fa276b113701d6
30.662149
119
0.613233
4.893327
false
false
false
false
dreamsxin/swift
test/IDE/structure.swift
6
7664
// RUN: %swift-ide-test -structure -source-filename %s | FileCheck %s // CHECK: <class>class <name>MyCls</name> : <inherited><elem-typeref>OtherClass</elem-typeref></inherited> { // CHECK: <property>var <name>bar</name> : Int</property> // CHECK: <property>var <name>anotherBar</name> : Int = 42</property> // CHECK: <cvar>class var <name>cbar</name> : Int = 0</cvar> class MyCls : OtherClass { var bar : Int var anotherBar : Int = 42 class var cbar : Int = 0 // CHECK: <ifunc>func <name>foo(<param>_ arg1: Int</param>, <param><name>name</name>: String</param>, <param><name>param</name> par: String</param>)</name> { // CHECK: var abc // CHECK: <if>if <elem-condexpr>1</elem-condexpr> <brace>{ // CHECK: <call><name>foo</name>(<param>1</param>, <param><name>name</name>:"test"</param>, <param><name>param</name>:"test2"</param>)</call> // CHECK: }</brace> // CHECK: }</ifunc> func foo(_ arg1: Int, name: String, param par: String) { var abc if 1 { foo(1, name:"test", param:"test2") } } // CHECK: <ifunc><name>init (<param><name>x</name>: Int</param>)</name></ifunc> init (x: Int) // CHECK: <cfunc>class func <name>cfoo()</name></cfunc> class func cfoo() // CHECK: }</class> } // CHECK: <struct>struct <name>MyStruc</name> { // CHECK: <property>var <name>myVar</name>: Int</property> // CHECK: <svar>static var <name>sbar</name> : Int = 0</svar> // CHECK: <sfunc>static func <name>cfoo()</name></sfunc> // CHECK: }</struct> struct MyStruc { var myVar: Int static var sbar : Int = 0 static func cfoo() } // CHECK: <protocol>protocol <name>MyProt</name> { // CHECK: <ifunc>func <name>foo()</name></ifunc> // CHECK: }</protocol> protocol MyProt { func foo() } // CHECK: <extension>extension <name>MyStruc</name> { // CHECK: <ifunc>func <name>foo()</name> { // CHECK: }</ifunc> // CHECK: }</extension> extension MyStruc { func foo() { } } // CHECK: <gvar>var <name>gvar</name> : Int = 0</gvar> var gvar : Int = 0 // CHECK: <ffunc>func <name>ffoo()</name> {}</ffunc> func ffoo() {} // CHECK: <foreach>for <elem-id>i</elem-id> in <elem-expr>0...5</elem-expr> <brace>{}</brace></foreach> for i in 0...5 {} // CHECK: <for>for <elem-initexpr>var i = 0, i2 = 1</elem-initexpr>; <elem-expr>i == 0</elem-expr>; <elem-expr>++i</elem-expr> <brace>{}</brace></for> for var i = 0, i2 = 1; i == 0; ++i {} // CHECK: <for>for <elem-initexpr>var (i,i2) = (0,0), i3 = 1</elem-initexpr>; <elem-expr>i == 0</elem-expr>; <elem-expr>++i</elem-expr> <brace>{}</brace></for> for var (i,i2) = (0,0), i3 = 1; i == 0; ++i {} for i = 0; i == 0; ++i {} // CHECK: <while>while <elem-condexpr>var v = o, z = o where v > z</elem-condexpr> <brace>{}</brace></while> while var v = o, z = o where v > z {} // CHECK: <while>while <elem-condexpr>v == 0</elem-condexpr> <brace>{}</brace></while> while v == 0 {} // CHECK: <repeat-while>repeat <brace>{}</brace> while <elem-expr>v == 0</elem-expr></repeat-while> repeat {} while v == 0 // CHECK: <if>if <elem-condexpr>var v = o, z = o where v > z</elem-condexpr> <brace>{}</brace></if> if var v = o, z = o where v > z {} // CHECK: <switch>switch <elem-expr>v</elem-expr> { // CHECK: <case>case <elem-pattern>1</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2</elem-pattern>, <elem-pattern>3</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern><call><name>Foo</name>(<param>var x</param>, <param>var y</param>)</call> where x < y</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2 where <call><name>foo</name>()</call></elem-pattern>, <elem-pattern>3 where <call><name>bar</name>()</call></elem-pattern>: break;</case> // CHECK: <case><elem-pattern>default</elem-pattern>: break;</case> // CHECK: }</switch> switch v { case 1: break; case 2, 3: break; case Foo(var x, var y) where x < y: break; case 2 where foo(), 3 where bar(): break; default: break; } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>]</array></gvar> let myArray = [1, 2, 3] // CHECK: <gvar>let <name>myDict</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>:<elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>:<elem-expr>3</elem-expr>]</dictionary></gvar> let myDict = [1:1, 2:2, 3:3] // CHECK: <gvar>let <name>myArray2</name> = <array>[<elem-expr>1</elem-expr>]</array></gvar> let myArray2 = [1] // CHECK: <gvar>let <name>myDict2</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>]</dictionary></gvar> let myDict2 = [1:1] // CHECK: <for>for <brace><brace>{}</brace></brace></for> for {} // CHECK: <class>class <name><#MyCls#></name> : <inherited><elem-typeref><#OtherClass#></elem-typeref></inherited> {} class <#MyCls#> : <#OtherClass#> {} // CHECK: <ffunc>func <name><#test1#> ()</name> { // CHECK: <foreach>for <elem-id><#name#></elem-id> in <elem-expr><#items#></elem-expr> <brace>{}</brace></foreach> // CHECK: }</ffunc> func <#test1#> () { for <#name#> in <#items#> {} } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr><#item1#></elem-expr>, <elem-expr><#item2#></elem-expr>]</array></gvar> let myArray = [<#item1#>, <#item2#>] // CHECK: <ffunc>func <name>test1()</name> { // CHECK: <call><name>dispatch_async</name>(<param><call><name>dispatch_get_main_queue</name>()</call></param>, <param><brace>{}</brace></param>)</call> // CHECK: <call><name>dispatch_async</name>(<param><call><name>dispatch_get_main_queue</name>()</call></param>) <param><brace>{}</brace></param></call> // CHECK: }</ffunc> func test1() { dispatch_async(dispatch_get_main_queue(), {}) dispatch_async(dispatch_get_main_queue()) {} } // CHECK: <enum>enum <name>SomeEnum</name> { // CHECK: <enum-case>case <enum-elem><name>North</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>South</name></enum-elem>, <enum-elem><name>East</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>QRCode</name>(String)</enum-elem></enum-case> // CHECK: <enum-case>case</enum-case> // CHECK: }</enum> enum SomeEnum { case North case South, East case QRCode(String) case } // CHECK: <enum>enum <name>Rawness</name> : <inherited><elem-typeref>Int</elem-typeref></inherited> { // CHECK: <enum-case>case <enum-elem><name>One</name> = <elem-initexpr>1</elem-initexpr></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>Two</name> = <elem-initexpr>2</elem-initexpr></enum-elem>, <enum-elem><name>Three</name> = <elem-initexpr>3</elem-initexpr></enum-elem></enum-case> // CHECK: }</enum> enum Rawness : Int { case One = 1 case Two = 2, Three = 3 } // CHECK: <ffunc>func <name>rethrowFunc(<param>_ f: () throws -> ()</param>)</name> rethrows {}</ffunc> func rethrowFunc(_ f: () throws -> ()) rethrows {} class NestedPoundIf{ func foo1() { #if os(OSX) var a = 1 #if USE_METAL var b = 2 #if os(iOS) var c = 3 #else var c = 3 #endif #else var b = 2 #endif #else var a = 1 #endif } func foo2() {} func foo3() {} } // CHECK: <ifunc>func <name>foo2()</name> {}</ifunc> // CHECK: <ifunc>func <name>foo3()</name> {}</ifunc> class A { func foo(_ i : Int, animations: () -> ()) {} func perform() {foo(5, animations: {})} // CHECK: <ifunc>func <name>perform()</name> {<call><name>foo</name>(<param>5</param>, <param><name>animations</name>: <brace>{}</brace></param>)</call>}</ifunc> }
apache-2.0
d6bf7cf4c868aba788f6e226ea4e52d5
40.204301
227
0.595903
2.897543
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Drawing/DrawingViewModel.swift
1
635
// // DrawingViewModel.swift // Rocket.Chat // // Created by Artur Rymarz on 13.02.2018. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation struct DrawingViewModel { internal static let defaultBrushColor: UIColor = .black internal static let defaultBrushWidth: CGFloat = 10.0 internal static let defaultBrushOpacity: CGFloat = 1.0 internal let title = localized("chat.upload.draw") internal var errorTitle = localized("chat.drawing.errorTitle") internal var errorMessage = localized("chat.drawing.messageTitle") internal var fileName = localized("chat.drawing.fileName") }
mit
42c43169debf68cb8fabb061f1071e71
27.818182
70
0.735016
4.171053
false
false
false
false
jalehman/twitter-clone
TwitterClient/TwitterService.swift
1
7024
// // TwitterService.swift // TwitterClient // // Created by Josh Lehman on 2/19/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import Foundation class TwitterService: BDBOAuth1RequestOperationManager { // MARK: Properties let AUTH_URL_BASE = "https://api.twitter.com/oauth/authorize?oauth_token=" let twitterBaseURL = NSURL(string: "https://api.twitter.com") let twitterConsumerKey = "C30J8TCseNs9Pdz4q3FFHJSAn" let twitterConsumerSecret = "q4kXNeiOaaSPg2t0EmR3uhz50ylebz55JgHxgQ0uXZ1zOIKseN" var executeOpenURL: RACCommand! override init() { super.init(baseURL: twitterBaseURL, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret) executeOpenURL = RACCommand() { input -> RACSignal in let url = input as! NSURL return self.openURL(url) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: API func twitterLogin() -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.requestSerializer.removeAccessToken() self.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "cptwitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuthToken!) in let authURL = NSURL(string: "\(self.AUTH_URL_BASE)\(requestToken.token)") subscriber.sendNext(authURL) subscriber.sendCompleted() }, failure: { (error: NSError!) in subscriber.sendError(error) }) return nil } } func logout() -> RACSignal { User.currentUser = nil requestSerializer.removeAccessToken() return RACSignal.empty() } func fetchTimelineTweets(timelineType: String) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.GET("1.1/statuses/\(timelineType)_timeline.json", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let tweets = Tweet.tweetsWithArray(response as! [NSDictionary]) subscriber.sendNext(tweets) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println(error) subscriber.sendError(error) }) return nil } } func updateStatus(tweet: Tweet) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in var parameters = ["status": tweet.text!] if tweet.inReplyToStatusId != nil { parameters["in_reply_to_status_id"] = String(tweet.inReplyToStatusId!) } self.POST("1.1/statuses/update.json", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let tweet = Tweet(dictionary: response as! NSDictionary) subscriber.sendNext(tweet) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in subscriber.sendError(error) }) return nil } } func retweet(tweetId: Int) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.POST("1.1/statuses/retweet/\(tweetId).json", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let tweet = Tweet(dictionary: response as! NSDictionary) subscriber.sendNext(tweet) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in subscriber.sendError(error) }) return nil } } func favorite(tweetId: Int) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.POST("1.1/favorites/create.json", parameters: ["id": tweetId], success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let tweet = Tweet(dictionary: response as! NSDictionary) subscriber.sendNext(tweet) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in subscriber.sendError(error) }) return nil } } func userInfo(user: User) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.GET("1.1/users/lookup.json", parameters: ["user_id": user.userId], success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let array = response as! [NSDictionary] let profile = Profile(user: user, dictionary: array.first!) subscriber.sendNext(profile) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in subscriber.sendError(error) }) return nil } } // MARK: Private private func openURL(url: NSURL) -> RACSignal { return openURLSignal(url).flattenMap { _ -> RACStream in self.fetchUserSignal() } } private func openURLSignal(url: NSURL) -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuthToken(queryString: url.query), success: { (accessToken: BDBOAuthToken!) in let success = self.requestSerializer.saveAccessToken(accessToken) subscriber.sendNext(success) subscriber.sendCompleted() }, failure: { (error: NSError!) in subscriber.sendError(error) }) return nil } } private func fetchUserSignal() -> RACSignal { return RACSignal.createSignal { subscriber -> RACDisposable! in self.GET("1.1/account/verify_credentials.json", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in let user = User(dictionary: response as! NSDictionary) User.currentUser = user subscriber.sendNext(user) subscriber.sendCompleted() }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in subscriber.sendError(error) }) return nil } } }
gpl-2.0
3a768569a450f79a4e7cf8179dc3bf1a
38.466292
156
0.580438
5.183764
false
false
false
false
josve05a/wikipedia-ios
WikipediaUnitTests/Code/TalkPageLocalHandlerTests.swift
3
17910
import XCTest import CoreData @testable import Wikipedia class TalkPageLocalHandlerTests: XCTestCase { let urlString1 = "https://en.wikipedia.org/api/rest_v1/page/talk/Username1" let urlString2 = "https://en.wikipedia.org/api/rest_v1/page/talk/Username2" let urlString3 = "https://es.wikipedia.org/api/rest_v1/page/talk/Username1" var tempDataStore: MWKDataStore! var moc: NSManagedObjectContext! override func setUp() { super.setUp() tempDataStore = MWKDataStore.temporary() moc = tempDataStore.viewContext } override func tearDown() { tempDataStore.removeFolderAtBasePath() tempDataStore = nil super.tearDown() } func testCreateFirstTalkPageSavesToDatabase() { //confirm no talk pages in DB let fetchRequest: NSFetchRequest<TalkPage> = TalkPage.fetchRequest() guard let firstResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching initial talk pages") return } XCTAssertEqual(firstResults.count, 0, "Expected zero existing talk pages at first") //add network talk page guard let json = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.original.fileName, ofType: "json"), let talkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: json, revisionId: 1) else { XCTFail("Failure stubbing out network talk page") return } //create db talk page guard let dbTalkPage = moc.createTalkPage(with: talkPage) else { XCTFail("Failure to create db talk page") return } //assert db talk page values let keyedUrlString = URL(string: urlString1)?.wmf_databaseKey XCTAssertNotNil(dbTalkPage.key) XCTAssertEqual(dbTalkPage.key, keyedUrlString, "Unexpected key") XCTAssertEqual(dbTalkPage.revisionId, 1, "Unexpected revisionId") XCTAssertEqual(dbTalkPage.topics?.count, 6, "Unexpected topic count") let topics = dbTalkPage.topics?.allObjects.sorted{ ($0 as! TalkPageTopic).sort < ($1 as! TalkPageTopic).sort } if let introTopic = topics?[0] as? TalkPageTopic { XCTAssertEqual(introTopic.title, "", "Unexpected topic title") XCTAssertEqual(introTopic.replies?.count, 1, "Unexpected replies count") let replies = introTopic.replies?.allObjects.sorted{ ($0 as! TalkPageReply).sort < ($1 as! TalkPageReply).sort } if let firstReply = replies?[0] as? TalkPageReply { XCTAssertEqual(firstReply.text, "Hello! This is some introduction text on my talk page. L8erz, <a href='./User:TSevener_(WMF)' title='User:TSevener (WMF)'>TSevener (WMF)</a> (<a href='./User_talk:TSevener_(WMF)' title='User talk:TSevener (WMF)'>talk</a>) 20:48, 21 June 2019 (UTC)", "Unexpected replies html") } else { XCTFail("Unexpected first reply type") } } else { XCTFail("Unexpected intro topic type") } if let firstTopic = topics?[1] as? TalkPageTopic { XCTAssertEqual(firstTopic.title, "Let’s talk about talk pages", "Unexpected topic title") XCTAssertEqual(firstTopic.replies?.count, 3, "Unexpected topic items count") let replies = firstTopic.replies?.allObjects.sorted{ ($0 as! TalkPageReply).sort < ($1 as! TalkPageReply).sort } if let firstReply = replies?[0] as? TalkPageReply { XCTAssertEqual(firstReply.text, "Hello, I am testing a new topic from the <a href='./IOS' title='IOS'>iOS</a> app. It is fun. <a href='./Special:Contributions/47.184.10.84' title='Special:Contributions/47.184.10.84'>47.184.10.84</a> 20:50, 21 June 2019 (UTC)") XCTAssertEqual(firstReply.depth, 0, "Unexpected reply depth") } else { XCTFail("Unexpected first reply type") } if let secondReply = replies?[1] as? TalkPageReply { XCTAssertEqual(secondReply.text, "Hello back! This is a nested reply. <a href='./User:TSevener_(WMF)' title='User:TSevener (WMF)'>TSevener (WMF)</a> (<a href='./User_talk:TSevener_(WMF)' title='User talk:TSevener (WMF)'>talk</a>) 20:51, 21 June 2019 (UTC)") XCTAssertEqual(secondReply.depth, 1, "Unexpected reply depth") } else { XCTFail("Unexpected second reply type") } if let thirdReply = replies?[2] as? TalkPageReply { XCTAssertEqual(thirdReply.text, "Yes I see, I am nested as well. <a href='./Special:Contributions/47.184.10.84' title='Special:Contributions/47.184.10.84'>47.184.10.84</a> 20:52, 21 June 2019 (UTC)") XCTAssertEqual(thirdReply.depth, 2, "Unexpected reply depth") } else { XCTFail("Unexpected third reply type") } } else { XCTFail("Unexpected first topic type") } if let secondTopic = topics?[2] as? TalkPageTopic { XCTAssertEqual(secondTopic.title, "Subtopic time") XCTAssertEqual(secondTopic.replies?.count, 2, "Unexpected topic items count") } if let thirdTopic = topics?[3] as? TalkPageTopic { XCTAssertEqual(thirdTopic.title, "Sub sub topic") XCTAssertEqual(thirdTopic.replies?.count, 2, "Unexpected topic items count") } if let fourthTopic = topics?[4] as? TalkPageTopic { XCTAssertEqual(fourthTopic.title, "Topic <a href='./Part' title='Part'>Part</a> Deux") XCTAssertEqual(fourthTopic.replies?.count, 9, "Unexpected topic items count") } if let fifthTopic = topics?[5] as? TalkPageTopic { XCTAssertEqual(fifthTopic.title, "Topic <a href='./Part' title='Part'>Part</a> Trois") XCTAssertEqual(fifthTopic.replies?.count, 1, "Unexpected topic items count") } //confirm one talk page exists in DB guard let secondResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching saved talk pages") return } XCTAssertEqual(secondResults.count, 1, "Expected 1 talk page in DB") XCTAssertEqual(secondResults.first, dbTalkPage) } func testExistingTalkPagePullsFromDB() { //confirm no talk pages in DB let fetchRequest: NSFetchRequest<TalkPage> = TalkPage.fetchRequest() guard let firstResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching initial talk pages") return } XCTAssertEqual(firstResults.count, 0, "Expected zero existing talk pages at first") //add network talk page guard let json = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.original.fileName, ofType: "json"), let talkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: json, revisionId: 1) else { XCTFail("Failure stubbing out network talk page") return } //create db talk page guard let dbTalkPage = moc.createTalkPage(with: talkPage) else { XCTFail("Failure to create db talk page") return } //confirm asking for existing talk page with key pulls same talk page guard let existingTalkPage = try? moc.talkPage(for: URL(string: urlString1)!) else { XCTFail("Pull existing talk page fails") return } XCTAssertEqual(existingTalkPage, dbTalkPage, "Unexpected existing talk page value") //confirm asking for urlString2 pulls nothing do { let nonexistantTalkPage = try moc.talkPage(for: URL(string: urlString2)!) XCTAssertNil(nonexistantTalkPage) } catch { XCTFail("Pull existing talk page fails") } } func testUpdateExistingTalkPageUpdatesValues() { //confirm no talk pages in DB let fetchRequest: NSFetchRequest<TalkPage> = TalkPage.fetchRequest() guard let firstResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching initial talk pages") return } XCTAssertEqual(firstResults.count, 0, "Expected zero existing talk pages at first") //add network talk page guard let originalJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.original.fileName, ofType: "json"), let talkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: originalJson, revisionId: 1) else { XCTFail("Failure stubbing out network talk page") return } //create db talk page guard let dbTalkPage = moc.createTalkPage(with: talkPage) else { XCTFail("Failure to create db talk page") return } //mark last topic as read to confirm it stays read after updating. let topics = dbTalkPage.topics?.allObjects.sorted{ ($0 as! TalkPageTopic).sort < ($1 as! TalkPageTopic).sort } if let fifthTopic = topics?[5] as? TalkPageTopic { fifthTopic.content?.isRead = true do { try moc.save() } catch { XCTFail("Failure to save isRead flag") } } //get updated talk page payload guard let updatedJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.updated.fileName, ofType: "json"), let updatedTalkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: updatedJson, revisionId: 1) else { XCTFail("Failure stubbing out network talk page") return } //update local talk page with new talk page guard let updatedDbTalkPage = moc.updateTalkPage(dbTalkPage, with: updatedTalkPage) else { XCTFail("Failure updating existing local talk page") return } XCTAssertEqual(updatedDbTalkPage.topics?.count, 3, "Unexpected topic count") let updatedTopics = updatedDbTalkPage.topics?.allObjects.sorted{ ($0 as! TalkPageTopic).sort < ($1 as! TalkPageTopic).sort } if let introTopic = updatedTopics?[0] as? TalkPageTopic { XCTAssertEqual(introTopic.title, "", "Unexpected topic title") XCTAssertEqual(introTopic.replies?.count, 1, "Unexpected replies count") let replies = introTopic.replies?.allObjects.sorted{ ($0 as! TalkPageReply).sort < ($1 as! TalkPageReply).sort } if let firstReply = replies?[0] as? TalkPageReply { XCTAssertEqual(firstReply.text, "Hello! This is some introduction text on my talk page. L8erz, <a href='./User:TSevener_(WMF)' title='User:TSevener (WMF)'>TSevener (WMF)</a> (<a href='./User_talk:TSevener_(WMF)' title='User talk:TSevener (WMF)'>talk</a>) 20:48, 21 June 2019 (UTC)", "Unexpected replies html") } else { XCTFail("Unexpected first reply type") } } else { XCTFail("Unexpected intro topic type") } if let firstTopic = updatedTopics?[1] as? TalkPageTopic { XCTAssertEqual(firstTopic.title, "Topic <a href='./Part' title='Part'>Part</a> Deux", "Unexpected topic title") XCTAssertEqual(firstTopic.replies?.count, 11, "Unexpected topic items count") let replies = firstTopic.replies?.allObjects.sorted{ ($0 as! TalkPageReply).sort < ($1 as! TalkPageReply).sort } if let firstReply = replies?[0] as? TalkPageReply { XCTAssertEqual(firstReply.text, "Also injecting something in the front because why not. 🤷‍♀️ <a href='./User:TSevener_(WMF)' title='User:TSevener (WMF)'>TSevener (WMF)</a> (<a href='./User_talk:TSevener_(WMF)' title='User talk:TSevener (WMF)'>talk</a>) 21:17, 21 June 2019 (UTC)") XCTAssertEqual(firstReply.depth, 0, "Unexpected reply depth") } else { XCTFail("Unexpected first reply type") } if let secondReply = replies?[1] as? TalkPageReply { XCTAssertEqual(secondReply.text, "Ok try this on for size - can you put a link in a topic title from the iOS app? Only time will tell. <a href='./Special:Contributions/47.184.10.84' title='Special:Contributions/47.184.10.84'>47.184.10.84</a> 20:57, 21 June 2019 (UTC)") XCTAssertEqual(secondReply.depth, 0, "Unexpected reply depth") } else { XCTFail("Unexpected second reply type") } if let thirdReply = replies?[2] as? TalkPageReply { XCTAssertEqual(thirdReply.text, "It certainly seems so. It is good we tested this my friend. <a href='./User:TSevener_(WMF)' title='User:TSevener (WMF)'>TSevener (WMF)</a> (<a href='./User_talk:TSevener_(WMF)' title='User talk:TSevener (WMF)'>talk</a>) 20:58, 21 June 2019 (UTC)") XCTAssertEqual(thirdReply.depth, 1, "Unexpected reply depth") } else { XCTFail("Unexpected third reply type") } } else { XCTFail("Unexpected first topic type") } if let secondTopic = updatedTopics?[2] as? TalkPageTopic { XCTAssertEqual(secondTopic.title, "Topic <a href='./Part' title='Part'>Part</a> Trois") XCTAssertEqual(secondTopic.replies?.count, 1, "Unexpected topic items count") XCTAssertTrue(secondTopic.content?.isRead ?? false, "isRead flag flipped back to false after reorder.") } //confirm one talk page exists in DB guard let secondResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching saved talk pages") return } XCTAssertEqual(secondResults.count, 1, "Expected 1 talk page in DB") XCTAssertEqual(secondResults.first, dbTalkPage) } func testPerformanceLargeToLargeUpdateTalkPages() { //confirm no talk pages in DB let fetchRequest: NSFetchRequest<TalkPage> = TalkPage.fetchRequest() guard let firstResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching initial talk pages") return } XCTAssertEqual(firstResults.count, 0, "Expected zero existing talk pages at first") guard let largeJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.largeForPerformance.fileName, ofType: "json"), let largeUpdatedJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.largeUpdatedForPerformance.fileName, ofType: "json"), let networkTalkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: largeJson, revisionId: 1), let updatedNetworkTalkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: largeUpdatedJson, revisionId: 1) else { XCTFail("Failure stubbing out network talk pages") return } var i = 0 measure { i += 1 //create db talk page guard let talkPage = moc.createTalkPage(with: networkTalkPage) else { XCTFail("Failure to create db talk page") return } //update local copy guard let _ = moc.updateTalkPage(talkPage, with: updatedNetworkTalkPage) else { XCTFail("Failure updating existing local talk page") return } } } func testPerformanceSmallToLargeUpdateTalkPages() { //confirm no talk pages in DB let fetchRequest: NSFetchRequest<TalkPage> = TalkPage.fetchRequest() guard let firstResults = try? tempDataStore.viewContext.fetch(fetchRequest) else { XCTFail("Failure fetching initial talk pages") return } XCTAssertEqual(firstResults.count, 0, "Expected zero existing talk pages at first") guard let smallJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.smallForPerformance.fileName, ofType: "json"), let largeUpdatedJson = wmf_bundle().wmf_data(fromContentsOfFile: TalkPageTestHelpers.TalkPageJSONType.largeUpdatedForPerformance.fileName, ofType: "json"), let networkTalkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: smallJson, revisionId: 1), let updatedNetworkTalkPage = TalkPageTestHelpers.networkTalkPage(for: urlString1, data: largeUpdatedJson, revisionId: 1) else { XCTFail("Failure stubbing out network talk pages") return } var i = 0 measure { i += 1 //create db talk page guard let talkPage = moc.createTalkPage(with: networkTalkPage) else { XCTFail("Failure to create db talk page") return } //update local copy guard let _ = moc.updateTalkPage(talkPage, with: updatedNetworkTalkPage) else { XCTFail("Failure updating existing local talk page") return } } } }
mit
8faa7aafd26accdde2442e074ce03165
48.30854
326
0.616962
4.643061
false
true
false
false
ruslanskorb/CoreStore
Sources/Relationship.swift
1
68196
// // Relationship.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - DynamicObject extension DynamicObject where Self: CoreStoreObject { /** The containing type for relationships. `Relationship`s can be any `CoreStoreObject` subclass. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - Important: `Relationship` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public typealias Relationship = RelationshipContainer<Self> } // MARK: - RelationshipContainer /** The containing type for relationships. Use the `DynamicObject.Relationship` typealias instead for shorter syntax. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` */ public enum RelationshipContainer<O: CoreStoreObject> { // MARK: - ToOne /** The containing type for to-one relationships. Any `CoreStoreObject` subclass can be a destination type. Inverse relationships should be declared from the destination type as well, using the `inverse:` argument for the relationship. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - Important: `Relationship.ToOne` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class ToOne<D: CoreStoreObject>: RelationshipKeyPathStringConvertible, RelationshipProtocol { /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { nil }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToOne<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyOrdered<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyUnordered<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** The relationship value */ public var value: ReturnValueType { get { return self.nativeValue.flatMap(D.cs_fromRaw) } set { self.nativeValue = newValue?.rawObject } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = D // MARK: RelationshipKeyPathStringConvertible public typealias ReturnValueType = DestinationValueType? // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: RelationshipProtocol internal let isToMany = false internal let isOrdered = false internal let deleteRule: NSDeleteRule internal let minCount: Int = 0 internal let maxCount: Int = 1 internal let inverse: (type: CoreStoreObject.Type, keyPath: () -> KeyPathString?) internal let versionHashModifier: () -> String? internal let renamingIdentifier: () -> String? internal let affectedByKeyPaths: () -> Set<String> internal var rawObject: CoreStoreManagedObject? internal var nativeValue: NSManagedObject? { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return object.getValue( forKvcKey: self.keyPath, didGetValue: { $0 as! NSManagedObject? } ) } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) object.setValue( newValue, forKvcKey: self.keyPath ) } } } internal var valueForSnapshot: Any { return self.value?.objectID() as Any } // MARK: Private private init(keyPath: KeyPathString, inverseKeyPath: @escaping () -> KeyPathString?, deleteRule: DeleteRule, versionHashModifier: @autoclosure @escaping () -> String?, renamingIdentifier: @autoclosure @escaping () -> String?, affectedByKeyPaths: @autoclosure @escaping () -> Set<String>) { self.keyPath = keyPath self.deleteRule = deleteRule.nativeValue self.inverse = (D.self, inverseKeyPath) self.versionHashModifier = versionHashModifier self.renamingIdentifier = renamingIdentifier self.affectedByKeyPaths = affectedByKeyPaths } } // MARK: - ToManyOrdered /** The containing type for to-many ordered relationships. Any `CoreStoreObject` subclass can be a destination type. Inverse relationships should be declared from the destination type as well, using the `inverse:` argument for the relationship. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - Important: `Relationship.ToManyOrdered` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class ToManyOrdered<D: CoreStoreObject>: ToManyRelationshipKeyPathStringConvertible, RelationshipProtocol { /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, minCount: Int = 0, maxCount: Int = 0, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, minCount: minCount, maxCount: maxCount, inverseKeyPath: { nil }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, minCount: Int = 0, maxCount: Int = 0, inverse: @escaping (D) -> RelationshipContainer<D>.ToOne<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, minCount: minCount, maxCount: maxCount, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, minCount: Int = 0, maxCount: Int = 0, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyOrdered<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, minCount: minCount, maxCount: maxCount, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, minCount: Int = 0, maxCount: Int = 0, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyUnordered<O>, deleteRule: DeleteRule = .nullify, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, minCount: minCount, maxCount: maxCount, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** The relationship value */ public var value: ReturnValueType { get { return self.nativeValue.map({ D.cs_fromRaw(object: $0 as! NSManagedObject) }) } set { self.nativeValue = NSOrderedSet(array: newValue.map({ $0.rawObject! })) } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = D // MARK: RelationshipKeyPathStringConvertible public typealias ReturnValueType = [DestinationValueType] // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: RelationshipProtocol internal let isToMany = true internal let isOptional = true internal let isOrdered = true internal let deleteRule: NSDeleteRule internal let minCount: Int internal let maxCount: Int internal let inverse: (type: CoreStoreObject.Type, keyPath: () -> KeyPathString?) internal let versionHashModifier: () -> String? internal let renamingIdentifier: () -> String? internal let affectedByKeyPaths: () -> Set<String> internal var rawObject: CoreStoreManagedObject? internal var nativeValue: NSOrderedSet { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return object.getValue( forKvcKey: self.keyPath, didGetValue: { ($0 as! NSOrderedSet?) ?? [] } ) } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) object.setValue( newValue, forKvcKey: self.keyPath ) } } } internal var valueForSnapshot: Any { return self.value.map({ $0.objectID() }) as Any } // MARK: Private private init(keyPath: String, minCount: Int, maxCount: Int, inverseKeyPath: @escaping () -> String?, deleteRule: DeleteRule, versionHashModifier: @autoclosure @escaping () -> String?, renamingIdentifier: @autoclosure @escaping () -> String?, affectedByKeyPaths: @autoclosure @escaping () -> Set<String>) { self.keyPath = keyPath self.deleteRule = deleteRule.nativeValue self.inverse = (D.self, inverseKeyPath) self.versionHashModifier = versionHashModifier self.renamingIdentifier = renamingIdentifier let range = (Swift.max(0, minCount) ... maxCount) self.minCount = range.lowerBound self.maxCount = range.upperBound self.affectedByKeyPaths = affectedByKeyPaths } } // MARK: - ToManyUnordered /** The containing type for to-many unordered relationships. Any `CoreStoreObject` subclass can be a destination type. Inverse relationships should be declared from the destination type as well, using the `inverse:` argument for the relationship. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - Important: `Relationship.ToManyUnordered` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class ToManyUnordered<D: CoreStoreObject>: ToManyRelationshipKeyPathStringConvertible, RelationshipProtocol { /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { nil }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToOne<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyOrdered<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyUnordered<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** The relationship value */ public var value: ReturnValueType { get { return Set(self.nativeValue.map({ D.cs_fromRaw(object: $0 as! NSManagedObject) })) } set { self.nativeValue = NSSet(array: newValue.map({ $0.rawObject! })) } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = D // MARK: RelationshipKeyPathStringConvertible public typealias ReturnValueType = Set<DestinationValueType> // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: RelationshipProtocol internal let isToMany = true internal let isOptional = true internal let isOrdered = false internal let deleteRule: NSDeleteRule internal let minCount: Int internal let maxCount: Int internal let inverse: (type: CoreStoreObject.Type, keyPath: () -> KeyPathString?) internal let versionHashModifier: () -> String? internal let renamingIdentifier: () -> String? internal let affectedByKeyPaths: () -> Set<String> internal var rawObject: CoreStoreManagedObject? internal var nativeValue: NSSet { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return object.getValue( forKvcKey: self.keyPath, didGetValue: { ($0 as! NSSet?) ?? [] } ) } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) object.setValue( newValue, forKvcKey: self.keyPath ) } } } internal var valueForSnapshot: Any { return Set(self.value.map({ $0.objectID() })) as Any } // MARK: Private private init(keyPath: KeyPathString, inverseKeyPath: @escaping () -> KeyPathString?, deleteRule: DeleteRule, minCount: Int, maxCount: Int, versionHashModifier: @autoclosure @escaping () -> String?, renamingIdentifier: @autoclosure @escaping () -> String?, affectedByKeyPaths: @autoclosure @escaping () -> Set<String>) { self.keyPath = keyPath self.deleteRule = deleteRule.nativeValue self.inverse = (D.self, inverseKeyPath) self.versionHashModifier = versionHashModifier self.renamingIdentifier = renamingIdentifier let range = (Swift.max(0, minCount) ... maxCount) self.minCount = range.lowerBound self.maxCount = range.upperBound self.affectedByKeyPaths = affectedByKeyPaths } } // MARK: - DeleteRule public enum DeleteRule { case nullify case cascade case deny fileprivate var nativeValue: NSDeleteRule { switch self { case .nullify: return .nullifyDeleteRule case .cascade: return .cascadeDeleteRule case .deny: return .denyDeleteRule } } } } // MARK: - Convenience extension RelationshipContainer.ToManyOrdered: RandomAccessCollection { // MARK: Sequence public typealias Iterator = AnyIterator<D> public func makeIterator() -> Iterator { var iterator = self.nativeValue.makeIterator() return AnyIterator({ iterator.next().flatMap({ D.cs_fromRaw(object: $0 as! NSManagedObject) }) }) } // MARK: Collection public typealias Index = Int public var startIndex: Index { return 0 } public var endIndex: Index { return self.nativeValue.count } public subscript(position: Index) -> Iterator.Element { return D.cs_fromRaw(object: self.nativeValue[position] as! NSManagedObject) } public func index(after i: Index) -> Index { return i + 1 } } extension RelationshipContainer.ToManyUnordered: Sequence { /** The number of elements in the set. */ public var count: Int { return self.nativeValue.count } /** A Boolean value indicating whether the range contains no elements. */ public var isEmpty: Bool { return self.nativeValue.count == 0 } // MARK: Sequence public typealias Iterator = AnyIterator<D> public func makeIterator() -> Iterator { var iterator = self.nativeValue.makeIterator() return AnyIterator({ iterator.next().flatMap({ D.cs_fromRaw(object: $0 as! NSManagedObject) }) }) } } // MARK: - Operations infix operator .= : AssignmentPrecedence infix operator .== : ComparisonPrecedence extension RelationshipContainer.ToOne { /** Assigns an object to the relationship. The operation ``` dog.master .= person ``` is equivalent to ``` dog.master.value = person ``` */ public static func .= (_ relationship: RelationshipContainer<O>.ToOne<D>, _ newObject: D?) { relationship.nativeValue = newObject?.cs_toRaw() } /** Assigns an object from another relationship. The operation ``` dog.master .= anotherDog.master ``` is equivalent to ``` dog.master.value = anotherDog.master.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToOne<D>, _ relationship2: RelationshipContainer<O2>.ToOne<D>) { relationship.nativeValue = relationship2.nativeValue } /** Compares equality between a relationship's object and another object ``` if dog.master .== person { ... } ``` is equivalent to ``` if dog.master.value == person { ... } ``` */ public static func .== (_ relationship: RelationshipContainer<O>.ToOne<D>, _ object: D?) -> Bool { return relationship.nativeValue == object?.cs_toRaw() } /** Compares equality between an object and a relationship's object ``` if dog.master .== person { ... } ``` is equivalent to ``` if dog.master.value == person { ... } ``` */ public static func .== (_ object: D?, _ relationship: RelationshipContainer<O>.ToOne<D>) -> Bool { return object?.cs_toRaw() == relationship.nativeValue } /** Compares equality between a relationship's object and another relationship's object ``` if dog.master .== person { ... } ``` is equivalent to ``` if dog.master.value == person { ... } ``` */ public static func .== <O2>(_ relationship: RelationshipContainer<O>.ToOne<D>, _ relationship2: RelationshipContainer<O2>.ToOne<D>) -> Bool { return relationship.nativeValue == relationship2.nativeValue } } extension RelationshipContainer.ToManyOrdered { /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= [dog, cat] ``` is equivalent to ``` person.pets.value = [dog, cat] ``` */ public static func .= <S: Sequence>(_ relationship: RelationshipContainer<O>.ToManyOrdered<D>, _ newValue: S) where S.Iterator.Element == D { relationship.nativeValue = NSOrderedSet(array: newValue.map({ $0.rawObject! })) } /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= anotherPerson.pets ``` is equivalent to ``` person.pets.value = anotherPerson.pets.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToManyOrdered<D>, _ relationship2: RelationshipContainer<O2>.ToManyOrdered<D>) { relationship.nativeValue = relationship2.nativeValue } /** Compares equality between a relationship's objects and a collection of objects ``` if person.pets .== [dog, cat] { ... } ``` is equivalent to ``` if person.pets.value == [dog, cat] { ... } ``` */ public static func .== <C: Collection>(_ relationship: RelationshipContainer<O>.ToManyOrdered<D>, _ collection: C) -> Bool where C.Iterator.Element == D { return relationship.nativeValue.elementsEqual( collection.lazy.map({ $0.rawObject! }), by: { ($0 as! NSManagedObject) == $1 } ) } /** Compares equality between a collection of objects and a relationship's objects ``` if [dog, cat] .== person.pets { ... } ``` is equivalent to ``` if [dog, cat] == person.pets.value { ... } ``` */ public static func .== <C: Collection>(_ collection: C, _ relationship: RelationshipContainer<O>.ToManyOrdered<D>) -> Bool where C.Iterator.Element == D { return relationship.nativeValue.elementsEqual( collection.lazy.map({ $0.rawObject! }), by: { ($0 as! NSManagedObject) == $1 } ) } /** Compares equality between a relationship's objects and a collection of objects ``` if person.pets .== anotherPerson.pets { ... } ``` is equivalent to ``` if person.pets.value == anotherPerson.pets.value { ... } ``` */ public static func .== <O2>(_ relationship: RelationshipContainer<O>.ToManyOrdered<D>, _ relationship2: RelationshipContainer<O2>.ToManyOrdered<D>) -> Bool { return relationship.nativeValue == relationship2.nativeValue } } extension RelationshipContainer.ToManyUnordered { /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= [dog, cat] ``` is equivalent to ``` person.pets.value = [dog, cat] ``` */ public static func .= <S: Sequence>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ newValue: S) where S.Iterator.Element == D { relationship.nativeValue = NSSet(array: newValue.map({ $0.rawObject! })) } /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= anotherPerson.pets ``` is equivalent to ``` person.pets.value = anotherPerson.pets.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyUnordered<D>) { relationship.nativeValue = relationship2.nativeValue } /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= anotherPerson.pets ``` is equivalent to ``` person.pets.value = anotherPerson.pets.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyOrdered<D>) { relationship.nativeValue = NSSet(set: relationship2.nativeValue.set) } /** Compares the if the relationship's objects and a set of objects have the same elements. ``` if person.pets .== Set<Animal>([dog, cat]) { ... } ``` is equivalent to ``` if person.pets.value == Set<Animal>([dog, cat]) { ... } ``` */ public static func .== (_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ set: Set<D>) -> Bool { return relationship.nativeValue.isEqual(to: Set(set.map({ $0.rawObject! }))) } /** Compares if a set of objects and a relationship's objects have the same elements. ``` if Set<Animal>([dog, cat]) .== person.pets { ... } ``` is equivalent to ``` if Set<Animal>([dog, cat]) == person.pets.value { ... } ``` */ public static func .== (_ set: Set<D>, _ relationship: RelationshipContainer<O>.ToManyUnordered<D>) -> Bool { return relationship.nativeValue.isEqual(to: Set(set.map({ $0.rawObject! }))) } /** Compares if a relationship's objects and another relationship's objects have the same elements. ``` if person.pets .== anotherPerson.pets { ... } ``` is equivalent to ``` if person.pets.value == anotherPerson.pets.value { ... } ``` */ public static func .== <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyUnordered<D>) -> Bool { return relationship.nativeValue.isEqual(relationship2.nativeValue) } }
mit
b0e16d1dc1ef9e56cc7c7ce0c35fd7b0
51.987568
413
0.643434
5.34695
false
false
false
false
OMTS/Lounge
Pod/Classes/LoungeViewController.swift
1
23118
// // LoungeViewController.swift // Pods // // Created by Eddy Claessens on 19/01/16. // // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } open class LoungeViewController: UIViewController { // MARK: - Properties //data weak open var dataSource: LoungeDataSource? = nil weak open var delegate: LoungeDelegate? = nil var messageArray : [LoungeMessageProtocol] = [LoungeMessageProtocol]() { didSet { if let emptyStateView = emptyStateView { if oldValue.count == 0 && messageArray.count > 0 { // hide empty state tableView.alpha = 0 tableView.isHidden = false UIView.animate(withDuration: 0.2, animations: { () -> Void in emptyStateView.alpha = 0 self.tableView.alpha = 1 }, completion: { (terminated) -> Void in emptyStateView.isHidden = true emptyStateView.alpha = 1 }) } else if oldValue.count > 0 && messageArray.count == 0 { // display empty state emptyStateView.alpha = 0 emptyStateView.isHidden = false UIView.animate(withDuration: 0.2, animations: { () -> Void in emptyStateView.alpha = 1 self.tableView.alpha = 0 }, completion: { (terminated) -> Void in self.tableView.isHidden = true self.tableView.alpha = 1 }) } } } } var hasMoreToLoad = false var maxLoadedMessages = 20 var tmpId = -1 override open var inputAccessoryView: UIView? { get { return inputMessageView } } /// This let you manage the send button status (e.g.: when network connection is lost) open var sendButtonEnabled: Bool = true { didSet { if let sendButton = sendButton { sendButton.isEnabled = textView.text.characters.count > 0 && sendButtonEnabled } } } //views @IBOutlet weak var topView: UIView? @IBOutlet weak var emptyStateView: UIView? @IBOutlet weak open var tableView: UITableView! @IBOutlet weak var inputMessageView: LoungeInputView! @IBOutlet weak var leftInputView: UIView? @IBOutlet weak var textView: UITextView! @IBOutlet weak var sendButton: UIButton! let separator: UIView = UIView() var placeholderLabel: UILabel? //constraints @IBOutlet weak var topViewHeightConstraint: NSLayoutConstraint? var textViewTopPadding: NSLayoutConstraint? var textViewBottomPadding: NSLayoutConstraint? var textViewLeftPadding: NSLayoutConstraint? var textViewRightPadding: NSLayoutConstraint? var textviewHeightConstraint: NSLayoutConstraint? var buttonTopPadding: NSLayoutConstraint? var buttonBottomPadding: NSLayoutConstraint? var buttonRightPadding: NSLayoutConstraint? var emptyStateBottomConstraint: NSLayoutConstraint? // MARK: - lifeCycle methods override open func viewDidLoad() { super.viewDidLoad() tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.interactive tableView.delegate = self tableView.dataSource = self if let emptyStateView = emptyStateView { tableView.isHidden = true emptyStateView.isHidden = false } sendButton.isEnabled = false textView.delegate = self sendButton.addTarget(self, action: "sendClicked", for: .touchUpInside) if self.canBecomeFirstResponder { self.becomeFirstResponder() } self.setConstraints() self.getLastMessages() } func getLastMessages() { dataSource!.getLastMessages(maxLoadedMessages) { messages in if let messages = messages { self.messageArray = messages self.updateIdOfLastMessageReceived() if messages.count == self.maxLoadedMessages { self.hasMoreToLoad = true } self.tableView.reloadData() self.scrollToLastCell(false) } else // error or no internet what do we do ? { let delayInSeconds = 1.0 let time = DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.getLastMessages() // we call it again } } } } override open var canBecomeFirstResponder : Bool { return true } func setConstraints() { // We need to keep the layout guide constraints so we don't delete all constraints but only those concerned by the selected views. var constraintsToRemove : [NSLayoutConstraint] = [] var viewWeNeedToRemoveConstraints : [UIView] = [tableView, inputMessageView] if let topView = topView { viewWeNeedToRemoveConstraints.append(topView) } for constraint in self.view.constraints { if let firstItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? UIView { if viewWeNeedToRemoveConstraints.contains(firstItem) || viewWeNeedToRemoveConstraints.contains(secondItem) { constraintsToRemove.append(constraint) } } } self.view.removeConstraints(constraintsToRemove) // pin topView if let viewTop = topView { self.view.pinSubview(viewTop, on: .leading) self.view.setSpace(on: .top, ofView: viewTop, fromView: self.topLayoutGuide) self.view.pinSubview(viewTop, on: .trailing) self.view.setSpace(space: 0, on: .bottom, ofView: viewTop, fromView: tableView) } else { self.view.setSpace(on: .top, ofView: self.tableView, fromView: self.topLayoutGuide) // self.view.pinSubview(tableView, on: .Top) } // pin tableView self.view.pinSubview(tableView, on: .leading) self.view.pinSubview(tableView, on: .trailing) self.view.pinSubview(tableView, on: .bottom) // input message view inputMessageView.removeFromSuperview() inputMessageView.removeConstraints(inputMessageView.constraints) // separator separator.translatesAutoresizingMaskIntoConstraints = false separator.backgroundColor = UIColor.clear inputMessageView.addSubview(separator) inputMessageView.pinSubview(separator, on: .top) inputMessageView.pinSubview(separator, on: .leading) inputMessageView.pinSubview(separator, on: .trailing) separator.set(.height, size: 0.5) // send button buttonRightPadding = inputMessageView.pinSubview(sendButton, on: .trailing, space : 15) buttonTopPadding = inputMessageView.pinSubview(sendButton, on: .top, relation: .greaterThanOrEqual, space: 5) buttonBottomPadding = inputMessageView.pinSubview(sendButton, on: .bottom, space : 5) if sendButton.constraints.count == 0 { sendButton.set(.height, size: 35) } // left input View if let leftViewMessage = leftInputView { inputMessageView.pinSubview(leftViewMessage, on: .leading, space : 5) inputMessageView.pinSubview(leftViewMessage, on: .top, relation: .greaterThanOrEqual, space : 5) inputMessageView.pinSubview(leftViewMessage, on: .bottom, space : 5) inputMessageView.setSpace(space: 5, on: .trailing, ofView: leftViewMessage, fromView: textView) } else { textViewLeftPadding = inputMessageView.pinSubview(textView, on: .leading, space: 15) } // textView textViewTopPadding = inputMessageView.pinSubview(textView, on: .top, space : 5) textViewBottomPadding = inputMessageView.pinSubview(textView, on: .bottom, space : 5) textViewRightPadding = inputMessageView.setSpace(space: 15, on: .leading, ofView: sendButton, fromView: textView) textviewHeightConstraint = textView.set(.height, size: 35) textviewHeightConstraint?.priority = 999 // empty state view if let emptyStateView = emptyStateView { self.view.align(emptyStateView, andTheView: tableView, on: .top) emptyStateBottomConstraint = self.view.align(emptyStateView, andTheView: tableView, on: .bottom) self.view.align(emptyStateView, andTheView: tableView, on: .right) self.view.align(emptyStateView, andTheView: tableView, on: .left) } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: "keyboardWillShow:", name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: "keyboardWillHide:", name: NSNotification.Name.UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: "keyboardDidHide:", name: NSNotification.Name.UIKeyboardDidHide, object: nil) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } func keyboardWillShow(_ notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let height = keyboardSize.height - (tabBarController?.tabBar.bounds.size.height ?? 0) tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0) emptyStateBottomConstraint?.constant = -height self.view.layoutIfNeeded() if height > inputMessageView.frame.size.height { self.scrollToLastCell() delegate?.keyBoardStateChanged(displayed: true) } else { delegate?.keyBoardStateChanged(displayed: false) } } } func keyboardWillHide(_ notification: Notification) { tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) self.view.layoutIfNeeded() } func keyboardDidHide(_ notification: Notification) { self.becomeFirstResponder() } func scrollToLastCell(_ animated: Bool = true) { if tableView.numberOfRows(inSection: 0) > 0 { let lastIndexPath = IndexPath(row: tableView.numberOfRows(inSection: 0) - 1, section: 0) tableView.scrollToRow(at: lastIndexPath, at: .bottom, animated: animated) } } func updateIdOfLastMessageReceived() { var idMessage : Int? = nil var i = messageArray.count - 1 while idMessage == nil && i >= 0 { idMessage = messageArray[i].id if idMessage < 0 { idMessage = nil } i -= 1 } dataSource?.idOfLastMessageReceived = idMessage } // MARK: - Internal Action methods open func sendClicked() { let message = dataSource!.messageFromText(textView.text) newMessage(message) } // MARK: - Methods for subclasses // MARK: Customization open func setTopViewHeight(_ height: CGFloat) { topViewHeightConstraint?.constant = height self.view.layoutIfNeeded() } open func setPlaceholder(_ text: String, color: UIColor = UIColor.lightGray) { if (placeholderLabel == nil) { self.placeholderLabel = UILabel() inputMessageView.addSubview(placeholderLabel!) placeholderLabel!.textColor = color placeholderLabel!.translatesAutoresizingMaskIntoConstraints = false placeholderLabel?.font = textView.font inputMessageView.align(placeholderLabel!, andTheView: textView, on: .top, space: textView.contentInset.top) inputMessageView.align(placeholderLabel!, andTheView: textView, on: .bottom, space: textView.contentInset.bottom) inputMessageView.align(placeholderLabel!, andTheView: textView, on: .leading, space: 5) } placeholderLabel!.text = text } open func setSeparatorColor(_ color: UIColor) { separator.backgroundColor = color } open func setPadding(_ verticalPadding: CGFloat, horizontalPadding: CGFloat) { textViewTopPadding?.constant = verticalPadding textViewBottomPadding?.constant = verticalPadding textViewLeftPadding?.constant = horizontalPadding textViewRightPadding?.constant = horizontalPadding buttonTopPadding?.constant = verticalPadding buttonBottomPadding?.constant = verticalPadding buttonRightPadding?.constant = horizontalPadding self.view.layoutIfNeeded() } //MARK: Methods you may call public func newMessage(_ newMessage: LoungeMessageProtocol) // call this when you want to send custom message (e.g. : picture), it's called automatically when send button is clicked { var newMessage = newMessage newMessage.id = tmpId newMessage.fromMe = true tmpId -= 1 dataSource!.sendNewMessage(newMessage) messageArray.append(newMessage) self.tableView.insertRows(at: [IndexPath(row: self.messageArray.count - 1 + (self.hasMoreToLoad ? 1 : 0), section: 0)], with: .bottom) textView.text = "" if let placeholderLB = placeholderLabel { placeholderLB.isHidden = false } sendButton.isEnabled = false textviewHeightConstraint?.constant = 35 self.inputAccessoryView?.layoutIfNeeded() self.reloadInputViews() self.scrollToLastCell() } //MARK: Methods you have to call // call this method when you did receive messages (this will be typically called by the dataSource) open func newMessagesReceived(_ messages: [LoungeMessageProtocol]) { guard messages.count > 0 else { return } let otherUserMessages : [LoungeMessageProtocol] = messages.filter({ message in return message.fromMe == false }) var newIndexPaths : [IndexPath] = [] for message in otherUserMessages { self.messageArray.append(message) newIndexPaths.append(IndexPath(row: self.messageArray.count - 1 + (self.hasMoreToLoad ? 1 : 0), section: 0)) } updateIdOfLastMessageReceived() if newIndexPaths.count > 0 { self.tableView.insertRows(at: newIndexPaths, with: .bottom) self.scrollToLastCell(true) } } } // MARK: - Delegates Methods extension LoungeViewController: UITextViewDelegate { public func textViewDidChange(_ textView: UITextView) { if textView.text.characters.count > 0 { if let placeholderLB = placeholderLabel { placeholderLB.isHidden = true } sendButton.isEnabled = sendButtonEnabled } else { if let placeholderLB = placeholderLabel { placeholderLB.isHidden = false } sendButton.isEnabled = false } if textView.contentSize.height > 120 { textviewHeightConstraint?.constant = 120 } else if textView.contentSize.height < 35 { textviewHeightConstraint?.constant = 35 } else { textviewHeightConstraint?.constant = textView.contentSize.height textView.layoutIfNeeded() textView.scrollRangeToVisible(NSMakeRange(0, 0)) } self.reloadInputViews() } } extension LoungeViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArray.count + (hasMoreToLoad ? 1 : 0) } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if hasMoreToLoad && indexPath.row == 0 { return delegate!.cellForLoadMore(indexPath) } let currentIndex = indexPath.row - (hasMoreToLoad ? 1 : 0) let message = messageArray[currentIndex] return delegate!.cellForMessage(message, indexPath: indexPath, width: tableView.frame.size.width) } } extension LoungeViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return self.tableView(tableView, heightForRowAt: indexPath) } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if hasMoreToLoad && indexPath.row == 0 { return tableView.rowHeight } let currentIndex = indexPath.row - (hasMoreToLoad ? 1 : 0) return delegate!.cellHeightForMessage(messageArray[currentIndex], width: tableView.frame.size.width) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { checkToLoadMore() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate == false { checkToLoadMore() } } func checkToLoadMore() { if hasMoreToLoad && tableView.contentOffset.y == 0 { dataSource!.getOldMessages(maxLoadedMessages, beforeMessage: messageArray.first!, completion: { messages in var indexPaths : [IndexPath] = [] for (index, message) in messages.enumerated() { self.messageArray.insert(message, at: 0) indexPaths.append(IndexPath(row: index + 1, section: 0)) } let yOfLastCell = self.tableView.rectForRow(at: IndexPath(row: 1, section: 0)).origin.y if indexPaths.count > 0 { UIView.setAnimationsEnabled(false) self.tableView.beginUpdates() self.tableView.insertRows(at: indexPaths, with: .none) self.tableView.endUpdates() UIView.setAnimationsEnabled(true) let newY = self.tableView.rectForRow(at: IndexPath(row: messages.count + 1, section: 0)).origin.y - yOfLastCell self.tableView.setContentOffset(CGPoint(x: 0, y: newY), animated: false) } if (messages.count < self.maxLoadedMessages) { self.hasMoreToLoad = false self.tableView.beginUpdates() self.tableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .none) self.tableView.endUpdates() } }) } } } extension UIView { func pinSubview(_ subview: UIView, on: NSLayoutAttribute, relation: NSLayoutRelation = .equal, space : CGFloat = 0) -> NSLayoutConstraint { let constraint : NSLayoutConstraint = NSLayoutConstraint(item: (on == .top || on == .leading ? subview : self), attribute: on, relatedBy: relation, toItem: (on == .top || on == .leading ? self : subview), attribute: on, multiplier: 1, constant: space) self.addConstraint(constraint) return constraint } // func pinOnTopLayoutGuide(subview: UIView, on: NSLayoutAttribute, viewController: UIViewController, space : CGFloat = 0) -> NSLayoutConstraint { // let constraint : NSLayoutConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: viewController.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: space) // // self.addConstraint(constraint) // // return constraint // } func setSpace(_ relation: NSLayoutRelation = .equal, space: CGFloat = 0, on: NSLayoutAttribute, ofView: UIView, fromView: AnyObject) -> NSLayoutConstraint { let oppositeSide: NSLayoutAttribute switch on { case .top: oppositeSide = .bottom case .bottom: oppositeSide = .top case .leading: oppositeSide = .trailing case .trailing: oppositeSide = .leading default: oppositeSide = on } let constraint : NSLayoutConstraint = NSLayoutConstraint(item: (on == .top || on == .leading ? ofView : fromView), attribute: (on == .top || on == .leading ? on : oppositeSide), relatedBy: relation, toItem: (on == .top || on == .leading ? fromView : ofView), attribute: (on == .top || on == .leading ? oppositeSide : on), multiplier: 1, constant: space) self.addConstraint(constraint) return constraint } func align(_ theView: UIView, andTheView: UIView, relation: NSLayoutRelation = .equal, on: NSLayoutAttribute, space: CGFloat = 0) -> NSLayoutConstraint { let constraint : NSLayoutConstraint = NSLayoutConstraint(item: theView, attribute: on, relatedBy: relation, toItem: andTheView, attribute: on, multiplier: 1, constant: space) self.addConstraint(constraint) return constraint } func set(_ widthOrHeight: NSLayoutAttribute, relation: NSLayoutRelation = .equal, size: CGFloat = 0) -> NSLayoutConstraint { let constraint : NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: widthOrHeight, relatedBy: relation, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size) self.addConstraint(constraint) return constraint } }
mit
812cccfda380832cfb25c9a6f212dc32
37.21157
262
0.610433
5.29622
false
false
false
false
FuzzyHobbit/bitcoin-swift
BitcoinSwift/PartialMerkleTree.swift
1
7133
// // PartialMerkleTree.swift // BitcoinSwift // // Created by Kevin Greene on 6/16/15. // Copyright (c) 2015 DoubleSha. All rights reserved. // import Foundation public func ==(left: PartialMerkleTree, right: PartialMerkleTree) -> Bool { return left.totalLeafNodes == right.totalLeafNodes && left.hashes == right.hashes && left.flags == right.flags && left.rootHash == right.rootHash && left.matchingHashes == right.matchingHashes } public struct PartialMerkleTree { /// The number of leaf nodes that would be present if this were a full merkle tree. public let totalLeafNodes: UInt32 /// The hashes used to build the partial merkle tree, in depth-first order. public let hashes: [SHA256Hash] /// Flag bits used to build the partial merkle tree, packed per 8 in a byte, least significant /// bit first. public let flags: [UInt8] /// The merkle root hash is calculated by building the merkle tree from the hashes and flags. public let rootHash: SHA256Hash /// The list of leaf hashes that were marked as matching the filter. public let matchingHashes: [SHA256Hash] /// Returns nil if a partial public init?(totalLeafNodes: UInt32, hashes: [SHA256Hash], flags: [UInt8]) { self.totalLeafNodes = totalLeafNodes self.hashes = hashes self.flags = flags let height = PartialMerkleTree.treeHeightWithtotalLeafNodes(totalLeafNodes) var matchingHashes: [SHA256Hash] = [] var flagBitIndex = 0 var hashIndex = 0 if let merkleRoot = PartialMerkleTree.merkleTreeNodeWithHeight(height, hashes: hashes, flags: flags, matchingHashes: &matchingHashes, flagBitIndex: &flagBitIndex, hashIndex: &hashIndex) { self.rootHash = merkleRoot.hash self.matchingHashes = matchingHashes // Fail if there are any unused hashes. if hashIndex < hashes.count { return nil } // Fail if there are unused flag bits, except for the minimum number of bits necessary to // pad up to the next full byte. if (flagBitIndex / 8 != flags.count - 1) && (flagBitIndex != flags.count * 8) { return nil } // Fail if there are any non-zero bits in the padding section. while flagBitIndex < flags.count * 8 { let flag = PartialMerkleTree.flagBitAtIndex(flagBitIndex++, flags: flags) if flag == 1 { return nil } } } else { self.rootHash = SHA256Hash() self.matchingHashes = [] return nil } } // MARK: - Private Methods private static func treeHeightWithtotalLeafNodes(totalLeafNodes: UInt32) -> Int { return Int(ceil(log2(Double(totalLeafNodes)))) } private static func merkleTreeNodeWithHeight(height: Int, hashes: [SHA256Hash], flags: [UInt8], inout matchingHashes: [SHA256Hash], inout flagBitIndex: Int, inout hashIndex: Int) -> MerkleTreeNode? { if hashIndex >= hashes.count { // We have run out of hashes without successfully building the tree. return nil } if flagBitIndex >= flags.count * 8 { // We have run out of flags without sucessfully building the tree. return nil } let flag = flagBitAtIndex(flagBitIndex++, flags: flags) let nodeHash: SHA256Hash var leftNode: MerkleTreeNode! = nil var rightNode: MerkleTreeNode! = nil if height == 0 { // This is a leaf node. nodeHash = hashes[hashIndex++] if flag == 1 { matchingHashes.append(nodeHash) } } else { // This is not a leaf node. if flag == 0 { nodeHash = hashes[hashIndex++] } else { leftNode = merkleTreeNodeWithHeight(height - 1, hashes: hashes, flags: flags, matchingHashes: &matchingHashes, flagBitIndex: &flagBitIndex, hashIndex: &hashIndex) rightNode = merkleTreeNodeWithHeight(height - 1, hashes: hashes, flags: flags, matchingHashes: &matchingHashes, flagBitIndex: &flagBitIndex, hashIndex: &hashIndex) if leftNode == nil || rightNode == nil { return nil } let hashData = NSMutableData() hashData.appendData(leftNode.hash.data.reversedData) hashData.appendData(rightNode.hash.data.reversedData) nodeHash = SHA256Hash(data: hashData.SHA256Hash().SHA256Hash().reversedData) } } return MerkleTreeNode(hash: nodeHash, left: leftNode, right: rightNode) } private static func flagBitAtIndex(index: Int, flags: [UInt8]) -> UInt8 { precondition(index < flags.count * 8) let flagByte = flags[flags.count - Int(index / 8) - 1] return (flagByte >> UInt8(index % 8)) & 1 } } extension PartialMerkleTree: BitcoinSerializable { public var bitcoinData: NSData { var data = NSMutableData() data.appendUInt32(totalLeafNodes) data.appendVarInt(hashes.count) for hash in hashes { data.appendData(hash.bitcoinData) } data.appendVarInt(flags.count) for flag in flags { data.appendUInt8(flag) } return data } public static func fromBitcoinStream(stream: NSInputStream) -> PartialMerkleTree? { let totalLeafNodes = stream.readUInt32() if totalLeafNodes == nil { Logger.warn("Failed to parse totalLeafNodes from PartialMerkleTree") return nil } let hashesCount = stream.readVarInt() if hashesCount == nil { Logger.warn("Failed to parse hashesCount from PartialMerkleTree") return nil } var hashes: [SHA256Hash] = [] for i in 0..<hashesCount! { let hash = SHA256Hash.fromBitcoinStream(stream) if hash == nil { Logger.warn("Failed to parse hash \(i) from PartialMerkleTree") return nil } hashes.append(hash!) } let flagBytesCount = stream.readVarInt() if flagBytesCount == nil { Logger.warn("Failed to parse flagBytesCount from PartialMerkleTree") return nil } var flags: [UInt8] = [] for i in 0..<flagBytesCount! { let flagByte = stream.readUInt8() if flagByte == nil { Logger.warn("Failed to parse flagByte \(i) from PartialMerkleTree") return nil } flags.append(flagByte!) } return PartialMerkleTree(totalLeafNodes: totalLeafNodes!, hashes: hashes, flags: flags) } }
apache-2.0
b3902e2fa34942185a6806b864b35f03
36.151042
96
0.581242
4.506001
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaLinkItemFactory.swift
1
946
import Foundation extension MVitaLink { private static let kLookItemPredicate:String = "identifier == \"%@\"" private static let kLookIdentifierSorter:String = "created" //MARK: internal class func factoryPredicateFor( itemStatus:MVitaItemStatus) -> NSPredicate { let identifier:String = String( describing:itemStatus.identifier) let predicateString:String = String( format:MVitaLink.kLookItemPredicate, identifier) let predicate:NSPredicate = NSPredicate( format:predicateString) return predicate } class func factorySortersForIdentifier() -> [NSSortDescriptor] { let sorter:NSSortDescriptor = NSSortDescriptor( key:MVitaLink.kLookIdentifierSorter, ascending:true) let sorters:[NSSortDescriptor] = [ sorter] return sorters } }
mit
41f9e0c1c64077689ed7465468d9c0c8
26.823529
73
0.625793
5.284916
false
true
false
false
jakepolatty/HighSchoolScienceBowlPractice
High School Science Bowl Practice/QuestionJSONParser.swift
1
4433
// // QuestionJSONParser.swift // High School Science Bowl Practice // // Created by Jake Polatty on 7/11/17. // Copyright © 2017 Jake Polatty. All rights reserved. // import GameKit import Foundation struct QuestionJSONParser { let parsedQuestions = { QuestionJSONParser.parseJSONToQuestions() }() static let shared = QuestionJSONParser() static func parseJsonFile(withName name: String) -> [[String: Any]] { let file = Bundle.main.path(forResource: name, ofType: "json") let data = try! Data.init(contentsOf: URL(fileURLWithPath: file!)) let jsonData = try! JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] return jsonData } static func parseJSONToQuestions() -> [Question] { var questionArray = [Question]() let parsedJSON = QuestionJSONParser.parseJsonFile(withName: "questions") for questionJSON in parsedJSON { if let parsedQuestion = Question(json: questionJSON) { questionArray.append(parsedQuestion) } } return questionArray } func parseQuestionForIndex(_ index: Int) -> Question { return parsedQuestions[index] } func getRandomQuestion() -> Question { let randomIndex = GKRandomSource.sharedRandom().nextInt(upperBound: parsedQuestions.count) return QuestionJSONParser.shared.parseQuestionForIndex(randomIndex) } func getQuestionForCategory(_ category: Category) -> Question { while true { let question = QuestionJSONParser.shared.getRandomQuestion() if question.category == category { return question } } // Will never reach this state because of limited enum values } func getQuestionForCategory(_ category: Category, andRound round: Int) -> Question { while true { let question = QuestionJSONParser.shared.getRandomQuestion() if question.category == category && question.roundNumber == round { return question } } // Will never reach this state because of limited enum values } func getQuestionForRound(_ round: Int) -> Question { while true { let question = QuestionJSONParser.shared.getRandomQuestion() if question.roundNumber == round { return question } } // Will never reach this state because of limited round number selections } func getQuestionForSet(_ set: Int, andRound round: Int) -> Question { while true { let question = QuestionJSONParser.shared.getRandomQuestion() if question.setNumber == set && question.roundNumber == round { return question } } // Will never reach this state because of limited set and round selections } func getQuestionSet(_ set: Int, forRound round: Int) -> [Question] { var questions = [Question]() for question in QuestionJSONParser.shared.parsedQuestions { if question.setNumber == set && question.roundNumber == round { questions.append(question) } } return questions.sorted(by: sortQuestionsByNumberAndType) } func sortQuestionsByNumberAndType(this: Question, that: Question) -> Bool { let thisFirst: Bool if this.questionNumber < that.questionNumber { thisFirst = true } else if this.questionNumber == that.questionNumber { if this.questionType == .tossup { thisFirst = true } else { thisFirst = false } } else { thisFirst = false } return thisFirst } func getMCQuestion() -> Question { while true { let question = QuestionJSONParser.shared.getRandomQuestion() if question.answerType == .multipleChoice && question.answerChoices!.count == 4 { return question } } } func getMCQuestionForCategory(_ category: Category) -> Question { while true { let question = QuestionJSONParser.shared.getMCQuestion() if question.category == category { return question } } } }
mit
7c2e000535c26b26b29e165a7883a8c0
31.82963
101
0.597473
5.135574
false
false
false
false
camdenfullmer/UnsplashSwift
Source/UnsplashUtil.swift
1
3065
// UnsplashUtil.swift // // Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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 UIKit public class Unsplash { public static var client : UnsplashClient? public static func setUpWithAppId(appId : String, secret : String, scopes: [String]=UnsplashAuthManager.publicScope) { precondition(appId != "APP_ID" && secret != "SECRET", "app id and secret are not valid") precondition(UnsplashClient.sharedClient == nil, "only call `UnsplashClient.init` one time") UnsplashAuthManager.sharedAuthManager = UnsplashAuthManager(appId: appId, secret: secret, scopes: scopes) UnsplashClient.sharedClient = UnsplashClient(appId: appId) Unsplash.client = UnsplashClient.sharedClient if let token = UnsplashAuthManager.sharedAuthManager.getAccessToken() { UnsplashClient.sharedClient.accessToken = token } } public static func unlinkClient() { precondition(UnsplashClient.sharedClient != nil, "call `UnsplashClient.init` before calling this method") Unsplash.client = nil UnsplashClient.sharedClient = nil UnsplashAuthManager.sharedAuthManager.clearAccessToken() UnsplashAuthManager.sharedAuthManager = nil } public static func authorizeFromController(controller: UIViewController, completion:(Bool, NSError?) -> Void) { precondition(UnsplashAuthManager.sharedAuthManager != nil, "call `UnsplashAuthManager.init` before calling this method") precondition(!UnsplashClient.sharedClient.authorized, "client is already authorized") UnsplashAuthManager.sharedAuthManager.authorizeFromController(controller, completion: { token, error in if let accessToken = token { UnsplashClient.sharedClient.accessToken = accessToken completion(true, nil) } else { completion(false, error!) } }) } }
mit
69f39555cda1ce2c6f57daf863d4e9cc
46.890625
128
0.711256
4.834385
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/Processors/GutenbergBlockProcessor.swift
2
8218
import Foundation import Aztec /// Struct to represent a Gutenberg block element /// public struct GutenbergBlock { public let name: String public let attributes: [String: Any] public let content: String } /// A class that processes a Gutenberg post content and replaces the designated Gutenberg block for the replacement provided strings. /// public class GutenbergBlockProcessor: Processor { /// Whenever a Guntenberg block is found by the processor, this closure will be executed so that elements can be customized. /// public typealias Replacer = (GutenbergBlock) -> String? let name: String private enum CaptureGroups: Int { case all = 0 case name case attributes static let allValues: [CaptureGroups] = [.all, .name, .attributes] } // MARK: - Parsing & processing properties private let replacer: Replacer // MARK: - Initializers public init(for blockName: String, replacer: @escaping Replacer) { self.name = blockName self.replacer = replacer } /// Regular expression to detect attributes of the opening tag of a block /// Capture groups: /// /// 1. The block id /// 2. The block attributes /// var openTagRegex: NSRegularExpression { let pattern = "\\<!--[ ]?(\(name))([\\s\\S]*?)-->" return try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) } /// Regular expression to detect the closing tag of a block /// var closingTagRegex: NSRegularExpression { let pattern = "\\<!-- \\/\(name) -->" return try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) } // MARK: - Processing /// Processes the block and for any needed replacements from a given opening tag match. /// - Parameters: /// - text: The string that the following parameter is found in. /// - Returns: The resulting string after the necessary replacements have occured /// public func process(_ text: String) -> String { let matches = openTagRegex.matches(in: text, options: [], range: text.utf16NSRange(from: text.startIndex ..< text.endIndex)) var replacements = [(NSRange, String)]() var lastReplacementBound = 0 for match in matches { if match.range.lowerBound >= lastReplacementBound, let replacement = process(match, in: text) { replacements.append(replacement) lastReplacementBound = replacement.0.upperBound } } let resultText = replace(replacements, in: text) return resultText } /// Replaces the /// - Parameters: /// - replacements: An array of tuples representing first a range of text that needs to be replaced then the string to replace /// - text: The string to perform the replacements on /// func replace(_ replacements: [(NSRange, String)], in text: String) -> String { let mutableString = NSMutableString(string: text) var offset = 0 for (range, replacement) in replacements { let lengthBefore = mutableString.length let offsetRange = NSRange(location: range.location + offset, length: range.length) mutableString.replaceCharacters(in: offsetRange, with: replacement) let lengthAfter = mutableString.length offset += (lengthAfter - lengthBefore) } return mutableString as String } } // MARK: - Regex Match Processing Logic private extension GutenbergBlockProcessor { /// Processes the block and for any needed replacements from a given opening tag match. /// - Parameters: /// - match: The match reperesenting an opening block tag /// - text: The string that the following parameter is found in. /// - Returns: Any necessary replacements within the provided string /// private func process(_ match: NSTextCheckingResult, in text: String) -> (NSRange, String)? { var result: (NSRange, String)? = nil if let closingRange = locateClosingTag(forMatch: match, in: text) { let attributes = readAttributes(from: match, in: text) let content = readContent(from: match, withClosingRange: closingRange, in: text) let parsedContent = process(content) // Recurrsively parse nested blocks and process those seperatly let block = GutenbergBlock(name: name, attributes: attributes, content: parsedContent) if let replacement = replacer(block) { let length = closingRange.upperBound - match.range.lowerBound let range = NSRange(location: match.range.lowerBound, length: length) result = (range, replacement) } } return result } /// Determines the location of the closing block tag for the matching open tag /// - Parameters: /// - openTag: The match reperesenting an opening block tag /// - text: The string that the following parameter is found in. /// - Returns: The Range of the closing tag for the block /// func locateClosingTag(forMatch openTag: NSTextCheckingResult, in text: String) -> NSRange? { guard let index = text.indexFromLocation(openTag.range.upperBound) else { return nil } let matches = closingTagRegex.matches(in: text, options: [], range: text.utf16NSRange(from: index ..< text.endIndex)) for match in matches { let content = readContent(from: openTag, withClosingRange: match.range, in: text) if tagsAreBalanced(in: content) { return match.range } } return nil } /// Determines if there are an equal number of opening and closing block tags in the provided text. /// - Parameters: /// - text: The string to test assumes that a block with an even number represents a valid block sequence. /// - Returns: A boolean where true represents an equal number of opening and closing block tags of the desired type /// func tagsAreBalanced(in text: String) -> Bool { let range = text.utf16NSRange(from: text.startIndex ..< text.endIndex) let openTags = openTagRegex.matches(in: text, options: [], range: range) let closingTags = closingTagRegex.matches(in: text, options: [], range: range) return openTags.count == closingTags.count } /// Obtains the block attributes from a regex match. /// - Parameters: /// - match: The `NSTextCheckingResult` from a successful regex detection of an opening block tag /// - text: The string that the following parameter is found in. /// - Returns: A JSON dictionary of the block attributes /// func readAttributes(from match: NSTextCheckingResult, in text: String) -> [String: Any] { guard let attributesText = match.captureGroup(in: CaptureGroups.attributes.rawValue, text: text), let data = attributesText.data(using: .utf8 ), let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments), let jsonDictionary = json as? [String: Any] else { return [:] } return jsonDictionary } /// Obtains the block content from a regex match and range. /// - Parameters: /// - match: The `NSTextCheckingResult` from a successful regex detection of an opening block tag /// - closingRange: The `NSRange` of the closing block tag /// - text: The string that the following parameters are found in. /// - Returns: The content between the opening and closing tags of a block /// func readContent(from match: NSTextCheckingResult, withClosingRange closingRange: NSRange, in text: String) -> String { guard let index = text.indexFromLocation(match.range.upperBound) else { return "" } guard let closingBound = text.indexFromLocation(closingRange.lowerBound) else { return "" } return String(text[index..<closingBound]) } }
gpl-2.0
18000e59bd0ea9e9d180e56419fa1a46
40.296482
138
0.638963
4.789044
false
false
false
false
marinehero/LeetCode-Solutions-in-Swift
Solutions/Solutions/Hard/Hard_037_Sudoku_Solver.swift
4
1974
/* https://leetcode.com/problems/sudoku-solver/ #37 Sudoku Solver Level: hard Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. Inspired by @power721 at https://leetcode.com/discuss/5958/afraid-cant-solve-problem-interview-because-someone-simplify */ import Foundation class Hard_037_Sudoku_Solver { class func validate(inout board board: [[Character]], x: Int, y: Int) -> Bool { let c: Character = board[x][y] for var i = 0; i < 9; i++ { if y != i && board[x][i] == c { return false } if x != i && board[i][y] == c { return false } } let xx: Int = x / 3 * 3 let yy: Int = y / 3 * 3 for var i = xx; i < xx + 3; i++ { for var j = yy; j < yy + 3; j++ { if x != i && y != j && board[i][j] == c { return false } } } return true } class func dfs(inout board board: [[Character]], position: Int) -> Bool { let n = board.count if position == n * n { return true } let x: Int = position / n let y: Int = position % n if board[x][y] == "." { let arr: [Character] = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] for c in arr { board[x][y] = c if validate(board: &board, x: x, y: y) && dfs(board: &board, position: position + 1) { return true } board[x][y] = "." } } else { if dfs(board: &board, position: position + 1) == true { return true } } return false } class func solveSudoku(inout board: [[Character]]) { dfs(board: &board, position: 0) } }
mit
b95f5d530e48acb80b2e938483fd4ee0
27.608696
119
0.463526
3.710526
false
false
false
false
stephentyrone/swift
test/Constraints/one_way_solve.swift
3
1438
// RUN: %target-typecheck-verify-swift -parse-stdlib -debug-constraints > %t.log 2>&1 // RUN: %FileCheck %s < %t.log import Swift func takeDoubleAndBool(_: Double, _: Bool) { } func testTernaryOneWay(b: Bool, b2: Bool) { // CHECK: ---Connected components--- // CHECK-NEXT: 3: $T10 depends on 1 // CHECK-NEXT: 1: $T5 $T8 $T9 depends on 0, 2 // CHECK-NEXT: 2: $T7 // CHECK-NEXT: 0: $T4 // CHECK-NEXT: 4: $T11 $T13 $T14 takeDoubleAndBool( Builtin.one_way( b ? Builtin.one_way(3.14159) : Builtin.one_way(2.71828)), b == true) } func int8Or16(_ x: Int8) -> Int8 { return x } func int8Or16(_ x: Int16) -> Int16 { return x } func testTernaryOneWayOverload(b: Bool) { // CHECK: ---Connected components--- // CHECK: 1: $T5 $T10 $T11 depends on 0, 2 // CHECK: 2: $T7 $T8 $T9 // CHECK: 0: $T2 $T3 $T4 // CHECK: solving component #1 // CHECK: Initial bindings: $T11 := Int16, $T11 := Int8 // CHECK: solving component #1 // CHECK: Initial bindings: $T11 := Int16, $T11 := Int8 // CHECK: solving component #1 // CHECK: Initial bindings: $T11 := Int8, $T11 := Int16 // CHECK: solving component #1 // CHECK: Initial bindings: $T11 := Int8 // CHECK: found solution 0 0 0 0 0 0 0 2 0 0 0 0 0 // CHECK: composed solution 0 0 0 0 0 0 0 2 0 0 0 0 0 // CHECK-NOT: composed solution 0 0 0 0 0 0 0 2 0 0 0 0 0 let _: Int8 = b ? Builtin.one_way(int8Or16(17)) : Builtin.one_way(int8Or16(42)) }
apache-2.0
4a1a489d4f1b6b31808a650412a028b5
30.26087
85
0.615438
2.776062
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Charts/ScatterChartView.swift
6
2265
// // ScatterChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase /// The ScatterChart. Draws dots, triangles, squares and custom shapes into the chartview. public class ScatterChartView: BarLineChartViewBase, ScatterChartRendererDelegate { public override func initialize() { super.initialize(); renderer = ScatterChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler); _chartXMin = -0.5; } public override func calcMinMax() { super.calcMinMax(); if (_deltaX == 0.0 && _data.yValCount > 0) { _deltaX = 1.0; } _chartXMax += 0.5; _deltaX = CGFloat(abs(_chartXMax - _chartXMin)); } // MARK: - ScatterChartRendererDelegate public func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData! { return _data as! ScatterChartData!; } public func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return getTransformer(which); } public func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter! { return self._defaultValueFormatter; } public func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Float { return self.chartYMax; } public func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Float { return self.chartYMin; } public func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Float { return self.chartXMax; } public func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Float { return self.chartXMin; } public func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int { return self.maxVisibleValueCount; } }
gpl-2.0
87147117e22ff7ac5f4161ac8cd6ad60
26.634146
142
0.671523
5.341981
false
false
false
false
benscazzero/Chess
Chess/AppDelegate.swift
1
6121
// // AppDelegate.swift // Chess // // Created by Scazzero, Benjamin on 11/2/14. // Copyright (c) 2014 Scazzero, Benjamin. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "S0.Chess" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Chess", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Chess.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
40ed3185ec0d6ba8a3c3910768f265af
54.144144
290
0.716223
5.769086
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/view model/TKUITripOverviewViewModel+Fetch.swift
1
939
// // TKUITripOverviewViewModel+Fetch.swift // TripKitUI-iOS // // Created by Adrian Schönig on 07.03.19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import Foundation import RxSwift import TripKit extension TKUITripOverviewViewModel { static func fetchContentOfServices(in trip: Trip) -> Observable<Void> { let queries: [(Service, Date, TKRegion)] = trip.segments .filter { !$0.isContinuation } // the previous segment will provide that .compactMap { $0.service != nil ? ($0.service!, $0.departureTime, $0.startRegion ?? .international) : nil } .filter { $0.0.hasServiceData == false } let requests: [Observable<Void>] = queries .map(TKBuzzInfoProvider.rx.downloadContent) .map { $0.asObservable() } let merged = Observable<Void>.merge(requests) return merged.throttle(.milliseconds(500), latest: true, scheduler: MainScheduler.asyncInstance) } }
apache-2.0
a85ffa110d032943e0f09c11ae2b3e5a
28.28125
113
0.689434
3.887967
false
false
false
false
eCrowdMedia/MooApi
Tests/PublisherTests.swift
1
850
import XCTest @testable import MooApi import Argo import Foundation final internal class PublisherTests: XCTestCase { func testDatas() { let testBundle = Bundle(for: type(of: self)) let path = testBundle.path(forResource: "PublisherInfo", ofType: "json") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) let json = JSON(try! JSONSerialization.jsonObject(with: data, options: [])) let result = ApiDocument<MooApi.Publisher>.decode(json) guard let publisher = result.value?.data else { XCTFail("\(result.error.debugDescription)") return } let attributes = publisher.attributes // Test type and id XCTAssertEqual(publisher.type, "publishers") XCTAssertEqual(publisher.id, "111") // Test attributes XCTAssertEqual(attributes.name, "iFit 愛瘦身") } }
mit
46afb7ef75f2c532828aff4d47d86d72
26.225806
79
0.689573
4.178218
false
true
false
false
Ansem717/IOS-GithubClient
GithubClient/GithubClient/ModelAdditions.swift
1
4823
// // ModelAdditions.swift // GithubClient // // Created by Andy Malik on 2/23/16. // Copyright © 2016 AndyMalik. All rights reserved. // import Foundation extension Repositories { class func update(completion: (success: Bool, repos: [Repositories]) -> ()) { API.shared.enqueue(GETRepoRequest()) { (success, json) -> () in var repos = [Repositories]() for eachRepo in json { let name = eachRepo["name"] as? String ?? kEmptyString let desc = eachRepo["description"] as? String ?? kEmptyString let ownerName = eachRepo["owner"]?["login"] as? String ?? kEmptyString let ownerProfileLink = eachRepo["owner"]?["html_url"] as? String ?? kEmptyString let ownerRepoLink = eachRepo["owner"]?["repos_url"] as? String ?? kEmptyString let owner = Owner(name: ownerName, linkToRepos: ownerRepoLink, profileLink: ownerProfileLink) repos.append(Repositories(name: name, owner: owner, desc: desc)) } NSOperationQueue.mainQueue().addOperationWithBlock { completion(success: true, repos: repos) } } } class func searchRepo(searchResult: String, completion: (success: Bool, repos: [Repositories]) -> ()) { API.shared.enqueue(GETSearchRequest(searchResult: searchResult)) { (success, json) -> () in var repos = [Repositories]() // print(json) for eachRepo in json { for var i = 0; i < eachRepo["items"]?.count; i++ { let name = eachRepo["items"]?[i]["name"] as? String ?? kEmptyString //I think this is the ugliest line of code I have ever written. I have no clue how to read this json! //Each time I did a guard let or if let, it said that eachRepo was an [Ambiguous reference to member 'subscript'] //Which would result in my if-let or guard-let checking a normal array of a string: ["items"] let desc = eachRepo["items"]?[i]["description"] as? String ?? kEmptyString let ownerName = (eachRepo["items"]?[i]["owner"]!)!["login"] as? String ?? kEmptyString let ownerProfileLink = (eachRepo["items"]?[i]["owner"]!)!["html_url"] as? String ?? kEmptyString let ownerRepoLink = (eachRepo["items"]?[i]["owner"]!)!["repos_url"] as? String ?? kEmptyString // To walk through this, this is a single "eachRepo" item, and in that has a key of "items" which is optional, and in that has an index that's in a for-loop, and in each of those has a key of "owner" which must be unwrapped, and then the whole thing must be unwrapped so now we can find the owner's Login, html url, and repos url. I just kept unwrapping until Xcode stopped yelling at me... Litterally, this was the only thing that I found which worked. I'd like to see the answer you guys used. let owner = Owner(name: ownerName, linkToRepos: ownerRepoLink, profileLink: ownerProfileLink) repos.append(Repositories(name: name, owner: owner, desc: desc)) } } NSOperationQueue.mainQueue().addOperationWithBlock { completion(success: true, repos: repos) } } } } extension CurrentUser { class func update(completion: (success: Bool, user: CurrentUser?) -> ()) { API.shared.enqueue(GETCurrentUserRequest()) { (success, json) -> () in var currUser = [CurrentUser]() for user in json { let realName = user["name"] as? String ?? user["login"] as? String // If name is not provided, default to the login name. let userProfileLink = user["html_url"] as? String ?? kEmptyString let linkToRepos = user["repos_url"] as? String ?? kEmptyString let avatarURL = user["avatar_url"] as? String ?? kEmptyString let email = user["email"] as? String ?? kEmptyString currUser.append(CurrentUser(name: realName!, linkToRepos: linkToRepos, profileLink: userProfileLink, avatarURL: avatarURL, email: email)) } if let user = currUser.first { NSOperationQueue.mainQueue().addOperationWithBlock { completion(success: true, user: user) } } else { NSOperationQueue.mainQueue().addOperationWithBlock { completion(success: false, user: nil) } } } } }
mit
ec6a46a30a8c5c688f397258419b3e54
52.577778
515
0.566363
4.860887
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/InconsistentLineEndingsViewController.swift
1
5849
// // InconsistentLineEndingsViewController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2022-04-11. // // --------------------------------------------------------------------------- // // © 2022 1024jp // // 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 // // https://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 Cocoa import Combine /// Table column identifiers private extension NSUserInterfaceItemIdentifier { static let line = Self("Line") static let lineEnding = Self("Line Ending") } final class InconsistentLineEndingsViewController: NSViewController { // MARK: Private Properties private var document: Document? { self.representedObject as? Document } private var lineEndings: [ItemRange<LineEnding>] = [] private var documentLineEnding: LineEnding = .lf private var observers: Set<AnyCancellable> = [] @IBOutlet private var numberFormatter: NumberFormatter? @IBOutlet private weak var messageField: NSTextField? @IBOutlet private weak var tableView: NSTableView? // MARK: Lifecycle override func viewWillAppear() { super.viewWillAppear() self.document?.lineEndingScanner.$inconsistentLineEndings .removeDuplicates() .receive(on: RunLoop.main) .sink { [unowned self] in self.lineEndings = $0.sorted(using: self.tableView?.sortDescriptors ?? []) self.tableView?.enclosingScrollView?.isHidden = $0.isEmpty self.tableView?.reloadData() self.updateMessage() } .store(in: &self.observers) self.document?.$lineEnding .removeDuplicates() .receive(on: RunLoop.main) .sink { [unowned self] in self.documentLineEnding = $0 self.updateMessage() } .store(in: &self.observers) } override func viewDidDisappear() { super.viewDidDisappear() self.observers.removeAll() } // MARK: Private Methods /// Update the result message above the table. @MainActor private func updateMessage() { guard let messageField = self.messageField else { return assertionFailure() } messageField.textColor = self.lineEndings.isEmpty ? .secondaryLabelColor : .labelColor messageField.stringValue = { switch self.lineEndings.count { case 0: return "No issues found.".localized case 1: return String(format: "Found a line ending other than %@.".localized, self.documentLineEnding.name) default: return String(format: "Found %i line endings other than %@.".localized, locale: .current, self.lineEndings.count, self.documentLineEnding.name) } }() } } extension InconsistentLineEndingsViewController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { guard let tableView = notification.object as? NSTableView, let selectedLineEnding = self.lineEndings[safe: tableView.selectedRow], let textView = self.document?.textView else { return } textView.selectedRange = selectedLineEnding.range textView.scrollRangeToVisible(textView.selectedRange) textView.showFindIndicator(for: textView.selectedRange) } } extension InconsistentLineEndingsViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { self.lineEndings.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { guard let lineEnding = self.lineEndings[safe: row], let identifier = tableColumn?.identifier else { return nil } switch identifier { case .line: // calculate the line number first at this point to postpone the high cost processing as much as possible return self.document?.string.lineNumber(at: lineEnding.location) case .lineEnding: return lineEnding.item.name default: fatalError() } } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { guard tableView.sortDescriptors != oldDescriptors, self.lineEndings.compareCount(with: 1) == .greater else { return } self.lineEndings.sort(using: tableView.sortDescriptors) tableView.reloadData() } } extension ItemRange: KeySortable where Item == LineEnding { func compare(with other: Self, key: String) -> ComparisonResult { switch key { case "location": return self.location.compare(other.location) case "lineEnding": return self.item.index.compare(other.item.index) default: fatalError() } } }
apache-2.0
a6194e340d71d3251a7f7d6df6131743
29.941799
121
0.596785
5.249551
false
false
false
false
CodaFi/SwiftCheck
Sources/SwiftCheck/WitnessedArbitrary.swift
1
7075
// // WitnessedArbitrary.swift // SwiftCheck // // Created by Robert Widmann on 12/15/15. // Copyright © 2016 Typelift. All rights reserved. // extension Array : Arbitrary where Element : Arbitrary { /// Returns a generator of `Array`s of arbitrary `Element`s. public static var arbitrary : Gen<Array<Element>> { return Element.arbitrary.proliferate } /// The default shrinking function for `Array`s of arbitrary `Element`s. public static func shrink(_ bl : Array<Element>) -> [[Element]] { let rec : [[Element]] = shrinkOne(bl) return Int.shrink(bl.count).reversed().flatMap({ k in removes((k + 1), n: bl.count, xs: bl) }) + rec } } extension AnyBidirectionalCollection : Arbitrary where Element : Arbitrary { /// Returns a generator of `AnyBidirectionalCollection`s of arbitrary `Element`s. public static var arbitrary : Gen<AnyBidirectionalCollection<Element>> { return [Element].arbitrary.map(AnyBidirectionalCollection.init) } /// The default shrinking function for `AnyBidirectionalCollection`s of arbitrary `Element`s. public static func shrink(_ bl : AnyBidirectionalCollection<Element>) -> [AnyBidirectionalCollection<Element>] { return [Element].shrink([Element](bl)).map(AnyBidirectionalCollection.init) } } extension AnySequence : Arbitrary where Element : Arbitrary { /// Returns a generator of `AnySequence`s of arbitrary `Element`s. public static var arbitrary : Gen<AnySequence<Element>> { return [Element].arbitrary.map(AnySequence.init) } /// The default shrinking function for `AnySequence`s of arbitrary `Element`s. public static func shrink(_ bl : AnySequence<Element>) -> [AnySequence<Element>] { return [Element].shrink([Element](bl)).map(AnySequence.init) } } extension ArraySlice : Arbitrary where Element : Arbitrary { /// Returns a generator of `ArraySlice`s of arbitrary `Element`s. public static var arbitrary : Gen<ArraySlice<Element>> { return [Element].arbitrary.map(ArraySlice.init) } /// The default shrinking function for `ArraySlice`s of arbitrary `Element`s. public static func shrink(_ bl : ArraySlice<Element>) -> [ArraySlice<Element>] { return [Element].shrink([Element](bl)).map(ArraySlice.init) } } extension CollectionOfOne : Arbitrary where Element : Arbitrary { /// Returns a generator of `CollectionOfOne`s of arbitrary `Element`s. public static var arbitrary : Gen<CollectionOfOne<Element>> { return Element.arbitrary.map(CollectionOfOne.init) } } /// Generates an Optional of arbitrary values of type A. extension Optional : Arbitrary where Wrapped : Arbitrary { /// Returns a generator of `Optional`s of arbitrary `Wrapped` values. public static var arbitrary : Gen<Optional<Wrapped>> { return Gen<Optional<Wrapped>>.frequency([ (1, Gen<Optional<Wrapped>>.pure(.none)), (3, liftM(Optional<Wrapped>.some, Wrapped.arbitrary)), ]) } /// The default shrinking function for `Optional`s of arbitrary `Wrapped`s. public static func shrink(_ bl : Optional<Wrapped>) -> [Optional<Wrapped>] { if let x = bl { let rec : [Optional<Wrapped>] = Wrapped.shrink(x).map(Optional<Wrapped>.some) return [.none] + rec } return [] } } extension ContiguousArray : Arbitrary where Element : Arbitrary { /// Returns a generator of `ContiguousArray`s of arbitrary `Element`s. public static var arbitrary : Gen<ContiguousArray<Element>> { return [Element].arbitrary.map(ContiguousArray.init) } /// The default shrinking function for `ContiguousArray`s of arbitrary `Element`s. public static func shrink(_ bl : ContiguousArray<Element>) -> [ContiguousArray<Element>] { return [Element].shrink([Element](bl)).map(ContiguousArray.init) } } /// Generates an dictionary of arbitrary keys and values. extension Dictionary : Arbitrary where Key : Arbitrary, Value : Arbitrary { /// Returns a generator of `Dictionary`s of arbitrary `Key`s and `Value`s. public static var arbitrary : Gen<Dictionary<Key, Value>> { return [Key].arbitrary.flatMap { (k : [Key]) in return [Value].arbitrary.flatMap { (v : [Value]) in return Gen.pure(Dictionary(zip(k, v)) { $1 }) } } } /// The default shrinking function for `Dictionary`s of arbitrary `Key`s and /// `Value`s. public static func shrink(_ d : Dictionary<Key, Value>) -> [Dictionary<Key, Value>] { return d.map { t in Dictionary(zip(Key.shrink(t.key), Value.shrink(t.value)), uniquingKeysWith: { (_, v) in v }) } } } extension EmptyCollection : Arbitrary { /// Returns a generator of `EmptyCollection`s of arbitrary `Element`s. public static var arbitrary : Gen<EmptyCollection<Element>> { return Gen.pure(EmptyCollection()) } } extension Range : Arbitrary where Bound : Arbitrary { /// Returns a generator of `HalfOpenInterval`s of arbitrary `Bound`s. public static var arbitrary : Gen<Range<Bound>> { return Bound.arbitrary.flatMap { l in return Bound.arbitrary.flatMap { r in return Gen.pure((Swift.min(l, r) ..< Swift.max(l, r))) } } } /// The default shrinking function for `HalfOpenInterval`s of arbitrary `Bound`s. public static func shrink(_ bl : Range<Bound>) -> [Range<Bound>] { return zip(Bound.shrink(bl.lowerBound), Bound.shrink(bl.upperBound)).map(Range.init) } } extension LazySequence : Arbitrary where Base : Arbitrary { /// Returns a generator of `LazySequence`s of arbitrary `Base`s. public static var arbitrary : Gen<LazySequence<Base>> { return Base.arbitrary.map({ $0.lazy }) } } extension Repeated : Arbitrary where Element : Arbitrary { /// Returns a generator of `Repeat`s of arbitrary `Element`s. public static var arbitrary : Gen<Repeated<Element>> { let constructor: (Element, Int) -> Repeated<Element> = { (element, count) in return repeatElement(element , count: count) } return Gen<(Element, Int)>.zip(Element.arbitrary, Int.arbitrary).map({ t in constructor(t.0, t.1) }) } } extension Set : Arbitrary where Element : Arbitrary { /// Returns a generator of `Set`s of arbitrary `Element`s. public static var arbitrary : Gen<Set<Element>> { return Gen.sized { n in return Gen<Int>.choose((0, n)).flatMap { k in if k == 0 { return Gen.pure(Set([])) } return sequence(Array((0...k)).map { _ in Element.arbitrary }).map(Set.init) } } } /// The default shrinking function for `Set`s of arbitrary `Element`s. public static func shrink(_ s : Set<Element>) -> [Set<Element>] { return [Element].shrink([Element](s)).map(Set.init) } } // MARK: - Implementation Details private func removes<A : Arbitrary>(_ k : Int, n : Int, xs : [A]) -> [[A]] { let xs2 : [A] = Array(xs.suffix(max(0, xs.count - k))) if k > n { return [] } else if xs2.isEmpty { return [[]] } else { let xs1 : [A] = Array(xs.prefix(k)) let rec : [[A]] = removes(k, n: n - k, xs: xs2).map({ xs1 + $0 }) return [xs2] + rec } } private func shrinkOne<A : Arbitrary>(_ xs : [A]) -> [[A]] { guard let x : A = xs.first else { return [[A]]() } let xss = [A](xs[1..<xs.endIndex]) let a : [[A]] = A.shrink(x).map({ [$0] + xss }) let b : [[A]] = shrinkOne(xss).map({ [x] + $0 }) return a + b }
mit
d002b8c55171cb4d523015d66e2c2ba3
34.19403
116
0.693243
3.483013
false
false
false
false