hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
9bf64c3974b5531b488b07597c104408fe36077b
2,596
// // NetworkServicePageViewModel.swift // MVVMExample // // Created by pham.minh.tien on 5/26/20. // Copyright © 2020 Sun*. All rights reserved. // import UIKit import MVVM import RxSwift import RxCocoa class NetworkServicePageViewModel: BaseViewModel { var networkService: NetworkService? let rxPageTitle = BehaviorRelay<String?>(value: "") let rxSearchText = BehaviorRelay<String?>(value: nil) let rxCurlText = BehaviorRelay<String?>(value: "") let rxResponseText = BehaviorRelay<String?>(value: "") let rxSearchState = BehaviorRelay<NetworkServiceState>(value: .none) let rxDidSearchState = PublishRelay<NetworkServiceState>() var page: Int = 0 override func react() { super.react() rxPageTitle.accept("Network service") // Get service self.networkService = DependencyManager.shared.getService() self.networkService?.curlString.bind(to: rxCurlText) => disposeBag rxSearchText.do(onNext: {[weak self] text in self?.page = 1 if let keyword = text { self?.rxCurlText.accept("Start Request \(keyword)... ") } else { self?.rxCurlText.accept("") } if !text.isNilOrEmpty { self?.rxSearchState.accept(.none) } }) .debounce(.microseconds(500), scheduler: Scheduler.shared.mainScheduler) .subscribe(onNext: {[weak self] text in if !text.isNilOrEmpty { self?.search(withText: text!, withPage: 0) } }) => disposeBag } func search(withText keyword: String, withPage page: Int) { _ = networkService?.search(withKeyword: keyword, page: page) .map(prepareSources) .subscribe(onSuccess: { [weak self] results in if let flickSearch = results, let desc = flickSearch.response_description { self?.rxResponseText.accept("Responsed: \n\(desc)") self?.rxSearchState.accept(.success) } self?.rxDidSearchState.accept(.success) }, onFailure: { error in self.rxResponseText.accept("Responsed: \n\(error)") self.rxSearchState.accept(.error) self.rxDidSearchState.accept(.error) }) } private func prepareSources(_ response: FlickrSearchResponse?) -> FlickrSearchResponse? { /// Mapping data if need. /// Create model return response } }
33.714286
93
0.588598
5d68a286685cf2671af7a375089d2753dd56a015
965
// // TypeHolderExample.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct TypeHolderExample: Codable { public private(set) var stringItem: String public private(set) var numberItem: Double public private(set) var integerItem: Int public private(set) var boolItem: Bool public private(set) var arrayItem: [Int] public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { self.stringItem = stringItem self.numberItem = numberItem self.integerItem = integerItem self.boolItem = boolItem self.arrayItem = arrayItem } public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" case boolItem = "bool_item" case arrayItem = "array_item" } }
26.081081
109
0.678756
891c9f3c13c38ad71a0e21abc3fb13e93211df32
9,225
// // PostFormWebViewController.swift // Alamofire // // Created by 武飞跃 on 2018/8/3. // import Foundation import WebKit protocol PostFormNavigationViewDelegate: class { func didBackTapped() func didCloseTapped() } final class PostFormNavigationView: UIView { weak var delegate: PostFormNavigationViewDelegate? private var backBtn: UIButton? private var closeBtn: UIButton? var titleLab: UILabel! override init(frame: CGRect) { super.init(frame: frame) setupView() } func setupView() { if let imagePath = Bundle.formAssetBundle.path(forResource: "icon_back@2x", ofType: "png", inDirectory: "Images") { if let back_nor = UIImage(contentsOfFile: imagePath) { let backBtn = UIButton() backBtn.setImage(back_nor, for: .normal) backBtn.addTarget(self, action: #selector(backTapped), for: .touchUpInside) addSubview(backBtn) self.backBtn = backBtn } } if let imagePath = Bundle.formAssetBundle.path(forResource: "icon_blackClose@2x", ofType: "png", inDirectory: "Images") { if let back_nor = UIImage(contentsOfFile: imagePath) { let closeBtn = UIButton() closeBtn.setImage(back_nor, for: .normal) closeBtn.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) addSubview(closeBtn) self.closeBtn = closeBtn } } let titleLab = UILabel() titleLab.textAlignment = .center titleLab.font = UIFont.boldSystemFont(ofSize: 18) titleLab.textColor = .black addSubview(titleLab) self.titleLab = titleLab } override func layoutSubviews() { super.layoutSubviews() titleLab.frame.size = CGSize(width: 200, height: 20) titleLab.center.x = bounds.midX titleLab.frame.origin.y = bounds.height - titleLab.bounds.height - 9 backBtn?.frame.size = CGSize(width: 30, height: 30) backBtn?.frame.origin = CGPoint(x: 10, y: bounds.height - 30 - 4) closeBtn?.frame.size = CGSize(width: 30, height: 30) if let backBtn = backBtn { closeBtn?.frame.origin = CGPoint(x: backBtn.frame.maxX + 10, y: bounds.height - 30 - 4) } else { closeBtn?.frame.origin = CGPoint(x: 10, y: bounds.height - 30 - 4) } } @objc private func backTapped() { delegate?.didBackTapped() } @objc private func closeTapped() { delegate?.didCloseTapped() } required init?(coder aDecoder: NSCoder) { return nil } } public final class PostFormWebViewController: UIViewController { public typealias ResponseCompletion = () -> Void //初始化实现 public var backAction: ResponseCompletion? public var loadHTMLString: String = "" public var baseURL: URL? public var returnURLString: String = "" public var javeScript: String? public var openURLRole: ((URL) -> Bool)! public var openURLCompletion: ((URL) -> Void)? public var navigationItemTitle: String = "" private var backNavigation: WKNavigation? private var webView: WKWebView! private var needLoadJSPOST = true private let configuration: WKWebViewConfiguration = WKWebViewConfiguration() /// 进度条 private var progressView: UIProgressView! private var navigationView: PostFormNavigationView! private var isFirst: Bool = true override public func viewDidLoad() { super.viewDidLoad() setupViews() } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear") } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("viewWillDisappear") } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if isFirst { isFirst = false let navigationRect = CGRect(x: 0, y: 0, width: view.bounds.width, height: iPhoneXTopInset + 64) navigationView.frame = navigationRect let progressRect = CGRect(x: 0, y: navigationRect.maxY, width: view.bounds.width, height: 3) progressView.frame = progressRect let webViewRect = CGRect(x: 0, y: progressRect.maxY, width: view.bounds.width, height: view.bounds.height - progressRect.maxY ) webView.frame = webViewRect } } private func setupViews() { automaticallyAdjustsScrollViewInsets = false view.backgroundColor = .white webView = WKWebView(frame: .zero, configuration: configuration) webView.loadHTMLString(loadHTMLString, baseURL: baseURL) webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil) webView.navigationDelegate = self webView.backgroundColor = UIColor.init(red: 247/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1) view.addSubview(webView) progressView = UIProgressView() progressView.tintColor = .orange progressView.trackTintColor = .white view.addSubview(progressView) navigationView = PostFormNavigationView(frame: .zero) navigationView.backgroundColor = .white navigationView.delegate = self navigationView.titleLab.text = navigationItemTitle view.addSubview(navigationView) } deinit { print("已经释放") } public func free() { webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress)) webView.navigationDelegate = nil } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == #keyPath(WKWebView.estimatedProgress) { progressView.alpha = 1.0 progressView.setProgress(Float(webView.estimatedProgress), animated: true) if webView.estimatedProgress >= 1.0 { UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: { self.progressView.alpha = 0.0 }, completion: { (finfished: Bool) in self.progressView.setProgress(0.0, animated: false) }) } } } /// 调用JS发送POST请求 private func postRequestWithJS() { guard let js = javeScript, js.isEmpty == false else { return } // 调用JS代码 webView.evaluateJavaScript(js) { (_, error) in if error == nil { //printLogDebug("----- post 请求成功") } } } private var iPhoneXTopInset: CGFloat { if #available(iOS 11, *) { guard UIScreen.main.nativeBounds.height == 2436 else { return 0 } return view.safeAreaInsets.top } return 0 } } extension PostFormWebViewController: PostFormNavigationViewDelegate { func didBackTapped() { if webView.canGoBack { backNavigation = webView.goBack() webView.reload() } else { backAction?() } } func didCloseTapped() { backAction?() } } extension PostFormWebViewController: WKNavigationDelegate { // 开始加载时 public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { progressView.isHidden = false } /// 即将白屏 public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { // printLogDebug("------ 白屏了") } // 完成加载 public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // printLogDebug("----- H5页面加载完成") if needLoadJSPOST { // 调用使用JS发送POST请求的方法 postRequestWithJS() // 将Flag置为NO(后面就不需要加载了) needLoadJSPOST = false } //一网通的H5界面不支持goback,猜测原因可能是WKWebView的老问题post请求的body信息丢失,回退之后再做一次刷新暂时可以解决 if let curNavigation = backNavigation, navigation == curNavigation { webView.reload() backNavigation = nil } } // 服务器开始请求的时候调用 public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { decisionHandler(.cancel) return } if url.absoluteString == returnURLString { self.backAction?() } else if openURLRole(url) { openURLCompletion?(url) } decisionHandler(.allow) } }
31.377551
164
0.595556
e5b7a860986f6f0d73b3308d9c13b98c6fe69e04
99
import Foundation @objc(NumericTypesClass) public class NumericTypesClass: _NumericTypesClass { }
16.5
52
0.838384
758c7b50bfc2053c1673fd3d981a22b7c8e447da
354
import Foundation import RxSwift public class FetchSchoolRankUseCase { private let rankRepository: RankRepository init(rankRepository: RankRepository) { self.rankRepository = rankRepository } public func excute(dateType: DateType) -> Observable<MySchool> { rankRepository.fetchSchoolRank(dateType: dateType) } }
19.666667
68
0.731638
298114037324bb76acad9cc5120ec444395e9e10
747
// // PublishedSubscriber.swift // // // Created by Sergej Jaskiewicz on 29.10.2020. // internal struct PublishedSubscriber<Value>: Subscriber { internal typealias Input = Value internal typealias Failure = Never internal let combineIdentifier = CombineIdentifier() private weak var subject: PublishedSubject<Value>? internal init(_ subject: PublishedSubject<Value>) { self.subject = subject } internal func receive(subscription: Subscription) { subject?.send(subscription: subscription) } internal func receive(_ input: Value) -> Subscribers.Demand { subject?.send(input) return .none } internal func receive(completion: Subscribers.Completion<Never>) {} }
22.636364
71
0.689424
1e6f516c18983e0e87d7f9b20271157c760b2a1f
13,669
import Foundation public struct CreditCardUtils { static let maxCvvLength = 3 static let maxCvvLengthAmex = 4 static let maxPanLength = 16 static let maxPanLengthAmericanExpress = 15 static let maxPanLengthDinersClub = 14 private static let prefixesAmericanExpress = ["34", "37"] private static let prefixesDinersClub = ["300", "301", "302", "303", "304", "305", "309", "36", "38", "39"] private static let prefixesDiscover = ["6011", "64", "65"] private static let prefixesJcb = ["35"] private static let prefixesMastercard = ["2221", "2222", "2223", "2224", "2225", "2226", "2227", "2228", "2229", "223", "224", "225", "226", "227", "228", "229", "23", "24", "25", "26", "270", "271", "2720", "50", "51", "52", "53", "54", "55", "67"] private static let prefixesUnionPay = ["62"] private static let prefixesVisa = ["4"] private static let prefixesUzcard = ["8600"] private static let prefixesHumo = ["9860","9987"] /** Checks if the card number is valid. - Parameter cardNumber: The card number as a string . - Returns: `true` if valid, `false` otherwise */ public static func isValidNumber(cardNumber: String) -> Bool { return isValidLuhnNumber(cardNumber: cardNumber) && isValidLength(cardNumber: cardNumber) } /** Checks if the card's cvv is valid - Parameters: - cvv: The cvv as a string - network: The card's bank network - Returns: `true` if valid, `false ` otherwise */ public static func isValidCvv(cvv: String, network: CardNetwork) -> Bool { let cvv = cvv.trimmingCharacters(in: .whitespacesAndNewlines) return (network == CardNetwork.AMEX && cvv.count == maxCvvLengthAmex) || (cvv.count == maxCvvLength) } /** Checks if the card's expiration date is valid - Parameters: - expMonth: The expiration month as a string - expYear: The expiration year as a string - Returns: `true` is both expiration month and year are valid, `false` otherwise */ public static func isValidDate(expMonth: String, expYear: String) -> Bool { guard let expirationMonth = Int(expMonth.trimmingCharacters(in: .whitespacesAndNewlines)) else { return false } guard let expirationYear = Int(expYear.trimmingCharacters(in: .whitespacesAndNewlines)) else { return false } if !isValidMonth(expMonth: expirationMonth) { return false } else if !isValidYear(expYear: expirationYear) { return false } else { return !hasMonthPassed(expMonth: expirationMonth, expYear: expirationYear) } } /** Checks if the card's expiration month is valid - Parameter expMonth: The expiration month as an integer - Returns: `true` if valid, `false` otherwise */ static func isValidMonth(expMonth: Int) -> Bool { return 1...12 ~= expMonth } /** Checks if the card's expiration year is valid - Parameter expYear: The expiration year as an integer - Returns: `true` if valid, `false` otherwise */ static func isValidYear(expYear: Int) -> Bool { return !hasYearPassed(expYear: expYear) } /** Checks if the card's expiration month has passed - Parameters: - expMonth: The expiration month as an integer - expYear: The expiration year as an integer - Returns: `true` if expiration month has passed current time, `false` otherwise */ static func hasMonthPassed(expMonth: Int, expYear: Int) -> Bool { let currentMonth = getCurrentMonth() let currentYear = getCurrentYear() if hasYearPassed(expYear: expYear) { return true } else { return normalizeYear(expYear: expYear) == currentYear && expMonth < currentMonth } } /** Checks if the card's expiration year has passed - Parameter expYear: The expiration year as an integer - Returns: `true` if expiration year has passed current time, `false` otherwise */ static func hasYearPassed(expYear: Int) -> Bool { let currentYear = getCurrentYear() guard let expirationYear = normalizeYear(expYear: expYear) else { print("Could not get normalized expiration year") return false } return expirationYear < currentYear } /** Returns expiration year in four digits. If expiration year is two digits, it appends the current century to the beginning of the year - Parameter expYear: The expiration year as an integer - Returns: An `Int` of the four digit year, `nil` otherwise */ static func normalizeYear(expYear: Int) -> Int? { let currentYear = getCurrentYear() var expirationYear: Int if 0...99 ~= expYear { let currentYearToString = String(currentYear) let currentYearPrefix = currentYearToString.prefix(2) guard let concatExpYear = Int("\(currentYearPrefix)\(expYear)") else { print("Could not convert newly concatenated exp year string to int") return nil } expirationYear = concatExpYear } else { expirationYear = expYear } return expirationYear } static func getCurrentYear() -> Int { let date = Date() let now = Calendar.current let currentYear = now.component(.year, from: date) return currentYear } static func getCurrentMonth() -> Int { let date = Date() let now = Calendar.current // The start of the month begins from 1 let currentMonth = now.component(.month, from: date) return currentMonth } // https://en.wikipedia.org/wiki/Luhn_algorithm // assume 16 digits are for MC and Visa (start with 4, 5) and 15 is for Amex // which starts with 3 /** Checks if the card number passes the Luhn's algorithm - Parameter cardNumber: The card number as a string - Returns: `true` if the card number is a valid Luhn number, `false` otherwise */ static func isValidLuhnNumber(cardNumber: String) -> Bool { if cardNumber.isEmpty || !isValidBin(cardNumber: cardNumber){ return false } var sum = 0 let reversedCharacters = cardNumber.reversed().map { String($0) } for (idx, element) in reversedCharacters.enumerated() { guard let digit = Int(element) else { return false } switch ((idx % 2 == 1), digit) { case (true, 9): sum += 9 case (true, 0...8): sum += (digit * 2) % 9 default: sum += digit } } return sum % 10 == 0 } /** Checks if the card number contains a valid bin - Parameter cardNumber: The card number as a string - Returns: `true` if the card number contains a valid bin, `false` otherwise */ static func isValidBin(cardNumber: String) -> Bool { determineCardNetwork(cardNumber: cardNumber) != CardNetwork.UNKNOWN } static func isValidLength(cardNumber: String) -> Bool { return isValidLength(cardNumber: cardNumber, network: determineCardNetwork(cardNumber: cardNumber)) } /** Checks if the inputted card number has a valid length in accordance with the card's bank network - Parameters: - cardNumber: The card number as a string - network: The card's bank network - Returns: `true` is card number is a valid length, `false` otherwise */ static func isValidLength(cardNumber: String, network: CardNetwork ) -> Bool { let cardNumber = cardNumber.trimmingCharacters(in: .whitespacesAndNewlines) let cardNumberLength = cardNumber.count if cardNumber.isEmpty || network == CardNetwork.UNKNOWN { return false } switch network { case CardNetwork.AMEX: return cardNumberLength == maxPanLengthAmericanExpress case CardNetwork.DINERSCLUB: return cardNumberLength == maxPanLengthDinersClub default: return cardNumberLength == maxPanLength } } /** Returns the card's issuer / bank network based on the card number - Parameter cardNumber: The card number as a string - Returns: The card's bank network as a CardNetwork enum */ public static func determineCardNetwork(cardNumber: String) -> CardNetwork { let cardNumber = cardNumber.trimmingCharacters(in: .whitespacesAndNewlines) if cardNumber.isEmpty { return CardNetwork.UNKNOWN } switch true { case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesAmericanExpress): return CardNetwork.AMEX case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesDiscover): return CardNetwork.DISCOVER case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesJcb): return CardNetwork.JCB case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesDinersClub): return CardNetwork.DINERSCLUB case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesVisa): return CardNetwork.VISA case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesMastercard): return CardNetwork.MASTERCARD case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesUnionPay): return CardNetwork.UNIONPAY case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesUzcard): return .UZCARD case hasAnyPrefix(cardNumber: cardNumber, prefixes: prefixesHumo): return .HUMO default: return CardNetwork.UNKNOWN } } /** Determines whether a card number belongs to any bank network according to their bin - Parameters: - cardNumber: The card number as a string - prefixes: The set of bin prefixes used with certain bank networks - Returns: `true` if card number belongs to a bank network, `false` otherwise */ static func hasAnyPrefix(cardNumber: String, prefixes: [String] ) -> Bool { return prefixes.filter { cardNumber.hasPrefix($0) }.count > 0 } //TODO: Will be replaced with `formatCardNumber` in future version public static func format(number: String) -> String { return formatCardNumber(cardNumber: number) } /** Returns the card number formatted for display - Parameter cardNumber: The card number as a string - Returns: The card number formatted */ public static func formatCardNumber(cardNumber: String) -> String { if cardNumber.count == maxPanLength { return format16(cardNumber: cardNumber) } else if cardNumber.count == maxPanLengthAmericanExpress { return format15(cardNumber: cardNumber) } else { return cardNumber } } /** Returns the card's expiration date formatted for display - Parameters: - expMonth: The expiration month as a string - expYear: The expiration year as a string - Returns: The card's expiration date formatted as MM/YY */ public static func formatExpirationDate(expMonth: String, expYear: String) -> String { var month = expMonth let year = "\(expYear.suffix(2))" if expMonth.count == 1 { month = "0\(expMonth)" } return "\(month)/\(year)" } static func format15(cardNumber: String) -> String { var displayNumber = "" for (idx, char) in cardNumber.enumerated() { if idx == 4 || idx == 10 { displayNumber += " " } displayNumber += String(char) } return displayNumber } static func format16(cardNumber: String) -> String { var displayNumber = "" for (idx, char) in cardNumber.enumerated() { if (idx % 4) == 0 && idx != 0 { displayNumber += " " } displayNumber += String(char) } return displayNumber } } //TODO: Added extension to make older network changes available, will remove in future version extension CreditCardUtils { public static func isVisa(number: String) -> Bool { return determineCardNetwork(cardNumber: number) == CardNetwork.VISA } public static func isAmex(number: String) -> Bool { return determineCardNetwork(cardNumber: number) == CardNetwork.AMEX } public static func isDiscover(number: String) -> Bool { return determineCardNetwork(cardNumber: number) == CardNetwork.DISCOVER } public static func isMastercard(number: String) -> Bool { return determineCardNetwork(cardNumber: number) == CardNetwork.MASTERCARD } public static func isUnionPay(number: String) -> Bool { return determineCardNetwork(cardNumber: number) == CardNetwork.UNIONPAY } }
38.612994
141
0.604068
bbd5ac7be394d920c960aa22e72e3b1c5db3ae4f
273
func modify<Value>(_ value: inout Value, _ modifier: (inout Value) throws -> Void) rethrows { try modifier(&value) } @discardableResult func with<Value>(_ value: Value, _ modifier: (Value) throws -> Void) rethrows -> Value { try modifier(value) return value }
27.3
93
0.692308
4bb228fcac6bef7c8a2afeed049b52ebdc492c9e
14,722
// // Request+AlamofireImage.swift // // Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(macOS) import Cocoa #endif extension DataRequest { static var acceptableImageContentTypes: Set<String> = [ "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-ms-bmp", "image/x-win-bitmap" ] #if swift(>=5) static let streamImageInitialBytePattern = Data([255, 216]) // 0xffd8 #else static let streamImageInitialBytePattern = Data(bytes: [255, 216]) // 0xffd8 #endif /// Adds the content types specified to the list of acceptable images content types for validation. /// /// - parameter contentTypes: The additional content types. public class func addAcceptableImageContentTypes(_ contentTypes: Set<String>) { DataRequest.acceptableImageContentTypes.formUnion(contentTypes) } // MARK: - iOS, tvOS and watchOS #if os(iOS) || os(tvOS) || os(watchOS) /// Creates a response serializer that returns an image initialized from the response data using the specified /// image options. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// /// - returns: An image response serializer. public class func imageResponseSerializer( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true) -> DataResponseSerializer<Image> { return DataResponseSerializer { request, response, data, error in let result = serializeResponseData(response: response, data: data, error: error) guard case let .success(data) = result else { return .failure(result.error!) } do { try DataRequest.validateContentType(for: request, response: response) let image = try DataRequest.image(from: data, withImageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .success(image) } catch { return .failure(error) } } } /// Adds a response handler to be called once the request has finished. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// This is set to the value of scale of the main screen by default, which /// automatically scales images for retina displays, for instance. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, /// which results in using `DispatchQueue.main`. /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 /// arguments: the URL request, the URL response, if one was received, the image, /// if one could be created from the URL response and data, and any error produced /// while creating the image. /// /// - returns: The request. @discardableResult public func responseImage( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true, queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Image>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server /// and converted into images. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// This is set to the value of scale of the main screen by default, which /// automatically scales images for retina displays, for instance. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 /// argument: the image, if one could be created from the data. /// /// - returns: The request. @discardableResult public func streamImage( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true, completionHandler: @escaping (Image) -> Void) -> Self { var imageData = Data() return stream { chunkData in if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { imageData = Data() } imageData.append(chunkData) if let image = DataRequest.serializeImage(from: imageData) { completionHandler(image) } } } private class func serializeImage( from data: Data, imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true) -> UIImage? { guard data.count > 0 else { return nil } do { let image = try DataRequest.image(from: data, withImageScale: imageScale) if inflateResponseImage { image.af_inflate() } return image } catch { return nil } } private class func image(from data: Data, withImageScale imageScale: CGFloat) throws -> UIImage { if let image = UIImage.af_threadSafeImage(with: data, scale: imageScale) { return image } throw AFIError.imageSerializationFailed } public class var imageScale: CGFloat { #if os(iOS) || os(tvOS) return UIScreen.main.scale #elseif os(watchOS) return WKInterfaceDevice.current().screenScale #endif } #elseif os(macOS) // MARK: - macOS /// Creates a response serializer that returns an image initialized from the response data. /// /// - returns: An image response serializer. public class func imageResponseSerializer() -> DataResponseSerializer<Image> { return DataResponseSerializer { request, response, data, error in let result = serializeResponseData(response: response, data: data, error: error) guard case let .success(data) = result else { return .failure(result.error!) } do { try DataRequest.validateContentType(for: request, response: response) } catch { return .failure(error) } guard let bitmapImage = NSBitmapImageRep(data: data) else { return .failure(AFIError.imageSerializationFailed) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .success(image) } } /// Adds a response handler to be called once the request has finished. /// /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 /// arguments: the URL request, the URL response, if one was received, the image, if /// one could be created from the URL response and data, and any error produced while /// creating the image. /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, /// which results in using `DispatchQueue.main`. /// /// - returns: The request. @discardableResult public func responseImage( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Image>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.imageResponseSerializer(), completionHandler: completionHandler ) } /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server /// and converted into images. /// /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 /// argument: the image, if one could be created from the data. /// /// - returns: The request. @discardableResult public func streamImage(completionHandler: @escaping (Image) -> Void) -> Self { var imageData = Data() return stream { chunkData in if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { imageData = Data() } imageData.append(chunkData) if let image = DataRequest.serializeImage(from: imageData) { completionHandler(image) } } } private class func serializeImage(from data: Data) -> NSImage? { guard data.count > 0 else { return nil } guard let bitmapImage = NSBitmapImageRep(data: data) else { return nil } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return image } #endif // MARK: - Content Type Validation /// Returns whether the content type of the response matches one of the acceptable content types. /// /// - parameter request: The request. /// - parameter response: The server response. /// /// - throws: An `AFError` response validation failure when an error is encountered. public class func validateContentType(for request: URLRequest?, response: HTTPURLResponse?) throws { if let url = request?.url, url.isFileURL { return } guard let mimeType = response?.mimeType else { let contentTypes = Array(DataRequest.acceptableImageContentTypes) throw AFError.responseValidationFailed(reason: .missingContentType(acceptableContentTypes: contentTypes)) } guard DataRequest.acceptableImageContentTypes.contains(mimeType) else { let contentTypes = Array(DataRequest.acceptableImageContentTypes) throw AFError.responseValidationFailed( reason: .unacceptableContentType(acceptableContentTypes: contentTypes, responseContentType: mimeType) ) } } }
44.343373
120
0.608137
f440fb1faa6053d29e9e29af78274bb4de9ea084
2,907
// // DetailMovieStarsLayoutManager.swift // KinoLenta // // Created by Dmitry Trifonov on 11.12.2021. // import Foundation import UIKit struct DetailMovieStarsLayoutManager: LayoutManager { typealias CellType = DetailMovieStarsCollectionViewCell func applyLayout(for cell: CellType, bounds: CGRect) { cell.primaryLabel.translatesAutoresizingMaskIntoConstraints = false cell.secondaryLabel.translatesAutoresizingMaskIntoConstraints = false cell.secondaryLabel.setContentCompressionResistancePriority(.defaultLow - 1, for: .horizontal) NSLayoutConstraint.activate([ cell.primaryLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor), cell.primaryLabel.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor), cell.secondaryLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor), cell.secondaryLabel.leadingAnchor.constraint( equalTo: cell.primaryLabel.trailingAnchor, constant: Consts .leadingMargin ), cell.secondaryLabel.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor), cell.secondaryLabel.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor) ]) } func calculateHeight(width: CGFloat, font: UIFont, text: String) -> CGFloat { return text.height(withWidth: width, font: font) } private enum Consts { static let leadingMargin: CGFloat = 20.0 } } struct DetailMovieStarsDescriptor: CollectionViewCellDescriptor { var cellClass: UICollectionReusableView.Type = DetailMovieStarsCollectionViewCell.self let primaryFont: UIFont let primaryTitle: String let secondaryFont: UIFont let secondaryTitle: String private let layoutManager = DetailMovieStarsLayoutManager() func sizeForItem(in collectionView: UICollectionView) -> CGSize { let width = collectionView.widthWithInsets let primaryWidth = primaryTitle.width(withHeight: .greatestFiniteMagnitude, font: primaryFont) let secondaryHeight = layoutManager.calculateHeight( width: width - primaryWidth, font: secondaryFont, text: secondaryTitle ) return CGSize(width: width, height: secondaryHeight) } func cell(in collectionView: UICollectionView, at indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) guard let cell = cell as? DetailMovieStarsCollectionViewCell else { fatalError("Invalid cell type") } cell.primaryLabel.text = primaryTitle cell.primaryLabel.font = primaryFont cell.secondaryLabel.text = secondaryTitle cell.secondaryLabel.font = secondaryFont return cell } }
36.797468
106
0.71173
9bd7ededa5f8159762651d4cb1207f594633130e
5,698
/* * Copyright (c) 2019, Nordic Semiconductor * 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. * * 3. Neither the name of the copyright holder 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. */ internal protocol SecureDFUPeripheralDelegate : DFUPeripheralDelegate { /** Callback called when DFU Control Point notifications were enabled successfully. */ func peripheralDidEnableControlPoint() /** Callback when Command Object Info has been received from the peripheral. - parameter maxLen: The maximum size of the Init Packet in bytes. - parameter offset: Number of bytes of Init Packet already sent, for example during last DFU operation. This resets to 0 on Create Command Object or when the DFU operation completes. - parameter crc: The CRC-32 calculated from the 'offset' bytes. This may be used to calculate if the stored Init packet matches the one being sent now. If crc matches the operation may be resumed, if not a new Command Object should be created and DFU should start over. */ func peripheralDidSendCommandObjectInfo(maxLen: UInt32, offset: UInt32, crc: UInt32) /** Callback when Data Object Info has been received from the peripheral. - parameter maxLen: The maximum size of a single data object in bytes. A firmware may be sent in multiple objects. - parameter offset: Number of bytes of data already sent (in total, not only the last object), for example during last DFU operation. Sending Create Data will rewind the offset to the last executed data object. This resets to 0 on Create Command Object or when the DFU operation completes. - parameter crc: The CRC-32 calculated from the 'offset' bytes. This may be used to calculate if the stored data matches the firmware being sent now. If crc matches the operation may be resumed, if not a new Command Object should be created and DFU should start over. */ func peripheralDidSendDataObjectInfo(maxLen: UInt32, offset: UInt32, crc: UInt32) /** Callback when Command Object was created. */ func peripheralDidCreateCommandObject() /** Callback when Data Object was created. */ func peripheralDidCreateDataObject() /** Callback when Packet Receipt Notifications were set or disabled. */ func peripheralDidSetPRNValue() /** Callback when init packet is sent. Actually this method is called when Init packet data were added to the outgoing buffer on iDevice and will be sent as soon as possible, not when the peripheral actually received them, as they are called with Write Without Response and no such callback is generated. */ func peripheralDidReceiveInitPacket() /** Callback when Checksum was received after sending Calculate Checksum request. - parameter offset: Number of bytes of the current objecy received by the peripheral. - parameter crc: CRC-32 calculated rom those received bytes. */ func peripheralDidSendChecksum(offset: UInt32, crc: UInt32) /** Callback when Execute Object command completes with status success. After receiving this callback the device may reset if the whole firmware was sent. */ func peripheralDidExecuteObject() /** Callback when the Command Object has been rejected by the target device by sending a Remote DFU Error, but the firmware contains a second part that the service should try to send. Perhaps the SoftDevice and Bootloader were sent before and the target rejects second update (bootloader can't be updated with one with the same FW version). Application update should succeeded in such case. - parameter error: The error that occurred. - parameter message: The error message. */ func peripheralRejectedCommandObject(withError error: DFUError, andMessage message: String) /** Callback when Data Object was successfully sent. */ func peripheralDidReceiveObject() }
46.325203
96
0.703405
aceb4ede25be72d9a536007d2da531a66b2edeb7
2,368
// // QueryBuilder.swift // SwifQLCore // // Created by Mihael Isaev on 19.12.2019. // import Foundation public protocol QueryBuilderItemable { var values: [SwifQLable] { get } } public struct QueryBuilderItem: SwifQLable { public let parts: [SwifQLPart] public let values: [SwifQLable] public init (_ values: [SwifQLable]? = nil) { var parts: [SwifQLPart] = [] if let values = values { values.forEach { parts.append(contentsOf: $0.parts) } } self.parts = parts self.values = values ?? [] } } @_functionBuilder public struct QueryBuilder { public typealias Block = () -> SwifQLable /// Builds an empty view from an block containing no statements, `{ }`. public static func buildBlock() -> SwifQLable { QueryBuilderItem() } /// Passes a single view written as a child view (e..g, `{ Text("Hello") }`) through unmodified. public static func buildBlock(_ attr: SwifQLable) -> SwifQLable { QueryBuilderItem([attr]) } /// Passes a single view written as a child view (e..g, `{ Text("Hello") }`) through unmodified. public static func buildBlock(_ attrs: SwifQLable...) -> SwifQLable { QueryBuilderItem(attrs) } /// Passes a single view written as a child view (e..g, `{ Text("Hello") }`) through unmodified. public static func buildBlock(_ attrs: [SwifQLable]) -> SwifQLable { QueryBuilderItem(attrs) } /// Provides support for "if" statements in multi-statement closures, producing an `Optional` view /// that is visible only when the `if` condition evaluates `true`. public static func buildIf(_ content: SwifQLable?) -> SwifQLable { guard let content = content else { return QueryBuilderItem() } return QueryBuilderItem([content]) } /// Provides support for "if" statements in multi-statement closures, producing /// ConditionalContent for the "then" branch. public static func buildEither(first: SwifQLable) -> SwifQLable { QueryBuilderItem([first]) } /// Provides support for "if-else" statements in multi-statement closures, producing /// ConditionalContent for the "else" branch. public static func buildEither(second: SwifQLable) -> SwifQLable { QueryBuilderItem([second]) } }
35.343284
102
0.646537
c19365ef3d4de7ed978a8faabf1e82359c36fcf2
4,302
// // SlowLogView.swift // redis-pro // // Created by chengpanwang on 2021/7/14. // import SwiftUI import Logging struct SlowLogView: View { @EnvironmentObject var redisInstanceModel:RedisInstanceModel @State private var slowerThan:Int = 10000 @State private var maxLen:Int = 128 @State private var size:Int = 50 @State private var total:Int = 0 @State private var datasource:[Any] = [SlowLogModel(), SlowLogModel()] @State private var selectIndex:Int? let logger = Logger(label: "slow-log-view") var body: some View { VStack(alignment: .leading, spacing: MTheme.V_SPACING) { // header HStack(alignment: .center, spacing: MTheme.H_SPACING) { FormItemInt(label: "Slower Than(us)", labelWidth: 120, value: $slowerThan, suffix: "square.and.pencil", onCommit: onSlowerThanAction, autoCommit: false) .help("REDIS_SLOW_LOG_SLOWER_THAN") .frame(width: 320) FormItemInt(label: "Max Len", value: $maxLen, suffix: "square.and.pencil", onCommit: onMaxLenAction, autoCommit: false) .help("REDIS_SLOW_LOG_MAX_LEN") .frame(width: 150) FormItemInt(label: "Size", value: $size, suffix: "square.and.pencil", onCommit: onSlowLogSizeChangeAction, autoCommit: true) .help("REDIS_SLOW_LOG_SIZE") .frame(width: 150) Spacer() MButton(text: "Reset", action: onSlowLogResetAction) .help("REDIS_SLOW_LOG_RESET") } SlowLogTable(datasource: $datasource, selectRowIndex: $selectIndex) // footer HStack(alignment: .center, spacing: MTheme.H_SPACING_L) { Spacer() Text("Total: \(total)") .font(.system(size: 12)) .help("REDIS_SLOW_LOG_TOTAL") Text("Current: \(datasource.count)") .font(.system(size: 12)) .help("REDIS_SLOW_LOG_SIZE") IconButton(icon: "arrow.clockwise", name: "Refresh", action: onRefreshAction) } .padding(EdgeInsets(top: 6, leading: 0, bottom: 6, trailing: 0)) }.onAppear { getSlowLog() getSlowLogMaxLen() getSlowLogSlowerThan() } } func onRefreshAction() -> Void { getSlowLog() getSlowLogMaxLen() getSlowLogSlowerThan() } func onSlowerThanAction() -> Void { logger.info("update slow log slower than: \(self.slowerThan)") let _ = self.redisInstanceModel.getClient().setConfig(key: "slowlog-log-slower-than", value: "\(maxLen)") } func onMaxLenAction() -> Void { logger.info("update slow log max len: \(self.maxLen)") let _ = self.redisInstanceModel.getClient().setConfig(key: "slowlog-max-len", value: "\(maxLen)") } func onSlowLogResetAction() -> Void { let _ = self.redisInstanceModel.getClient().slowLogReset().done({_ in self.getSlowLog() }) } func onSlowLogSizeChangeAction() -> Void { getSlowLog() } func getSlowLog() -> Void { let _ = self.redisInstanceModel.getClient().getSlowLog(self.size).done({ res in self.datasource = res }) let _ = self.redisInstanceModel.getClient().slowLogLen().done({ res in self.total = res }) } func getSlowLogMaxLen() -> Void { let _ = self.redisInstanceModel.getClient().getConfigOne(key: "slowlog-max-len").done({ res in self.maxLen = NumberHelper.toInt(res) }) } func getSlowLogSlowerThan() -> Void { let _ = self.redisInstanceModel.getClient().getConfigOne(key: "slowlog-log-slower-than").done({ res in self.slowerThan = NumberHelper.toInt(res) }) } } struct SlowLogView_Previews: PreviewProvider { static var redisInstanceModel:RedisInstanceModel = RedisInstanceModel(redisModel: RedisModel()) static var previews: some View { SlowLogView() .environmentObject(redisInstanceModel) } }
35.262295
168
0.578568
189a02012b7b68a4b4583810e2b29b1980edd54f
5,218
// // LX_NewFeatureViewController.swift // LX_WeiBo // // Created by 李lucy on 16/8/6. // Copyright © 2016年 com.muyandialog.Co.,Ltd. All rights reserved. // import UIKit import SnapKit class LX_NewFeatureViewController: UIViewController, UICollectionViewDataSource ,UICollectionViewDelegate{ let maxCount = 4 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.redColor() // Do any additional setup after loading the view. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return maxCount } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("NewFeatureCellID", forIndexPath: indexPath) as! LXCollectionViewCell cell.index = indexPath.item cell.startButton.hidden = true return cell } // MARK - UICollectionViewDelegate /** * 当一个cell完全显示完就会调用 */ func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { //1.获取当前展现在眼前的cell对应的cell let path = collectionView.indexPathsForVisibleItems().last! //2.根据索引获取当前展现在眼前的cell let cell = collectionView.cellForItemAtIndexPath(path) as! LXCollectionViewCell //3.判断是否是最后一页 if path.item == maxCount - 1 { cell.startButton.hidden = false cell.startButton.userInteractionEnabled = false cell.startButton.transform = CGAffineTransformMakeScale(0.0, 0.0) //动画 // usingSpringWithDamping 的范围为 0.0f 到 1.0f ,数值越小「弹簧」的振动效果越明显。 // initialSpringVelocity 则表示初始的速度,数值越大一开始移动越快, 值得注意的是,初始速度取值较高而时间较短时,也会出现反弹情况。 UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { cell.startButton.transform = CGAffineTransformIdentity }, completion: { (_) in cell.startButton.userInteractionEnabled = true }) } } } class LXCollectionViewCell: UICollectionViewCell { //保存图片的索引 var index: Int = 0 { didSet{ iconView.image = UIImage(named: "new_feature_\(index+1)") } } override init(frame: CGRect) { super.init(frame: frame) //初始化UI setUpUI() } required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) setUpUI() } private func setUpUI(){ //添加子控件 contentView.addSubview(iconView) contentView.addSubview(startButton) //布局子控件 // iconView.translatesAutoresizingMaskIntoConstraints = false // // var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[iconView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconView":iconView]) // // cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[iconView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconView": iconView]) // contentView.addConstraints(cons) //框架 iconView.snp_makeConstraints { (make) in // make.left.equalTo(0) // make.right.equalTo(0) // make.top.equalTo(0) // make.bottom.equalTo(0) make.edges.equalTo(0) } startButton.snp_makeConstraints { (make) in make.centerX.equalTo(contentView) make.bottom.equalTo(contentView.snp_bottom).offset(-160) } } @objc private func startBtnClick(){ LXLog("") } // MARK - 懒加载 //大图容器 private lazy var iconView = UIImageView() //开始按钮 private lazy var startButton: UIButton = { let btn = UIButton(type: UIButtonType.Custom) btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted) btn.addTarget(self, action: #selector(LXCollectionViewCell.startBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() } class LXFlowLayout: UICollectionViewFlowLayout { //准备布局 override func prepareLayout() { super.prepareLayout() itemSize = collectionView!.bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView?.bounces = false collectionView?.showsVerticalScrollIndicator = false collectionView?.showsHorizontalScrollIndicator = false collectionView?.pagingEnabled = true } }
31.817073
180
0.635684
4852a8165cc1f51acdc4f41eb9dcfc02f674f9d6
643
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "CodableGeoJSON", products: [ .library( name: "CodableGeoJSON", targets: ["CodableGeoJSON"]), ], dependencies: [ .package(url: "https://github.com/guykogus/CodableJSON.git", from: "1.2.0"), ], targets: [ .target( name: "CodableGeoJSON", dependencies: ["CodableJSON"], path: "CodableGeoJSON"), .testTarget( name: "CodableGeoJSONTests", dependencies: ["CodableGeoJSON"], path: "CodableGeoJSONTests"), ] )
24.730769
84
0.545879
fb758c717ac1640988765393f66c38718ddb852e
1,344
// // CountterButton.swift // kinderGardenCG // // Created by d182_Jorge_M on 16/06/18. // Copyright © 2018 none. All rights reserved. // import UIKit @IBDesignable class CountterButton: UIButton { private var halfWidth : CGFloat { return bounds.width / 2 } private var halfHeight : CGFloat{ return bounds.height / 2 } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { let path = UIBezierPath(ovalIn: rect) #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1).setFill() path.fill() let plusWidth: CGFloat = min(bounds.width, bounds.height) * 0.6 let halfPlusWidth = plusWidth / 2 let plusPath = UIBezierPath() plusPath.lineWidth = 3.0 plusPath.move(to: CGPoint(x: halfWidth - halfPlusWidth, y: halfHeight)) plusPath.addLine(to: CGPoint(x: halfWidth + halfPlusWidth, y: halfHeight)) plusPath.move(to: CGPoint(x: halfWidth, y: halfHeight - halfPlusWidth)) plusPath.addLine(to: CGPoint(x: halfWidth, y: halfHeight + halfPlusWidth)) UIColor.white.setStroke() plusPath.stroke() } }
29.217391
101
0.63244
e2bd5c4d5ba5fd4eb8c85e03b92d2557f5c37187
782
// Atom // // Copyright (c) 2019 Alaska Airlines // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public extension Atom.Response { /// Returns default, success response where status code is 200. static let success = Atom.Response(statusCode: 200) }
34
75
0.742967
e4870db04465d3f23f4c919dbef587812442429a
2,160
// // AppDelegate.swift // TypedTableView // // Created by Adam Śliwakowski on 20.12.2015. // Copyright © 2015 AdamSliwakowski. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.957447
285
0.756019
20ca40c0608668bad5ca5fcf1b6e6a28520337ce
1,660
// CommunicationsViewController.swift // UXSDKSwiftSample // // Created by Benjamin Ursel on 2018-05-23. // Copyright © 2018 DJI. All rights reserved. // import UIKit import Foundation import DJISDK import DJIUXSDK class CommunicationsViewController: UIViewController, UITextViewDelegate { //This is instantiated as a UIViewController as soon as app launches //The reference in appDelegate is reassigned every time the view launches //MARK: Properties @IBOutlet weak var DataDisplay: UITextView! open weak var appDelegate = UIApplication.shared.delegate as? AppDelegate //MARK: Methods override func viewDidLoad() { super.viewDidLoad() appDelegate?.communicationsViewController = self appDelegate?.productCommunicationManager.connectToProduct() appDelegate?.productCommunicationManager.connectedProduct = DJISDKManager.product() if (appDelegate?.productCommunicationManager.connectedProduct?.model != nil){ self.DataDisplay.text = (appDelegate?.productCommunicationManager.connectedProduct.model) } //This works and will register the manifold appDelegate?.osdkDevice = OnboardSDKDevice() appDelegate?.osdkDevice?.delegate = appDelegate?.osdkDevice } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: Actions @IBAction func back(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } //This doesn't update text until after the function has returned @IBAction func getData(_ sender: UIButton) { //Empty } }
31.923077
101
0.710843
f569f6500417f44339bd21b94f536b2cc7e0b4a6
244
// // ActivityLogger.swift // CoachKit // // Created by Keith Coughtrey on 11/07/15. // Copyright © 2015 Keith Coughtrey. All rights reserved. // import Foundation public protocol ActivityLogger { func addLogItem(_ message: String) }
17.428571
58
0.713115
3a6b9df5afe22fb8827f8bbfab05c0c443e48e86
625
// // EnergyReading.swift // IoTApp // // Created by Viraj Padte on 4/20/17. // Copyright © 2017 VirajPadte. All rights reserved. // import UIKit import AWSDynamoDB class EneryReading: AWSDynamoDBObjectModel,AWSDynamoDBModeling { var NodeID:String? var DataID:String? var Cost:String? var CreatedAt:String? var Reading:String? var Place:String? class func dynamoDBTableName() -> String { return "Energy" } class func hashKeyAttribute() -> String { return "NodeID" } class func rangeKeyAttribute() -> String { return "CreatedAt" } }
19.53125
64
0.6416
50f16ef201a3b06225c3dd241fc1c07b744de6ff
532
// // JournalEntryDetailFactory.swift // MFLHalsa // // Created by Alex Miculescu on 07/07/2017. // Copyright © 2017 Future Workshops. All rights reserved. // import Foundation class JournalEntryDetailFactory { class func wireframe() -> JournalEntryDetailWireframe { return JournalEntryDetailWireframeImplementation() } class func presenter(journalEntry: JournalEntry) -> JournalEntryDetailPresenter { return JournalEntryDetailPresenterImplementation(journalEntry: journalEntry) } }
24.181818
85
0.738722
ab422965bbc551615919da4fecb223a4009316f0
696
import Foundation public func run() { let options = Options.fromCommandLine() guard !options.help, !options.unknownOption, let manglerType = options.manglerType, let appDirectoryOrFile = options.appDirectoryOrFile else { print(Options.usage) if options.help { return } else { exit(EXIT_FAILURE) } } LOGGER = SoutLogger(options: options) let mangler = manglerType.resolveMangler(machOViewDoomEnabled: options.machOViewDoom) let obfuscator = Obfuscator(directoryOrFileURL: appDirectoryOrFile, mangler: mangler, options: options) obfuscator.run() }
33.142857
146
0.632184
e4448cb8e514ec36f68413cc01fed3d4ee5a6625
10,970
// // BLEManager.swift // smartdesk // // Created by Jing Wei Li on 10/10/18. // Copyright © 2018 Jing Wei Li. All rights reserved. // import Foundation import CoreBluetooth import UIKit /// Note: dispatch to the main thread when calling delegate methods. class BLEManager: NSObject { static let current = BLEManager() weak var delegate: BLEManagerDelegate? private var bluetoothManager: CBCentralManager! private var adc: CBPeripheral? private var adcDataPoint: CBCharacteristic? private let bleModuleUUID = CBUUID(string: "0xFFE0") private let bleCharacteristicUUID = CBUUID(string: "0xFFE1") // if the connection request last more than 5s, then let the delegate know of the timeout error. private let timeOutInterval: TimeInterval = 5.0 private var connectingTimeoutTimer: Timer? private var scanningTimeoutTimer: Timer? private var availableBLEs: Set<CBPeripheral> = Set() private override init() { super.init() bluetoothManager = CBCentralManager(delegate: self, queue: DispatchQueue.global(qos: .userInitiated)) } // MARK: - Instance methods func scan() { availableBLEs.removeAll() if bluetoothManager.state == .poweredOn { bluetoothManager.scanForPeripherals(withServices: [bleModuleUUID], options: nil) scanningTimeoutTimer = Timer.scheduledTimer( withTimeInterval: timeOutInterval, repeats: false) { [weak self] _ in self?.bluetoothManager.stopScan() self?.delegate?.didReceiveWarning?(warning: .scanningTimeout) } } else { DispatchQueue.main.async { [weak self] in if let strongSelf = self { strongSelf.delegate?.didReceiveError?(error: BLEError(managerState: strongSelf.bluetoothManager.state)) } } } } func connect(peripheral: CBPeripheral) { connectingTimeoutTimer = Timer.scheduledTimer( withTimeInterval: timeOutInterval, repeats: false) { [weak self] _ in self?.delegate?.didReceiveError?(error: BLEError.connectionTimeout) } bluetoothManager.connect(peripheral) } func disconnect() { if let peripheral = adc { bluetoothManager.cancelPeripheralConnection(peripheral) adc = nil adcDataPoint = nil DispatchQueue.main.async { [weak self] in self?.delegate?.didDisconnectFromPeripheral?() } } } func send(string: String) { guard let peripheral = adc, let characteristic = adcDataPoint else { print("Not ready to send data") delegate?.didReceiveError?(error: BLEError.inactiveConnection) return } // note: will not work using the .withResponse type peripheral.writeValue(string.data(using: String.Encoding.utf8)!, for: characteristic, type: .withoutResponse) } func send(colorCommand: String, color: UIColor) { guard let peripheral = adc, let characteristic = adcDataPoint else { print("Not ready to send data") delegate?.didReceiveError?(error: BLEError.inactiveConnection) return } // send 4 bytes of color information to the peripheral peripheral.writeValue(Data(BLEManager.generateByteArray(for: colorCommand, color: color)), for: characteristic, type: .withoutResponse) } /** * Read the signal strength of the BLE connection. The result is passed * in as a parameter in the delegate callback `didReceiveRSSIReading(reading:status:)`. */ func readSignalStrength() { adc?.readRSSI() } } extension BLEManager: CBCentralManagerDelegate { // MARK: - CBCentralManagerDelegate func centralManagerDidUpdateState(_ central: CBCentralManager) { handle(updatedState: central.state) } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { print(peripheral.debugDescription) // if you rename the ble module, there will be a newline. Be sure to remove it availableBLEs.insert(peripheral) scanningTimeoutTimer?.invalidate() DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.delegate?.didDiscoverDoors?( doors: Array(strongSelf.availableBLEs) .compactMap { Door(peripheral: $0, prefetchedDoors: DoorsAPI.prefetchedDoors) }) } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("Connected") adc = peripheral adc?.delegate = self adc?.discoverServices([bleModuleUUID]) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { if let error = error { DispatchQueue.main.async { [weak self] in print(error.localizedDescription) self?.delegate?.didReceiveError?(error: BLEError.peripheralDisconnected) } } } func handle(updatedState state: CBManagerState) { DispatchQueue.main.async { [weak self] in switch state { case .poweredOff: print("BLE Manager Powered off State") self?.delegate?.didReceiveError?(error: BLEError.bluetoothOff) case .poweredOn: print("BLE Manager Powered on State") self?.delegate?.didAuthorize?() default: if let error = BLEError(managerState: state) { self?.delegate?.didReceiveError?(error: error) } } } } } extension BLEManager: CBPeripheralDelegate { // MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { return } guard let service = services.first, services.count == 1 else { delegate?.didReceiveError?(error: NSError(domain: "Should only have 1 service or no service discovered", code: 0, userInfo: [:])) return } peripheral.discoverCharacteristics([bleCharacteristicUUID], for: service) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard error == nil else { DispatchQueue.main.async { [weak self] in self?.delegate?.didReceiveError?(error: error) } return } guard let characteristics = service.characteristics, let dataPoint = characteristics.first, characteristics.count == 1 else { delegate?.didReceiveError?(error: BLEError.unexpected) return } adcDataPoint = dataPoint // at this point, cancel the timeout error message connectingTimeoutTimer?.invalidate() // listen for values sent from the BLE module adc?.setNotifyValue(true, for: dataPoint) DispatchQueue.main.async { [weak self] in self?.delegate?.readyToSendData?() } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let data = characteristic.value { let byteArray = [UInt8](data) // Arduino Serial string encoding is ascii // this can only receive 4 bytes at a time (4 characters) if let asciiStr = String(bytes: byteArray, encoding: String.Encoding.ascii) { DispatchQueue.main.async { [weak self] in print(asciiStr) let strippedString = asciiStr.trimmingCharacters(in: .whitespacesAndNewlines) if let error = BLEError(errorMessage: strippedString) { self?.delegate?.didReceiveError?(error: error) } else { self?.delegate?.didReceiveMessage?(message: strippedString) } } } } } func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { guard error == nil else { delegate?.didReceiveError?(error: error) return } let dbm = RSSI.intValue DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.delegate?.didReceiveRSSIReading?(reading: BLESignalStrength(rssi: dbm)) } } } extension BLEManager { // MARK: - Utilities /** * Convert to a string with letters (e.g. `"AB"`) from an ascii string such as * `"65\r\n66\r\n10"`. * - Use this method when processing strings from the serial monitor * - parameter asciiStr: String in ascii number form, separeted by \r\n */ class func string(ascii asciiStr: String) -> String { let asciiArr = asciiStr.components(separatedBy: "\r\n") print(asciiArr) // remove the 10 and empty string return asciiArr .filter { $0 != "10" && $0 != "" } .map { element -> String in guard let asciiNum = Int(element), let unicodeScalar = UnicodeScalar(asciiNum) else { return "" } return "\(Character(unicodeScalar))" } .joined().trimmingCharacters(in: .whitespacesAndNewlines) } /** * Generate 4 bytes of data with the first byte being the command and last 3 bytes being the rgb values. * - parameter command: the command used to send the indicate what this byte arr is for * - parameter color: the color to send */ class func generateByteArray(for command: String, color: UIColor) -> [UInt8] { var bytesToSend = [UInt8]() // add the ascii representation of the command to array bytesToSend.append(UInt8(command.unicodeScalars.first!.value)) // append the respective rgb values to byte array var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0 color.getRed(&red, green: &green, blue: &blue, alpha: nil) bytesToSend.append(UInt8(red * 255)) bytesToSend.append(UInt8(green * 255)) bytesToSend.append(UInt8(blue * 255)) return bytesToSend } }
38.491228
141
0.60155
e45ed859c3bf3eeeb01d90f6a64aabe9aac19f53
201
// // StagesViewTypes.swift // MFL-Common // // Created by Alex Miculescu on 16/02/2018. // struct StagesStepViewData { let imageName : String let title : String? let detail: String? }
15.461538
44
0.656716
6206c0004c75adc7dee864e9a70c3921ff91e03f
755
import XCTest import GiniReoTestProject class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
26.034483
111
0.605298
895dea74cd624dc6c153530ebcf20b7a771414b1
152
let words: [String] = ["Hello", "My", "Name", "Is", "Bhavneet", "Singh"] let result = words.reduce(""){ return $0 + " " + $1 } print(words, result)
25.333333
72
0.552632
212d13695b7999ccd70ceadf52e68b2a59b20991
3,632
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation /// The `ModelKey` protocol is used to decorate Swift standard's `CodingKey` enum with /// query functions and operators that are used to build query conditions. /// /// ``` /// let post = Post.keys /// /// Amplify.DataStore.query(Post.self, where: { /// post.title.contains("[Amplify]") /// .and(post.content.ne(nil)) /// }) /// ``` /// /// **Using Operators:** /// /// The operators on a `ModelKey` reference are defined so queries can also be written /// with Swift operators as well: /// /// ``` /// let post = Post.keys /// /// Amplify.DataStore.query(Post.self, where: { /// post.title ~= "[Amplify]" && /// post.content != nil /// }) /// ``` public protocol ModelKey: CodingKey, CaseIterable, QueryFieldOperation {} extension CodingKey where Self: ModelKey { // MARK: - beginsWith public func beginsWith(_ value: String) -> QueryPredicateOperation { return field(stringValue).beginsWith(value) } // MARK: - between public func between(start: Persistable, end: Persistable) -> QueryPredicateOperation { return field(stringValue).between(start: start, end: end) } // MARK: - contains public func contains(_ value: String) -> QueryPredicateOperation { return field(stringValue).contains(value) } public static func ~= (key: Self, value: String) -> QueryPredicateOperation { return key.contains(value) } // MARK: - eq public func eq(_ value: Persistable?) -> QueryPredicateOperation { return field(stringValue).eq(value) } public func eq(_ value: EnumPersistable) -> QueryPredicateOperation { return field(stringValue).eq(value) } public static func == (key: Self, value: Persistable?) -> QueryPredicateOperation { return key.eq(value) } public static func == (key: Self, value: EnumPersistable) -> QueryPredicateOperation { return key.eq(value) } // MARK: - ge public func ge(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).ge(value) } public static func >= (key: Self, value: Persistable) -> QueryPredicateOperation { return key.ge(value) } // MARK: - gt public func gt(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).gt(value) } public static func > (key: Self, value: Persistable) -> QueryPredicateOperation { return key.gt(value) } // MARK: - le public func le(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).le(value) } public static func <= (key: Self, value: Persistable) -> QueryPredicateOperation { return key.le(value) } // MARK: - lt public func lt(_ value: Persistable) -> QueryPredicateOperation { return field(stringValue).lt(value) } public static func < (key: Self, value: Persistable) -> QueryPredicateOperation { return key.lt(value) } // MARK: - ne public func ne(_ value: Persistable?) -> QueryPredicateOperation { return field(stringValue).ne(value) } public func ne(_ value: EnumPersistable) -> QueryPredicateOperation { return field(stringValue).ne(value) } public static func != (key: Self, value: Persistable?) -> QueryPredicateOperation { return key.ne(value) } public static func != (key: Self, value: EnumPersistable) -> QueryPredicateOperation { return key.ne(value) } }
26.705882
90
0.641795
392dc0224c76137d96bf3150a985370a33bd7e41
150
// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s // REQUIRES: asserts let bounds: Range#^A^#
30
104
0.72
90933c7c832420813920ce9a63876ba1cd8f64bd
3,775
// // File.swift // // // Created by Thomas Ricouard on 30/04/2020. // import Foundation import JavaScriptCore import Combine public class TurnipPredictionsService: ObservableObject { public static let shared = TurnipPredictionsService() @Published public var predictions: TurnipPredictions? public var fields: TurnipFields? { didSet { refresh() } } public var enableNotifications: Bool? public var turnipProhetUrl: URL? { guard let fields = fields, !fields.buyPrice.isEmpty else { return nil } var base = "https://turnipprophet.io/?prices=\(fields.buyPrice)." for field in fields.fields { base += field.isEmpty ? "." : "\(field)." } base += "&first=false&pattern=-1&achelper" return URL(string: base) } public var currentDate = Date() private var turnipsCancellable: AnyCancellable? private lazy var calculatorContext: JSContext? = { guard let url = Bundle.module.url(forResource: "turnips", withExtension: "js"), let script = try? String(contentsOf: url) else { return nil } let context = JSContext() context?.evaluateScript(script) return context }() private init() { turnipsCancellable = $predictions .subscribe(on: RunLoop.main) .sink { predictions in if let predictions = predictions { if self.enableNotifications == true { NotificationManager.shared.registerTurnipsPredictionNotification(prediction: predictions) } else if self.enableNotifications == false { NotificationManager.shared.removePendingNotifications() } } } self.fields = TurnipFields.decode() self.refresh() } private func refresh() { if let fields = fields, !fields.buyPrice.isEmpty { self.predictions = calculate(values: fields) } else { self.predictions = nil } } private func calculate(values: TurnipFields) -> TurnipPredictions { let call = "calculate([\(values.buyPrice),\(values.fields.filter{ !$0.isEmpty }.joined(separator: ","))])" let results = calculatorContext?.evaluateScript(call) let averagePrices: [Int]? = (results?.toDictionary()["avgPattern"] as? [Int])? .enumerated() .map({ index, value in guard let enteredValue = Int(values.fields[index]) else { return value } return enteredValue }) let minMax: [[Int]]? = (results?.toDictionary()["minMaxPattern"] as? [[Int]])? .enumerated() .map({ index, value in guard let enteredValue = Int(values.fields[index]) else { return value } return [enteredValue, enteredValue] }) var averageProfits: [Int]? if let averagePrices = averagePrices, values.amount > 0, let buyPrice = Int(values.buyPrice) { averageProfits = [] let investment = values.amount * buyPrice for avg in averagePrices { averageProfits?.append((avg * values.amount) - investment) } } return TurnipPredictions(minBuyPrice: results?.toDictionary()["minWeekValue"] as? Int, averagePrices: averagePrices, minMax: minMax, averageProfits: averageProfits, currentDate: currentDate) } }
34.318182
114
0.554437
0143f1253cd61fe8e5915c8396b918a79a6be51d
1,179
// // Extension + AddShadow.swift // Swift Support Codes // // Created by Shyngys Kuandyk on 2/17/20. // Copyright © 2020 Shyngys Kuandyk. All rights reserved. // import Foundation import UIKit extension UIView { // OUTPUT 1 func dropShadow(scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: -1, height: 1) layer.shadowRadius = 1 layer.shadowPath = UIBezierPath(rect: bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } // OUTPUT 2 func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowOffset = offSet layer.shadowRadius = radius layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } }
30.230769
116
0.644614
f9466ff4f792295159da1028df8bcf545a179791
291
// // AccountManager.swift // Manager // // Created by 张伟 on 2018/3/13. // Copyright © 2018年 zevwings. All rights reserved. // /// 1. 账号登录,自动登录 /// 2. 账号相关数据获取 /// 3. 账号权限相关数据获取 public struct AccountManager { public static let manager = AccountManager() init() {} }
14.55
52
0.618557
d5371cea5ca68ce6543deb6420065e2a0d2bcedf
4,294
// // PlaceDetailsCommentsTableViewCell.swift // Travelling // // Created by Dimitri Strauneanu on 08/10/2020. // import Foundation import UIKit protocol PlaceDetailsCommentsTableViewCellDelegate: AnyObject { func placeDetailsCommentsTableViewCell(_ cell: PlaceDetailsCommentsTableViewCell?, didSelectComments button: UIButton?) } class PlaceDetailsCommentsTableViewCell: UITableViewCell { weak var containerView: UIStackView! weak var commentsButton: UIButton! weak var timeButton: UIButton! weak var delegate: PlaceDetailsCommentsTableViewCellDelegate? convenience init() { self.init(style: .default, reuseIdentifier: PlaceDetailsCommentsTableViewCell.defaultReuseIdentifier) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setupSubviews() self.setupSubviewsConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setComments(comments: NSAttributedString?) { self.commentsButton?.setAttributedTitle(comments, for: .normal) } func setTime(time: NSAttributedString?) { self.timeButton?.setAttributedTitle(time, for: .normal) } } // MARK: - Subviews configuration extension PlaceDetailsCommentsTableViewCell { private func setupSubviews() { self.setupContentView() self.setupContainerView() self.setupCommentsButton() self.setupTimeButton() } private func setupContentView() { self.selectionStyle = .none self.backgroundColor = PlaceDetailsStyle.shared.commentsCellModel.backgroundColor } private func setupContainerView() { let view = UIStackView() view.translatesAutoresizingMaskIntoConstraints = false view.axis = .horizontal view.distribution = .fillEqually view.spacing = PlaceDetailsStyle.shared.commentsCellModel.buttonSpacing self.contentView.addSubview(view) self.containerView = view } private func setupCommentsButton() { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.tintColor = PlaceDetailsStyle.shared.commentsCellModel.tintColor button.setImage(PlaceDetailsStyle.shared.commentsCellModel.commentsImage, for: .normal) button.setContentSpacing(PlaceDetailsStyle.shared.commentsCellModel.buttonSpacing) button.addTarget(self, action: #selector(PlaceDetailsCommentsTableViewCell.touchUpInsideCommentsButton), for: .touchUpInside) self.containerView?.addArrangedSubview(button) self.commentsButton = button } private func setupTimeButton() { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.tintColor = PlaceDetailsStyle.shared.commentsCellModel.tintColor button.setImage(PlaceDetailsStyle.shared.commentsCellModel.timeImage, for: .normal) button.isUserInteractionEnabled = false button.setContentSpacing(PlaceDetailsStyle.shared.commentsCellModel.buttonSpacing) self.containerView?.addArrangedSubview(button) self.timeButton = button } } // MARK: - Actions extension PlaceDetailsCommentsTableViewCell { @objc func touchUpInsideCommentsButton() { self.delegate?.placeDetailsCommentsTableViewCell(self, didSelectComments: self.commentsButton) } } // MARK: - Constraints configuration extension PlaceDetailsCommentsTableViewCell { private func setupSubviewsConstraints() { self.setupContainerViewConstraints() } private func setupContainerViewConstraints() { NSLayoutConstraint.activate([ self.containerView.topAnchor.constraint(equalTo: self.contentView.topAnchor), self.containerView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -30), self.containerView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 30), self.containerView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -30) ]) } }
36.700855
133
0.728924
db49c4f6095c979d7ca4887fd53dd4b3f6b90611
2,656
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: protoex.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import ChronoxorFbe // Fast Binary Encoding OrderMessage model public class OrderMessageModel: Model { public let model: FieldModelOrderMessage public override init(buffer: Buffer = Buffer()) { model = FieldModelOrderMessage(buffer: buffer, offset: 4) super.init(buffer: buffer) } // Model size public func fbeSize() -> Int { model.fbeSize + model.fbeExtra } // Model type public var fbeType: Int = fbeTypeConst static let fbeTypeConst: Int = FieldModelOrderMessage.fbeTypeConst // Check if the struct value is valid public func verify() -> Bool { if buffer.offset + model.fbeOffset - 4 > buffer.size { return false } let fbeFullSize = Int(readUInt32(offset: model.fbeOffset - 4)) if fbeFullSize < model.fbeSize { return false } return model.verify() } // Create a new model (begin phase) public func createBegin() throws -> Int { return try buffer.allocate(size: 4 + model.fbeSize) } // Create a new model (end phase) public func createEnd(fbeBegin: Int) -> Int { let fbeEnd = buffer.size let fbeFullSize = fbeEnd - fbeBegin write(offset: model.fbeOffset - 4, value: UInt32(fbeFullSize)) return fbeFullSize } // Serialize the struct value public func serialize(value: OrderMessage) throws -> Int { let fbeBegin = try createBegin() try model.set(value: value) return createEnd(fbeBegin: fbeBegin) } // Deserialize the struct value public func deserialize() -> OrderMessage { var value = OrderMessage(); _ = deserialize(value: &value); return value } public func deserialize(value: inout OrderMessage) -> Int { if buffer.offset + model.fbeOffset - 4 > buffer.size { value = OrderMessage() return 0 } let fbeFullSize = Int(readUInt32(offset: model.fbeOffset - 4)) if fbeFullSize < model.fbeSize { assertionFailure("Model is broken!") value = OrderMessage() return 0 } value = model.get(fbeValue: &value) return fbeFullSize } // Move to the next struct value public func next(prev: Int) { model.fbeShift(size: prev) } }
32
122
0.592997
f7413db7ec278fd4909bd794e2028ad96e23e4fc
590
import WebErrorKit import ShellKit /// Extension with commands public struct Docker { public enum DockerError: String, WebError { case unsupportedPlatform public var statusCode: Int { return 412 } } let shell: Shell init(_ shell: Shell) { self.shell = shell } } extension Shell { public var docker: Docker { return Docker(self) } } extension Docker { public var commandBuilder: DockerCommand { return DockerCommand() } }
13.72093
47
0.545763
f86885fe2d13d62494212c9b6918998207491291
757
// // NetworkConfiguration.swift // SwiftTrader // // Created by Lobanov Dmitry on 23.02.17. // Copyright © 2017 OpenSourceIO. All rights reserved. // import Foundation public struct Configuration { public var serverAddress = "" public var apiAccessKey = "" // fileprivate static var apiServerAddress = "https://www.omdbapi.com/" // // public init(serverAddress: String, apiAccessKey: String) { // self.serverAddress = serverAddress // self.apiAccessKey = apiAccessKey // } // public static func api(apiAccessKey: String) -> Configuration { // return self.init(serverAddress: apiServerAddress, apiAccessKey: apiAccessKey) // } public init() {} public weak var headersProvider: HeadersProvider? }
30.28
87
0.688243
f50efe9a570d20147b354ab3960db77c8f06f2d8
817
// // Dictionary+Extractable.swift // Outlaw // // Created by Brian Mullen on 11/5/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import Foundation extension Dictionary: Extractable { public func optionalAny(for key: Outlaw.Key) -> Any? { guard let aKey = key as? Key else { return nil } return self[aKey] } } extension NSDictionary: Extractable { public func any(for key: Outlaw.Key) throws -> Any { guard let value: Any = self.value(forKeyPath: key.outlawKey) else { throw OutlawError.keyNotFound(key: key) } if let _ = value as? NSNull { throw OutlawError.nullValueWithKey(key: key) } return value } public func optionalAny(for key: Outlaw.Key) -> Any? { return self[key] } }
24.029412
75
0.615667
f9cb9bb5de2ca8a1eb91543ffe99208eb771e7c2
9,141
// // Step3MakeAClockController.swift // Climate Clock // // Created by Matt Frohman on 11/7/20. // Copyright © 2020 Matthew Frohman. All rights reserved. // // Attach the HAT and battery import UIKit class Step3MakeAClockController: UITableViewController { var images = [UIImage(named: "Step3Materials"), UIImage(named: "Step3Middle"), UIImage(named: "Step3Finished")] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Create header view tableView.tableHeaderView = HelperMethods.createHeaderView(title: "Attach the HAT and battery") // Set up navbar navigation let (left, home, right) = HelperMethods.createNavigationButtons(item: self.navigationItem, vc: self) left.action = #selector(goBack) home.action = #selector(goHome) right.action = #selector(goNext) // Set up "next" and "back" button let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 140)) tableView.tableFooterView = footerView // Initialize next/back let (next, back) = HelperMethods.createBackAndNext(view: tableView!.tableFooterView!) back.addTarget(self, action: #selector(goBack), for: .touchUpInside) next.addTarget(self, action: #selector(goNext), for: .touchUpInside) } /** Used for popping the View Controller to the home screen. */ @objc func goHome() { navigationController?.popToRootViewController(animated: true) } /// Displays a full-screen image based on a tap. /// - parameter sender: The UITapGestureRecognizer from a user tap. @objc func imageTapped(_ sender: UITapGestureRecognizer) { let previewVC = storyboard!.instantiateViewController(withIdentifier: "FullScreenHelper") as! FullScreenHelper previewVC.image = (sender.view as! UIImageView).image let navVC = UINavigationController() navVC.modalPresentationStyle = .fullScreen navVC.viewControllers = [previewVC] self.present(navVC, animated: true, completion: nil) } /** Advances the current View Controller to the first instructional page. */ @objc func goNext() { let vc = storyboard?.instantiateViewController(withIdentifier: "4") navigationController?.pushViewController(vc!, animated: true) // Update saved state UserDefaults.standard.set(5, forKey: "page") } /** Returns the current View Controller to the first instructional page. */ @objc func goBack() { // Remove saved states UserDefaults.standard.set(3, forKey: "page") navigationController?.popViewController(animated: true) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } return 3 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 { return "Steps:" } else { return "" } } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if section != 0 { let label = view as! UITableViewHeaderFooterView label.textLabel?.font = UIFont(name: "Raleway-Medium", size: 22) label.textLabel?.numberOfLines = 0 label.textLabel?.textAlignment = .center label.textLabel?.textColor = .black } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section != 0 { return 60 } else { return 0 } } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section != 0 { return 40 } else { return 0 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 && indexPath.section == 0 { // First image return images[0]!.aspectRatio() * (view.bounds.width - 50) } else if indexPath.section == 1 && indexPath.row == 1 { // Second Image return images[1]!.aspectRatio() * (view.bounds.width - 50) } else if indexPath.section == 1 && indexPath.row == 2 { // Third Image return images[2]!.aspectRatio() * (view.bounds.width - 50) } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let attributedString = NSMutableAttributedString() // Show banner let iv = UIImageView(frame: CGRect(x: 10, y: 0, width: view.bounds.width - 20, height: view.bounds.width - 60)) iv.contentMode = .scaleAspectFit iv.tag = 64 iv.isUserInteractionEnabled = true iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:)))) cell.selectionStyle = .none cell.isUserInteractionEnabled = true // Configure banner if indexPath.section == 0 && indexPath.row == 0 { // First Image iv.image = images[0] cell.contentView.addSubview(iv) cell.contentView.clipsToBounds = true } else if indexPath.section == 1 && indexPath.row == 1 { // Second Image iv.image = images[1] cell.contentView.addSubview(iv) cell.contentView.clipsToBounds = true } else if indexPath.section == 1 && indexPath.row == 2 { // Third Image iv.image = images[2] cell.contentView.addSubview(iv) cell.contentView.clipsToBounds = true } else { cell.imageView?.image = nil cell.contentView.viewWithTag(64)?.removeFromSuperview() } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 // Whatever line spacing you want in points // Set string if indexPath.section == 0 && indexPath.row == 1 { attributedString.mutableString.setString(paragraphs[0]) attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length)) cell.textLabel?.attributedText = attributedString cell.textLabel?.textColor = .darkGray } else if indexPath.section == 1 && indexPath.row == 0 { attributedString.mutableString.setString(paragraphs[1]) attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length)) cell.textLabel?.attributedText = attributedString cell.textLabel?.textColor = .black } else { cell.textLabel?.attributedText = nil cell.textLabel?.textColor = .darkGray } // Configuring general cell layouts cell.layoutMargins = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: -30) cell.textLabel?.numberOfLines = 0 cell.textLabel?.textAlignment = .left if indexPath.section == 0 && indexPath.row == 1 { cell.textLabel?.font = UIFont(name: "Raleway-Regular", size: 16) } else { cell.textLabel?.font = UIFont(name: "Raleway-Regular", size: 17) } return cell } var paragraphs = ["Materials: \n \u{2022} Raspberry Pi 3 Model B+\n \u{2022} Fully-assembled RGB Matrix HAT\n \u{2022} CR1220 3V battery\n \u{2022} Brass M2.5 Standoffs for Pi HATs (optional)\n\nThe Raspberry Pi does not, by itself, have a way to remember the date and time while switched off, but the HAT provides this capability with a small quartz crystal clock powered by a battery. When attached to the GPIO pins of the Pi, the HAT will also supply the Pi with power.", "\u{2022} Screw the optional standoffs to the HAT for stability and plug its 40-pin header to the 40 GPIO (general-purpose input/output) pins on the Raspberry Pi. Insert the coin cell battery with its + side facing up."] /* // 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.destination. // Pass the selected object to the new view controller. } */ }
41.175676
699
0.630128
ef9d8425ce7c4faace378f495bb9b8b078e3444e
2,803
// // PrinterListCellViewModel.swift // OctoPhone // // Created by Josef Dolezal on 27/02/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import ReactiveSwift import Icons import class UIKit.UIImage /// Cell inputs protocol PrinterListCellViewModelInputs { } /// Cell logic outputs protocol PrinterListCellViewModelOutputs { /// Name of stored printer var printerName: Property<String> { get } /// URL of printer var printerURL: Property<String> { get } /// Image of printer stream var printerStream: Property<UIImage?> { get } } /// View model for printer list cell protocol PrinterListCellViewModelType { /// Available inputs var inputs: PrinterListCellViewModelInputs { get } /// Available outputs var outputs: PrinterListCellViewModelOutputs { get } } /// View model for printer list cell final class PrinterListCellViewModel: PrinterListCellViewModelInputs, PrinterListCellViewModelOutputs, PrinterListCellViewModelType { var inputs: PrinterListCellViewModelInputs { return self } var outputs: PrinterListCellViewModelOutputs { return self } // MARK: Outputs let printerName: Property<String> let printerURL: Property<String> let printerStream: Property<UIImage?> // MARK: Private properties /// Octoprint requests provider private let provider = StaticContentProvider() /// Holds current value of stream illustration private let streamProperty = MutableProperty<UIImage?>(PrinterListCellViewModel.imageForIcon(.questionIcon)) init(printer: Printer) { self.printerName = Property(value: printer.name) self.printerURL = Property(value: printer.url.absoluteString) self.printerStream = Property(capturing: streamProperty) if let url = printer.streamUrl { requestStreamImage(url: url) } } /// Requests stream photo from given URL /// /// - Parameter url: URL of streamg private func requestStreamImage(url: URL) { provider.request(.get(url)) .filterSuccessfulStatusCodes() .startWithResult { [weak self] result in switch result { case let .success(response): self?.streamProperty.value = UIImage(data: response.data) case .failure: self?.streamProperty.value = PrinterListCellViewModel.imageForIcon(.minusSignIcon) } } } /// Creates preconfigured image from given icon /// /// - Parameter icon: Icon to be converted to image /// - Returns: New image generated from icon private static func imageForIcon(_ icon: FontAwesomeIcon) -> UIImage { return icon.image(ofSize: CGSize(width: 100, height: 100), color: Colors.Pallete.greyHue3) } }
29.197917
113
0.692472
69989f1cfd5a3e6416b61db71cc6e44f76746215
2,355
// // NotesFontProvider.swift // NotesTextView // // Created by Rimesh Jotaniya on 29/05/20. // Copyright © 2020 Rimesh Jotaniya. All rights reserved. // import UIKit class NotesFontProvider{ static let shared = NotesFontProvider() lazy var titleFont = UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont.systemFont(ofSize: 24, weight: .bold)) lazy var headingFont = UIFontMetrics(forTextStyle: .headline).scaledFont(for: UIFont.systemFont(ofSize: 20, weight: .bold)) lazy var bodyFont = UIFont.preferredFont(forTextStyle: .body) lazy var serifFont: UIFont = { getSerifFont() }() private init(){ NotificationCenter.default.addObserver(self, selector: #selector(fontSizeChanged), name: UIContentSizeCategory.didChangeNotification, object: nil) } @objc private func fontSizeChanged(){ titleFont = UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont.systemFont(ofSize: 24, weight: .bold)) headingFont = UIFontMetrics(forTextStyle: .headline).scaledFont(for: UIFont.systemFont(ofSize: 20, weight: .bold)) bodyFont = UIFont.preferredFont(forTextStyle: .body) serifFont = getSerifFont() } private func getSerifFont() -> UIFont { // if let serfFontDescriptor = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 17)).fontDescriptor.withDesign(.serif){ // let serifFont = UIFont(descriptor: serfFontDescriptor, size: 0) // return serifFont // } else{ // return .systemFont(ofSize: 10) // } // if we use system serif fonts i.e. fontDescriptor.withDesign(.serif) // then when retrieving the font back from CoreData, serif font wasn't identifiable. It might be a bug because of relatively new API and might get resolved in near future. // if we use named font then the same font is identifiable. // However Apple Discourages use of named font in WWDC 2019 - Font Management and Text Scaling // https://developer.apple.com/videos/play/wwdc2019/227/ if let georgiaFont = UIFont(name: "Georgia", size: 18){ return UIFontMetrics(forTextStyle: .body).scaledFont(for: georgiaFont) } else { return bodyFont } } }
39.915254
179
0.664119
116a5c9e4aca5f115318c6f0a87ad652cfd49876
2,035
// // Copyright © 2022 Alexander Romanov // SectionView.swift // import SwiftUI public struct SectionView<Content: View>: View { private let content: Content private let title: String private let verticalPadding: Space public init(_ title: String = "", verticalPadding: Space = .xxSmall, @ViewBuilder content: () -> Content) { self.title = title self.verticalPadding = verticalPadding self.content = content() } private enum Constants { /// Radius static var radiusMedium: CGFloat { Radius.medium.rawValue } static var radiusSmall: CGFloat { Radius.small.rawValue } } public var body: some View { VStack(alignment: .leading, spacing: Space.xSmall.rawValue) { if title != "" { Text(title) .fontStyle(.subtitle1) .foregroundColor(.onBackgroundHighEmphasis) .padding(.leading, .xxxSmall) } Surface { content .padding(.vertical, verticalPadding) } .controlPadding(.zero) .clipShape( RoundedRectangle(cornerRadius: Constants.radiusMedium, style: .circular) ) } .paddingContent(.horizontal) .padding(.vertical, Space.small) } } struct SectionView_Previews: PreviewProvider { static var previews: some View { VStack(spacing: .zero) { SectionView("App") { Row("Label", leadingType: .icon(.user), paddingHorizontal: .medium) } SectionView("Feedback") { VStack(spacing: .zero) { Row("Label", leadingType: .icon(.user), paddingHorizontal: .medium) Row("Label", leadingType: .icon(.user), paddingHorizontal: .medium) } } Spacer() } .background(Color.backgroundSecondary.ignoresSafeArea(.all)) } }
29.926471
111
0.549386
2947e1e384eff5a7db120a9df35bc6fc3e6b7ba7
654
// Source: http://stackoverflow.com/a/3732812/1123156 extension UIView { func firstAvailableUIViewController() -> UIViewController? { // convenience function for casting and to "mask" the recursive function return traverseResponderChainForUIViewController() } func traverseResponderChainForUIViewController() -> UIViewController? { if let nextUIViewController = next as? UIViewController { return nextUIViewController } else if let nextUIView = next as? UIView { return nextUIView.traverseResponderChainForUIViewController() } else { return nil } } }
34.421053
80
0.681957
dd55bf8ae74c0569a2eb92a7b9a5626076081a3f
66,622
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that iterates over a collection using its indices. /// /// The `IndexingIterator` type is the default iterator for any collection that /// doesn't declare its own. It acts as an iterator by using a collection's /// indices to step over each value in the collection. Most collections in the /// standard library use `IndexingIterator` as their iterator. /// /// By default, any custom collection type you create will inherit a /// `makeIterator()` method that returns an `IndexingIterator` instance, /// making it unnecessary to declare your own. When creating a custom /// collection type, add the minimal requirements of the `Collection` /// protocol: starting and ending indices and a subscript for accessing /// elements. With those elements defined, the inherited `makeIterator()` /// method satisfies the requirements of the `Sequence` protocol. /// /// Here's an example of a type that declares the minimal requirements for a /// collection. The `CollectionOfTwo` structure is a fixed-size collection /// that always holds two elements of a specific type. /// /// struct CollectionOfTwo<Element>: Collection { /// let elements: (Element, Element) /// /// init(_ first: Element, _ second: Element) { /// self.elements = (first, second) /// } /// /// var startIndex: Int { return 0 } /// var endIndex: Int { return 2 } /// /// subscript(index: Int) -> Element { /// switch index { /// case 0: return elements.0 /// case 1: return elements.1 /// default: fatalError("Index out of bounds.") /// } /// } /// /// func index(after i: Int) -> Int { /// precondition(i < endIndex, "Can't advance beyond endIndex") /// return i + 1 /// } /// } /// /// Because `CollectionOfTwo` doesn't define its own `makeIterator()` /// method or `Iterator` associated type, it uses the default iterator type, /// `IndexingIterator`. This example shows how a `CollectionOfTwo` instance /// can be created holding the values of a point, and then iterated over /// using a `for`-`in` loop. /// /// let point = CollectionOfTwo(15.0, 20.0) /// for element in point { /// print(element) /// } /// // Prints "15.0" /// // Prints "20.0" @frozen public struct IndexingIterator<Elements: Collection> { @usableFromInline internal let _elements: Elements @usableFromInline internal var _position: Elements.Index /// Creates an iterator over the given collection. @inlinable @inline(__always) public /// @testable init(_elements: Elements) { self._elements = _elements self._position = _elements.startIndex } /// Creates an iterator over the given collection. @inlinable @inline(__always) public /// @testable init(_elements: Elements, _position: Elements.Index) { self._elements = _elements self._position = _position } } extension IndexingIterator: IteratorProtocol, Sequence { public typealias Element = Elements.Element public typealias Iterator = IndexingIterator<Elements> public typealias SubSequence = AnySequence<Element> /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns all the elements of the underlying /// sequence in order. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// This example shows how an iterator can be used explicitly to emulate a /// `for`-`in` loop. First, retrieve a sequence's iterator, and then call /// the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence if a next element /// exists; otherwise, `nil`. @inlinable @inline(__always) public mutating func next() -> Elements.Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _elements.formIndex(after: &_position) return element } } extension IndexingIterator: Sendable where Elements: Sendable, Elements.Index: Sendable { } /// A sequence whose elements can be traversed multiple times, /// nondestructively, and accessed by an indexed subscript. /// /// Collections are used extensively throughout the standard library. When you /// use arrays, dictionaries, and other collections, you benefit from the /// operations that the `Collection` protocol declares and implements. In /// addition to the operations that collections inherit from the `Sequence` /// protocol, you gain access to methods that depend on accessing an element /// at a specific position in a collection. /// /// For example, if you want to print only the first word in a string, you can /// search for the index of the first space, and then create a substring up to /// that position. /// /// let text = "Buffalo buffalo buffalo buffalo." /// if let firstSpace = text.firstIndex(of: " ") { /// print(text[..<firstSpace]) /// } /// // Prints "Buffalo" /// /// The `firstSpace` constant is an index into the `text` string---the position /// of the first space in the string. You can store indices in variables, and /// pass them to collection algorithms or use them later to access the /// corresponding element. In the example above, `firstSpace` is used to /// extract the prefix that contains elements up to that index. /// /// Accessing Individual Elements /// ============================= /// /// You can access an element of a collection through its subscript by using /// any valid index except the collection's `endIndex` property. This property /// is a "past the end" index that does not correspond with any element of the /// collection. /// /// Here's an example of accessing the first character in a string through its /// subscript: /// /// let firstChar = text[text.startIndex] /// print(firstChar) /// // Prints "B" /// /// The `Collection` protocol declares and provides default implementations for /// many operations that depend on elements being accessible by their /// subscript. For example, you can also access the first character of `text` /// using the `first` property, which has the value of the first element of /// the collection, or `nil` if the collection is empty. /// /// print(text.first) /// // Prints "Optional("B")" /// /// You can pass only valid indices to collection operations. You can find a /// complete set of a collection's valid indices by starting with the /// collection's `startIndex` property and finding every successor up to, and /// including, the `endIndex` property. All other values of the `Index` type, /// such as the `startIndex` property of a different collection, are invalid /// indices for this collection. /// /// Saved indices may become invalid as a result of mutating operations. For /// more information about index invalidation in mutable collections, see the /// reference for the `MutableCollection` and `RangeReplaceableCollection` /// protocols, as well as for the specific type you're using. /// /// Accessing Slices of a Collection /// ================================ /// /// You can access a slice of a collection through its ranged subscript or by /// calling methods like `prefix(while:)` or `suffix(_:)`. A slice of a /// collection can contain zero or more of the original collection's elements /// and shares the original collection's semantics. /// /// The following example creates a `firstWord` constant by using the /// `prefix(while:)` method to get a slice of the `text` string. /// /// let firstWord = text.prefix(while: { $0 != " " }) /// print(firstWord) /// // Prints "Buffalo" /// /// You can retrieve the same slice using the string's ranged subscript, which /// takes a range expression. /// /// if let firstSpace = text.firstIndex(of: " ") { /// print(text[..<firstSpace] /// // Prints "Buffalo" /// } /// /// The retrieved slice of `text` is equivalent in each of these cases. /// /// Slices Share Indices /// -------------------- /// /// A collection and its slices share the same indices. An element of a /// collection is located under the same index in a slice as in the base /// collection, as long as neither the collection nor the slice has been /// mutated since the slice was created. /// /// For example, suppose you have an array holding the number of absences from /// each class during a session. /// /// var absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You're tasked with finding the day with the most absences in the second /// half of the session. To find the index of the day in question, follow /// these steps: /// /// 1) Create a slice of the `absences` array that holds the second half of the /// days. /// 2) Use the `max(by:)` method to determine the index of the day with the /// most absences. /// 3) Print the result using the index found in step 2 on the original /// `absences` array. /// /// Here's an implementation of those steps: /// /// let secondHalf = absences.suffix(absences.count / 2) /// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) { /// print("Highest second-half absences: \(absences[i])") /// } /// // Prints "Highest second-half absences: 3" /// /// Slices Inherit Collection Semantics /// ----------------------------------- /// /// A slice inherits the value or reference semantics of its base collection. /// That is, when working with a slice of a mutable collection that has value /// semantics, such as an array, mutating the original collection triggers a /// copy of that collection and does not affect the contents of the slice. /// /// For example, if you update the last element of the `absences` array from /// `0` to `2`, the `secondHalf` slice is unchanged. /// /// absences[7] = 2 /// print(absences) /// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]" /// print(secondHalf) /// // Prints "[0, 3, 1, 0]" /// /// Traversing a Collection /// ======================= /// /// Although a sequence can be consumed as it is traversed, a collection is /// guaranteed to be *multipass*: Any element can be repeatedly accessed by /// saving its index. Moreover, a collection's indices form a finite range of /// the positions of the collection's elements. The fact that all collections /// are finite guarantees the safety of many sequence operations, such as /// using the `contains(_:)` method to test whether a collection includes an /// element. /// /// Iterating over the elements of a collection by their positions yields the /// same elements in the same order as iterating over that collection using /// its iterator. This example demonstrates that the `characters` view of a /// string returns the same characters in the same order whether the view's /// indices or the view itself is being iterated. /// /// let word = "Swift" /// for character in word { /// print(character) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// for i in word.indices { /// print(word[i]) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// Conforming to the Collection Protocol /// ===================================== /// /// If you create a custom sequence that can provide repeated access to its /// elements, make sure that its type conforms to the `Collection` protocol in /// order to give a more useful and more efficient interface for sequence and /// collection operations. To add `Collection` conformance to your type, you /// must declare at least the following requirements: /// /// - The `startIndex` and `endIndex` properties /// - A subscript that provides at least read-only access to your type's /// elements /// - The `index(after:)` method for advancing an index into your collection /// /// Expected Performance /// ==================== /// /// Types that conform to `Collection` are expected to provide the `startIndex` /// and `endIndex` properties and subscript access to elements as O(1) /// operations. Types that are not able to guarantee this performance must /// document the departure, because many collection operations depend on O(1) /// subscripting performance for their own performance guarantees. /// /// The performance of some collection operations depends on the type of index /// that the collection provides. For example, a random-access collection, /// which can measure the distance between two indices in O(1) time, can /// calculate its `count` property in O(1) time. Conversely, because a forward /// or bidirectional collection must traverse the entire collection to count /// the number of contained elements, accessing its `count` property is an /// O(*n*) operation. public protocol Collection: Sequence { // FIXME: ideally this would be in MigrationSupport.swift, but it needs // to be on the protocol instead of as an extension @available(*, deprecated/*, obsoleted: 5.0*/, message: "all index distances are now of type Int") typealias IndexDistance = Int // FIXME: Associated type inference requires this. override associatedtype Element /// A type that represents a position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript /// argument. associatedtype Index: Comparable /// The position of the first element in a nonempty collection. /// /// If the collection is empty, `startIndex` is equal to `endIndex`. var startIndex: Index { get } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// When you need a range that includes the last element of a collection, use /// the half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let index = numbers.firstIndex(of: 30) { /// print(numbers[index ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the collection is empty, `endIndex` is equal to `startIndex`. var endIndex: Index { get } /// A type that provides the collection's iteration interface and /// encapsulates its iteration state. /// /// By default, a collection conforms to the `Sequence` protocol by /// supplying `IndexingIterator` as its associated `Iterator` /// type. associatedtype Iterator = IndexingIterator<Self> // FIXME: Only needed for associated type inference. Otherwise, // we get an `IndexingIterator` rather than properly deducing the // Iterator type from makeIterator(). <rdar://problem/21539115> /// Returns an iterator over the elements of the collection. override __consuming func makeIterator() -> Iterator /// A collection representing a contiguous subrange of this collection's /// elements. The subsequence shares indices with the original collection. /// /// The default subsequence type for collections that don't define their own /// is `Slice`. associatedtype SubSequence: Collection = Slice<Self> where SubSequence.Index == Index, Element == SubSequence.Element, SubSequence.SubSequence == SubSequence /// Accesses the element at the specified position. /// /// The following example accesses an element of an array through its /// subscript to print its value: /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// print(streets[1]) /// // Prints "Bryant" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) @_borrowed subscript(position: Index) -> Element { get } /// Accesses a contiguous subrange of the collection's elements. /// /// For example, using a `PartialRangeFrom` range expression with an array /// accesses the subrange from the start of the range expression until the /// end of the array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2..<5] /// print(streetsSlice) /// // ["Channing", "Douglas", "Evarts"] /// /// The accessed slice uses the same indices for the same elements as the /// original collection. This example searches `streetsSlice` for one of the /// strings in the slice, and then uses that index in the original array. /// /// let index = streetsSlice.firstIndex(of: "Evarts")! // 4 /// print(streets[index]) /// // "Evarts" /// /// Always use the slice's `startIndex` property instead of assuming that its /// indices start at a particular value. Attempting to access an element by /// using an index outside the bounds of the slice may result in a runtime /// error, even if that index is valid for the original collection. /// /// print(streetsSlice.startIndex) /// // 2 /// print(streetsSlice[2]) /// // "Channing" /// /// print(streetsSlice[0]) /// // error: Index out of bounds /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices: Collection = DefaultIndices<Self> where Indices.Element == Index, Indices.Index == Index, Indices.SubSequence == Indices /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be nonuniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can result in an unexpected copy of the collection. To avoid /// the unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.isEmpty { /// print("My horse has no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!" /// /// - Complexity: O(1) var isEmpty: Bool { get } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. var count: Int { get } // The following requirements enable dispatching for firstIndex(of:) and // lastIndex(of:) when the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found /// or `Optional(nil)` if an element was determined to be missing; /// otherwise, `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func _customIndexOfEquatableElement(_ element: Element) -> Index?? /// Customization point for `Collection.lastIndex(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: Hopefully less than O(`count`). func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. 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. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the /// resulting distance. func distance(from start: Index, to end: Index) -> Int /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition(bounds.contains(index)) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition( /// bounds.contains(range.lowerBound) || /// range.lowerBound == bounds.upperBound) /// precondition( /// bounds.contains(range.upperBound) || /// range.upperBound == bounds.upperBound) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. func formIndex(after i: inout Index) } /// Default implementation for forward collections. extension Collection { /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable // protocol-only @inline(__always) public func formIndex(after i: inout Index) { i = index(after: i) } @inlinable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "Out of bounds: index < startIndex") _precondition( index < bounds.upperBound, "Out of bounds: index >= endIndex") } @inlinable public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "Out of bounds: index < startIndex") _precondition( index <= bounds.upperBound, "Out of bounds: index > endIndex") } @inlinable public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= range.lowerBound, "Out of bounds: range begins before startIndex") _precondition( range.lowerBound <= bounds.upperBound, "Out of bounds: range ends after endIndex") _precondition( bounds.lowerBound <= range.upperBound, "Out of bounds: range ends before bounds.lowerBound") _precondition( range.upperBound <= bounds.upperBound, "Out of bounds: range begins after bounds.upperBound") } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { return self._advanceForward(i, by: distance) } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @inlinable public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { return self._advanceForward(i, by: distance, limitedBy: limit) } /// Offsets the given index by the specified distance. /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @inlinable public func formIndex(_ i: inout Index, offsetBy distance: Int) { i = index(i, offsetBy: distance) } /// Offsets the given index by the specified distance, or so that it equals /// the given limiting index. /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: `true` if `i` has been offset by exactly `distance` steps /// without going beyond `limit`; otherwise, `false`. When the return /// value is `false`, the value of `i` is equal to `limit`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @inlinable public func formIndex( _ i: inout Index, offsetBy distance: Int, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: distance, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the /// resulting distance. @inlinable public func distance(from start: Index, to end: Index) -> Int { _precondition(start <= end, "Only BidirectionalCollections can have end come before start") var start = start var count = 0 while start != end { count = count + 1 formIndex(after: &start) } return count } /// Returns a random element of the collection, using the given generator as /// a source for randomness. /// /// Call `randomElement(using:)` to select a random element from an array or /// another collection when you are using a custom random number generator. /// This example picks a name at random from an array: /// /// let names = ["Zoey", "Chloe", "Amani", "Amaia"] /// let randomName = names.randomElement(using: &myGenerator)! /// // randomName == "Amani" /// /// - Parameter generator: The random number generator to use when choosing a /// random element. /// - Returns: A random element from the collection. If the collection is /// empty, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. /// - Note: The algorithm used to select a random element may change in a /// future version of Swift. If you're passing a generator that results in /// the same sequence of elements each time you run your program, that /// sequence may change when your program is compiled using a different /// version of Swift. @inlinable public func randomElement<T: RandomNumberGenerator>( using generator: inout T ) -> Element? { guard !isEmpty else { return nil } let random = Int.random(in: 0 ..< count, using: &generator) let idx = index(startIndex, offsetBy: random) return self[idx] } /// Returns a random element of the collection. /// /// Call `randomElement()` to select a random element from an array or /// another collection. This example picks a name at random from an array: /// /// let names = ["Zoey", "Chloe", "Amani", "Amaia"] /// let randomName = names.randomElement()! /// // randomName == "Amani" /// /// This method is equivalent to calling `randomElement(using:)`, passing in /// the system's default random generator. /// /// - Returns: A random element from the collection. If the collection is /// empty, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public func randomElement() -> Element? { var g = SystemRandomNumberGenerator() return randomElement(using: &g) } /// Do not use this method directly; call advanced(by: n) instead. @inlinable @inline(__always) internal func _advanceForward(_ i: Index, by n: Int) -> Index { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { formIndex(after: &i) } return i } /// Do not use this method directly; call advanced(by: n, limit) instead. @inlinable @inline(__always) internal func _advanceForward( _ i: Index, by n: Int, limitedBy limit: Index ) -> Index? { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { if i == limit { return nil } formIndex(after: &i) } return i } } /// Supply the default `makeIterator()` method for `Collection` models /// that accept the default associated `Iterator`, /// `IndexingIterator<Self>`. extension Collection where Iterator == IndexingIterator<Self> { /// Returns an iterator over the elements of the collection. @inlinable // trivial-implementation @inline(__always) public __consuming func makeIterator() -> IndexingIterator<Self> { return IndexingIterator(_elements: self) } } /// Supply the default "slicing" `subscript` for `Collection` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension Collection where SubSequence == Slice<Self> { /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @inlinable public subscript(bounds: Range<Index>) -> Slice<Self> { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } } extension Collection { // This unavailable default implementation of `subscript(bounds: Range<_>)` // prevents incomplete Collection implementations from satisfying the // protocol through the use of the generic convenience implementation // `subscript<R: RangeExpression>(r: R)`. If that were the case, at // runtime the generic implementation would call itself // in an infinite recursion because of the absence of a better option. @available(*, unavailable) @_alwaysEmitIntoClient public subscript(bounds: Range<Index>) -> SubSequence { fatalError() } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// - Returns: The first element of the collection if the collection is /// not empty; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable public mutating func popFirst() -> Element? { // TODO: swift-3-indexing-model - review the following guard !isEmpty else { return nil } let element = first! self = self[index(after: startIndex)..<endIndex] return element } } /// Default implementations of core requirements extension Collection { /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.isEmpty { /// print("My horse has no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!") /// /// - Complexity: O(1) @inlinable public var isEmpty: Bool { return startIndex == endIndex } /// The first element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let firstNumber = numbers.first { /// print(firstNumber) /// } /// // Prints "10" @inlinable public var first: Element? { let start = startIndex if start != endIndex { return self[start] } else { return nil } } /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public var underestimatedCount: Int { // TODO: swift-3-indexing-model - review the following return count } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public var count: Int { return distance(from: startIndex, to: endIndex) } // TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)? /// Customization point for `Collection.firstIndex(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: Hopefully less than O(`count`). @inlinable @inline(__always) public // dispatching func _customIndexOfEquatableElement(_: Element) -> Index?? { return nil } /// Customization point for `Collection.lastIndex(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: Hopefully less than O(`count`). @inlinable @inline(__always) public // dispatching func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for Collection //===----------------------------------------------------------------------===// extension Collection { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @inlinable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { // TODO: swift-3-indexing-model - review the following let n = self.count if n == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(n) var i = self.startIndex for _ in 0..<n { result.append(try transform(self[i])) formIndex(after: &i) } _expectEnd(of: self, is: i) return Array(result) } /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop from the beginning of /// the collection. `k` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to drop from the beginning of the collection. @inlinable public __consuming func dropFirst(_ k: Int = 1) -> SubSequence { _precondition(k >= 0, "Can't drop a negative number of elements from a collection") let start = index(startIndex, offsetBy: k, limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop off the end of the /// collection. `k` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off the specified number of elements /// at the end. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of /// the collection. @inlinable public __consuming func dropLast(_ k: Int = 1) -> SubSequence { _precondition( k >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, count - k) let end = index(startIndex, offsetBy: amount, limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be skipped or `false` if it should be included. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public __consuming func drop( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { var start = startIndex while try start != endIndex && predicate(self[start]) { formIndex(after: &start) } return self[start..<endIndex] } /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this collection /// with at most `maxLength` elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to select from the beginning of the collection. @inlinable public __consuming func prefix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = index(startIndex, offsetBy: maxLength, limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence containing the initial elements until `predicate` /// returns `false` and skipping the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be included or `false` if it should be excluded. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public __consuming func prefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence { var end = startIndex while try end != endIndex && predicate(self[end]) { formIndex(after: &end) } return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of /// the collection. @inlinable public __consuming func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = Swift.max(0, count - maxLength) let start = index(startIndex, offsetBy: amount, limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence from the start of the collection up to, but not /// including, the specified position. /// /// The resulting subsequence *does not include* the element at the position /// `end`. The following example searches for the index of the number `40` /// in an array of integers, and then prints the prefix of the array up to, /// but not including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.firstIndex(of: 40) { /// print(numbers.prefix(upTo: i)) /// } /// // Prints "[10, 20, 30]" /// /// Passing the collection's starting index as the `end` parameter results in /// an empty subsequence. /// /// print(numbers.prefix(upTo: numbers.startIndex)) /// // Prints "[]" /// /// Using the `prefix(upTo:)` method is equivalent to using a partial /// half-open range as the collection's subscript. The subscript notation is /// preferred over `prefix(upTo:)`. /// /// if let i = numbers.firstIndex(of: 40) { /// print(numbers[..<i]) /// } /// // Prints "[10, 20, 30]" /// /// - Parameter end: The "past the end" index of the resulting subsequence. /// `end` must be a valid index of the collection. /// - Returns: A subsequence up to, but not including, the `end` position. /// /// - Complexity: O(1) @inlinable public __consuming func prefix(upTo end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns a subsequence from the specified position to the end of the /// collection. /// /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the suffix of the array starting at /// that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.firstIndex(of: 40) { /// print(numbers.suffix(from: i)) /// } /// // Prints "[40, 50, 60]" /// /// Passing the collection's `endIndex` as the `start` parameter results in /// an empty subsequence. /// /// print(numbers.suffix(from: numbers.endIndex)) /// // Prints "[]" /// /// Using the `suffix(from:)` method is equivalent to using a partial range /// from the index as the collection's subscript. The subscript notation is /// preferred over `suffix(from:)`. /// /// if let i = numbers.firstIndex(of: 40) { /// print(numbers[i...]) /// } /// // Prints "[40, 50, 60]" /// /// - Parameter start: The index at which to start the resulting subsequence. /// `start` must be a valid index of the collection. /// - Returns: A subsequence starting at the `start` position. /// /// - Complexity: O(1) @inlinable public __consuming func suffix(from start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns a subsequence from the start of the collection through the /// specified position. /// /// The resulting subsequence *includes* the element at the position `end`. /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the prefix of the array up to, and /// including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.firstIndex(of: 40) { /// print(numbers.prefix(through: i)) /// } /// // Prints "[10, 20, 30, 40]" /// /// Using the `prefix(through:)` method is equivalent to using a partial /// closed range as the collection's subscript. The subscript notation is /// preferred over `prefix(through:)`. /// /// if let i = numbers.firstIndex(of: 40) { /// print(numbers[...i]) /// } /// // Prints "[10, 20, 30, 40]" /// /// - Parameter position: The index of the last element to include in the /// resulting subsequence. `position` must be a valid index of the collection /// that is not equal to the `endIndex` property. /// - Returns: A subsequence up to, and including, the `end` position. /// /// - Complexity: O(1) @inlinable public __consuming func prefix(through position: Index) -> SubSequence { return prefix(upTo: index(after: position)) } /// Returns the longest possible subsequences of the collection, in order, /// that don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " })) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(maxSplits: 1, whereSeparator: { $0 == " " })) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " })) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the collection satisfying the `isSeparator` /// predicate. The default value is `true`. /// - isSeparator: A closure that takes an element as an argument and /// returns a Boolean value indicating whether the collection should be /// split at that element. /// - Returns: An array of subsequences, split from this collection's /// elements. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public __consuming func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] { // TODO: swift-3-indexing-model - review the following _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end: Index) -> Bool { if subSequenceStart == end && omittingEmptySubsequences { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplits == 0 || isEmpty { _ = appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) formIndex(after: &subSequenceEnd) subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplits { break } continue } formIndex(after: &subSequenceEnd) } if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension Collection where Element: Equatable { /// Returns the longest possible subsequences of the collection, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the collection are not returned as part /// of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ")) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the collection and for each instance of `separator` at /// the start or end of the collection. If `true`, only nonempty /// subsequences are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this collection's /// elements. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public __consuming func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { // TODO: swift-3-indexing-model - review the following return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) @inlinable @discardableResult public mutating func removeFirst() -> Element { // TODO: swift-3-indexing-model - review the following _precondition(!isEmpty, "Can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// - Parameter k: The number of elements to remove. `k` must be greater than /// or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the specified /// number of elements. @inlinable public mutating func removeFirst(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") guard let idx = index(startIndex, offsetBy: k, limitedBy: endIndex) else { _preconditionFailure( "Can't remove more items from a collection than it contains") } self = self[idx..<endIndex] } }
39.468009
100
0.647249
03ec5252b45d34d9e6acc17f66357d60a0a8b8f3
1,691
// // UIFont+Theme.swift // import UIKit extension UIFont { static func themeFont(_ size: CGFloat) -> UIFont { if let font = UIFont(name: "Roboto", size: size) { return font } return UIFont.systemFont(ofSize: size) } static func themeCondensedFont(_ size: CGFloat) -> UIFont { if let font = UIFont(name: "RobotoCondensed-Regular", size: size) { return font } return UIFont.systemFont(ofSize: size) } static func themeCondensedBoldFont(_ size: CGFloat) -> UIFont { if let font = UIFont(name: "RobotoCondensed-Bold", size: size) { return font } return UIFont.boldSystemFont(ofSize: size) } public static func loadFonts() { registerFont(withFileName: "Roboto-Regular", type: "ttf") registerFont(withFileName: "RobotoCondensed-Bold", type: "ttf") registerFont(withFileName: "RobotoCondensed-Italic", type: "ttf") registerFont(withFileName: "RobotoCondensed-Regular", type: "ttf") } static func registerFont(withFileName fileName: String, type: String) { if let fontPath = Bundle.frameworkResources.path(forResource: fileName, ofType: type), let fontData = NSData(contentsOfFile: fontPath), let dataProvider = CGDataProvider(data: fontData) { let fontRef = CGFont(dataProvider) var errorRef: Unmanaged<CFError>? = nil if CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) == false { print("Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.") } } } }
33.156863
195
0.638675
262bbbf0dfc2aac279d19a6ab0eb8e45313f9b15
1,379
// // TransitionPerformer.swift // XCoordinator // // Created by Paul Kraft on 13.09.18. // Copyright © 2018 QuickBird Studios. All rights reserved. // /// /// The TransitionPerformer protocol is used to abstract the route-type specific characteristics of a Coordinator. /// It keeps type information about its transition performing capabilities. /// public protocol TransitionPerformer: Presentable { /// The type of transitions that can be executed on the rootViewController. associatedtype TransitionType: TransitionProtocol /// The rootViewController on which transitions are performed. var rootViewController: TransitionType.RootViewController { get } /// /// Perform a transition. /// /// - Warning: /// Do not use this method directly, but instead try to use the `trigger` /// method of your coordinator instead wherever possible. /// /// - Parameters: /// - transition: The transition to be performed. /// - options: The options on how to perform the transition, including the option to enable/disable animations. /// - completion: The completion handler called once a transition has finished. /// func performTransition(_ transition: TransitionType, with options: TransitionOptions, completion: PresentationHandler?) }
36.289474
119
0.685279
9bc3cfb996bc9684c1c90c42374db346eeea8247
6,919
// // MeteorDDPServerTests.swift // MeteorDDP_Tests // // Created by Muhammad Ahsan Ali on 2020/02/28. // Copyright © 2020 CocoaPods. All rights reserved. // import Quick import Nimble @testable import MeteorDDP // Tests against a Meteor instance at swiftddp.meteor.com class MeteorDDPServerTests:QuickSpec { override func spec() { describe ("MeteorDDP Connection") { it ("can connect to a DDP server"){ var testSession:String? let client = MeteorClient() client.connect(url) { session in testSession = session } expect(client.connection.ddp).toEventually(beTrue(), timeout:5) expect(client.connection.session).toEventually(equal(testSession), timeout:5) } } // DDP Methods // tests login:, logout:, insert:, remove:, update: describe ("MeteorDDP Methods") { it ("can login to a Meteor server") { // On connect, the client should set the client.connection.session property // After logging in with a username and password, the client should receive a result // object that the session token var testResult:NSDictionary! var testSession:String! let client = MeteorClient() client.connect(url) { session in testSession = session client.loginWithPassword(user, password: pass) { result, e in testResult = result! as? NSDictionary } } // Both of these should be non nil; the callbacks should assign them their respective values expect(testResult).toEventuallyNot(beNil(), timeout:5) expect(testSession).toEventuallyNot(beNil(), timeout:5) let userDefaultsToken = client.userData.object(forKey: "MeteorDDP_TOKEN") as! String let resultToken = testResult["token"] as! String expect(userDefaultsToken).toEventually(equal(resultToken), timeout:5) expect(testSession).toEventually(equal(client.connection.session), timeout:5) } it ("can add and remove a document on the server"){ var added = [NSDictionary]() var removed = [String]() let client = MeteorClient() let _id = client.getId() client.events.onAdded = { collection, id, fields in if ((collection == "test-collection2") && (_id == id)) { added.append(fields!) } } client.events.onRemoved = { collection, id in removed.append(id) } client.connect(url) { session in print("Connected to DDP server!!! \(session)") client.loginWithPassword(user, password: pass) { result, e in print("Login data: \(String(describing: result)), \(String(describing: e))") client.sub("test-collection2", params:nil) client.insert("test-collection2", document: NSArray(arrayLiteral:["_id":_id, "foo":"bar"])) } } // the tuple that holds the subscription data in the client should be updated to reflect that the // subscription is ready let subscriptionID = client.findSubscription("test-collection2") print("subscriptionID ", subscriptionID) expect(client.subscriptionReady("test-collection2")).toEventually(beTrue(), timeout:5) // test that the data is returned from the server expect(added.count).toEventually(equal(1), timeout:5) expect(added[0]["foo"] as? String).toEventually(equal("bar"), timeout:5) // test that the data is removed from the server (can also me checked on the server) client.remove("test-collection2", document:NSArray(arrayLiteral:["_id":_id])) expect(removed.count).toEventually(equal(1), timeout:5) // expect(removed[0]).toEventually(equal("100"), timeout:5) } it ("can update a document in a collection") { var added = [NSDictionary]() var updated = [NSDictionary]() let client = MeteorClient() let _id = client.getId() client.events.onAdded = { collection, id, fields in if ((collection == "test-collection2") && (_id == id)) { added.append(fields!) } } client.events.onChanged = { collection, id, fields, cleared in if ((collection == "test-collection2") && (_id == id)) { updated.append(fields!) } } client.connect(url) { session in print("Connected to DDP server!!! \(session)") client.loginWithPassword(user, password: pass) { result, e in print("Login data: \(String(describing: result)), \(String(describing: e))") client.sub("test-collection2", params:nil) client.insert("test-collection2", document: NSArray(arrayLiteral:["_id":_id, "foo":"bar"])) } } expect(added.count).toEventually(equal(1), timeout:10) var params = NSMutableDictionary() params = ["$set":["foo":"baz"]] client.update("test-collection2", document: [["_id":_id], params]) { result, error in } expect(updated.count).toEventually(equal(1)) client.remove("test-collection2", document: [["_id":_id]]) } it ("can execute a method on the server that returns a value") { var response:String! let client = MeteorClient() client.connect(url) { session in client.loginWithPassword(user, password: pass) { result, error in client.method("test", params: nil) { result, error in let r = result as! String response = r } } } expect(response).toEventually(equal("test123"), timeout:5) } } } }
45.222222
150
0.503975
91967264a3356b64e4f239534643a975e32ddd33
2,990
// // QueryTests.swift // SwiftyGraphQLTests // // Created by Taylor McIntyre on 2018-10-09. // Copyright © 2018 hiimtmac All rights reserved. // import XCTest import SwiftyGraphQL class QueryTests: BaseTestCase { func testWithoutFragment() { GQL(.query) { GQLNode("allNodes") { "hi" "ok" } } .serialize(to: &serializer) XCTAssertEqual(graphQL, #"query { allNodes { hi ok } }"#) XCTAssert(fragmentQL.isEmpty) } func testWithFragment() { GQL(.query) { GQLNode("allNodes") { GQLFragment(Frag2.self) } } .serialize(to: &serializer) XCTAssertEqual(graphQL, #"query { allNodes { ...frag2 } }"#) XCTAssertEqual(fragmentQL, #"fragment frag2 on Frag2 { birthday address }"#) } func testAdvanced() { GQL(.query) { GQLNode("myQuery") { "thing1" "thing2" GQLNode("frag2") { Frag2.asFragment() GQLNode("frag1", alias: "allFrag1s") { GQLFragment(Frag1.self) } .withArgument("since", value: 20) .withArgument("name", value: "taylor") } } } .serialize(to: &serializer) XCTAssertEqual(graphQL, #"query { myQuery { thing1 thing2 frag2 { ...frag2 allFrag1s: frag1(name: "taylor", since: 20) { ...frag1 } } } }"#) XCTAssertEqual(fragmentQL, #"fragment frag1 on Frag1 { name age } fragment frag2 on Frag2 { birthday address }"#) } func testWithArray() { GQL(.query) { GQLNode("one") { Frag1.asFragment() } GQLNode("two") { "no" "maybe" Frag3.asFragment() } } .serialize(to: &serializer) XCTAssertEqual(graphQL, #"query { one { ...frag1 } two { no maybe ...fragment3 } }"#) XCTAssertEqual(fragmentQL, #"fragment frag1 on Frag1 { name age } fragment fragment3 on Fragment3 { name age address cool }"#) } func testWithArrayWithEmptyNode() { GQL(.query) { GQLNode("one") {} GQLNode("two") { "no" "maybe" Frag2.asFragment() } } .serialize(to: &serializer) XCTAssertEqual(graphQL, #"query { one { } two { no maybe ...frag2 } }"#) XCTAssertEqual(fragmentQL, #"fragment frag2 on Frag2 { birthday address }"#) } static var allTests = [ ("testWithoutFragment", testWithoutFragment), ("testWithFragment", testWithFragment), ("testAdvanced", testAdvanced), ("testWithArray", testWithArray), ("testWithArrayWithEmptyNode", testWithArrayWithEmptyNode) ] }
29.9
149
0.500669
905af013d4440e196333225d734a014e442f65d5
1,302
// // BaseViewController.swift // DouYuZhiBo_new // // Created by LEPU on 2020/7/24. // Copyright © 2020 LEPU. All rights reserved. // import UIKit class BaseViewController: UIViewController { // @IBOutlet weak var imgView: UIImageView! fileprivate lazy var imgView:UIImageView = { let imgView = UIImageView(image: UIImage(named: "img_loading_1")) imgView.center = self.view.center imgView.animationImages = [UIImage(named: "img_loading_1")!,UIImage(named: "img_loading_2")!] imgView.animationDuration = 0.5 imgView.animationRepeatCount = LONG_MAX /* 问题: imgView 没有显示在视图中间 原因:父控件进行了拉伸导致的,子控件需要跟随进行拉伸 */ imgView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin] return imgView }() //这个imgview 是要覆盖到pageCollectionView上的 var coverView:UIView? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(R: 250, G: 250, B: 250) view.addSubview(imgView) imgView.startAnimating() } } extension BaseViewController { @objc func removeImgV(){ coverView?.isHidden = false imgView.stopAnimating() imgView.removeFromSuperview() } }
24.566038
101
0.631336
e5c7885ac5185946f7cc0b6fb834e0343fc193cc
11,062
// // R.generated.swift // VK News Feed // // Created by Roman Rakhlin on 09.02.2020. // Copyright © 2020 Roman Rakhlin. All rights reserved. // import Foundation import Rswift import UIKit /// This `R` struct is generated and contains references to static resources. struct R: Rswift.Validatable { fileprivate static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap(Locale.init) ?? Locale.current fileprivate static let hostingBundle = Bundle(for: R.Class.self) /// Find first language and bundle for which the table exists fileprivate static func localeBundle(tableName: String, preferredLanguages: [String]) -> (Foundation.Locale, Foundation.Bundle)? { // Filter preferredLanguages to localizations, use first locale var languages = preferredLanguages .map(Locale.init) .prefix(1) .flatMap { locale -> [String] in if hostingBundle.localizations.contains(locale.identifier) { if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [locale.identifier, language] } else { return [locale.identifier] } } else if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [language] } else { return [] } } // If there's no languages, use development language as backstop if languages.isEmpty { if let developmentLocalization = hostingBundle.developmentLocalization { languages = [developmentLocalization] } } else { // Insert Base as second item (between locale identifier and languageCode) languages.insert("Base", at: 1) // Add development language as backstop if let developmentLocalization = hostingBundle.developmentLocalization { languages.append(developmentLocalization) } } // Find first language for which table exists // Note: key might not exist in chosen language (in that case, key will be shown) for language in languages { if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"), let lbundle = Bundle(url: lproj) { let strings = lbundle.url(forResource: tableName, withExtension: "strings") let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict") if strings != nil || stringsdict != nil { return (Locale(identifier: language), lbundle) } } } // If table is available in main bundle, don't look for localized resources let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil) let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil) if strings != nil || stringsdict != nil { return (applicationLocale, hostingBundle) } // If table is not found for requested languages, key will be shown return nil } /// Load string from Info.plist file fileprivate static func infoPlistString(path: [String], key: String) -> String? { var dict = hostingBundle.infoDictionary for step in path { guard let obj = dict?[step] as? [String: Any] else { return nil } dict = obj } return dict?[key] as? String } static func validate() throws { try intern.validate() } #if os(iOS) || os(tvOS) /// This `R.storyboard` struct is generated, and contains static references to 3 storyboards. struct storyboard { /// Storyboard `AuthViewController`. static let authViewController = _R.storyboard.authViewController() /// Storyboard `LaunchScreen`. static let launchScreen = _R.storyboard.launchScreen() /// Storyboard `NewsfeedViewController`. static let newsfeedViewController = _R.storyboard.newsfeedViewController() #if os(iOS) || os(tvOS) /// `UIStoryboard(name: "AuthViewController", bundle: ...)` static func authViewController(_: Void = ()) -> UIKit.UIStoryboard { return UIKit.UIStoryboard(resource: R.storyboard.authViewController) } #endif #if os(iOS) || os(tvOS) /// `UIStoryboard(name: "LaunchScreen", bundle: ...)` static func launchScreen(_: Void = ()) -> UIKit.UIStoryboard { return UIKit.UIStoryboard(resource: R.storyboard.launchScreen) } #endif #if os(iOS) || os(tvOS) /// `UIStoryboard(name: "NewsfeedViewController", bundle: ...)` static func newsfeedViewController(_: Void = ()) -> UIKit.UIStoryboard { return UIKit.UIStoryboard(resource: R.storyboard.newsfeedViewController) } #endif fileprivate init() {} } #endif /// This `R.image` struct is generated, and contains static references to 5 images. struct image { /// Image `VKLabelClear`. static let vkLabelClear = Rswift.ImageResource(bundle: R.hostingBundle, name: "VKLabelClear") /// Image `comment`. static let comment = Rswift.ImageResource(bundle: R.hostingBundle, name: "comment") /// Image `eye`. static let eye = Rswift.ImageResource(bundle: R.hostingBundle, name: "eye") /// Image `like`. static let like = Rswift.ImageResource(bundle: R.hostingBundle, name: "like") /// Image `share`. static let share = Rswift.ImageResource(bundle: R.hostingBundle, name: "share") #if os(iOS) || os(tvOS) /// `UIImage(named: "VKLabelClear", bundle: ..., traitCollection: ...)` static func vkLabelClear(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? { return UIKit.UIImage(resource: R.image.vkLabelClear, compatibleWith: traitCollection) } #endif #if os(iOS) || os(tvOS) /// `UIImage(named: "comment", bundle: ..., traitCollection: ...)` static func comment(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? { return UIKit.UIImage(resource: R.image.comment, compatibleWith: traitCollection) } #endif #if os(iOS) || os(tvOS) /// `UIImage(named: "eye", bundle: ..., traitCollection: ...)` static func eye(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? { return UIKit.UIImage(resource: R.image.eye, compatibleWith: traitCollection) } #endif #if os(iOS) || os(tvOS) /// `UIImage(named: "like", bundle: ..., traitCollection: ...)` static func like(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? { return UIKit.UIImage(resource: R.image.like, compatibleWith: traitCollection) } #endif #if os(iOS) || os(tvOS) /// `UIImage(named: "share", bundle: ..., traitCollection: ...)` static func share(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? { return UIKit.UIImage(resource: R.image.share, compatibleWith: traitCollection) } #endif fileprivate init() {} } /// This `R.string` struct is generated, and contains static references to 1 localization tables. struct string { /// This `R.string.localizable` struct is generated, and contains static references to 1 localization keys. struct localizable { /// Value: %#@totalAmount@ static let newsfeedCellsCount = Rswift.StringResource(key: "newsfeed cells count", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil) /// Value: %#@totalAmount@ static func newsfeedCellsCount(totalAmount value1: Int, preferredLanguages: [String]? = nil) -> String { guard let preferredLanguages = preferredLanguages else { let format = NSLocalizedString("newsfeed cells count", bundle: hostingBundle, comment: "") return String(format: format, locale: applicationLocale, value1) } guard let (locale, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else { return "newsfeed cells count" } let format = NSLocalizedString("newsfeed cells count", bundle: bundle, comment: "") return String(format: format, locale: locale, value1) } fileprivate init() {} } fileprivate init() {} } fileprivate struct intern: Rswift.Validatable { fileprivate static func validate() throws { try _R.validate() } fileprivate init() {} } fileprivate class Class {} fileprivate init() {} } struct _R: Rswift.Validatable { static func validate() throws { #if os(iOS) || os(tvOS) try storyboard.validate() #endif } #if os(iOS) || os(tvOS) struct storyboard: Rswift.Validatable { static func validate() throws { #if os(iOS) || os(tvOS) try authViewController.validate() #endif #if os(iOS) || os(tvOS) try launchScreen.validate() #endif #if os(iOS) || os(tvOS) try newsfeedViewController.validate() #endif } #if os(iOS) || os(tvOS) struct authViewController: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable { typealias InitialController = AuthViewController let authViewController = StoryboardViewControllerResource<AuthViewController>(identifier: "AuthViewController") let bundle = R.hostingBundle let name = "AuthViewController" func authViewController(_: Void = ()) -> AuthViewController? { return UIKit.UIStoryboard(resource: self).instantiateViewController(withResource: authViewController) } static func validate() throws { if UIKit.UIImage(named: "VKLabelClear", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'VKLabelClear' is used in storyboard 'AuthViewController', but couldn't be loaded.") } if #available(iOS 11.0, tvOS 11.0, *) { } if _R.storyboard.authViewController().authViewController() == nil { throw Rswift.ValidationError(description:"[R.swift] ViewController with identifier 'authViewController' could not be loaded from storyboard 'AuthViewController' as 'AuthViewController'.") } } fileprivate init() {} } #endif #if os(iOS) || os(tvOS) struct launchScreen: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable { typealias InitialController = UIKit.UIViewController let bundle = R.hostingBundle let name = "LaunchScreen" static func validate() throws { if #available(iOS 11.0, tvOS 11.0, *) { } } fileprivate init() {} } #endif #if os(iOS) || os(tvOS) struct newsfeedViewController: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable { typealias InitialController = NewsfeedViewController let bundle = R.hostingBundle let name = "NewsfeedViewController" static func validate() throws { if #available(iOS 11.0, tvOS 11.0, *) { } } fileprivate init() {} } #endif fileprivate init() {} } #endif fileprivate init() {} }
36.508251
265
0.674381
227298587de34b17bd65fbd4f972fe023a01a042
1,114
// // APIChatsExtension.swift // sphinx // // Created by Tomas Timinskas on 17/12/2019. // Copyright © 2019 Sphinx. All rights reserved. // import Foundation import SwiftyJSON import Alamofire extension API { public func toggleChatSound(chatId: Int, muted: Bool, callback: @escaping MuteChatCallback, errorCallback: @escaping EmptyCallback) { let route = muted ? "mute" : "unmute" guard let request = getURLRequest(route: "/chats/\(chatId)/\(route)", method: "POST") else { errorCallback() return } sphinxRequest(request) { response in switch response.result { case .success(let data): if let json = data as? NSDictionary { if let success = json["success"] as? Bool, let response = json["response"] as? NSDictionary, success { callback(JSON(response)) } else { errorCallback() } } case .failure(_): errorCallback() } } } }
30.108108
137
0.5386
eb6d5b0adc520bc6f1c9efc321a15f7817719f79
9,504
// // VulkanCommandBuffer.swift // VkRenderer // // Created by Thomas Roughton on 10/01/18. // #if canImport(Vulkan) import Vulkan import SubstrateCExtras import SubstrateUtilities import Dispatch import Foundation // Represents all resources that are associated with a particular command buffer // and should be freed once the command buffer has finished execution. final class VulkanCommandBuffer: BackendCommandBuffer { typealias Backend = VulkanBackend struct Error: Swift.Error { public var result: VkResult } static let semaphoreSignalQueue = DispatchQueue(label: "Vulkan Semaphore Signal Queue") let backend: VulkanBackend let queue: VulkanDeviceQueue let commandBuffer: VkCommandBuffer let commandInfo: FrameCommandInfo<VulkanBackend> let resourceMap: FrameResourceMap<VulkanBackend> let compactedResourceCommands: [CompactedResourceCommand<VulkanCompactedResourceCommandType>] var buffers = [VulkanBuffer]() var bufferView = [VulkanBufferView]() var images = [VulkanImage]() var imageViews = [VulkanImageView]() var renderPasses = [VulkanRenderPass]() var framebuffers = [VulkanFramebuffer]() var descriptorSets = [VkDescriptorSet?]() var argumentBuffers = [VulkanArgumentBuffer]() var waitSemaphores = [ResourceSemaphore]() var waitSemaphoreWaitValues = ExpandingBuffer<UInt64>() var signalSemaphores = [VkSemaphore?]() var signalSemaphoreSignalValues = ExpandingBuffer<UInt64>() var presentSwapchains = [VulkanSwapChain]() init(backend: VulkanBackend, queue: VulkanDeviceQueue, commandInfo: FrameCommandInfo<VulkanBackend>, resourceMap: FrameResourceMap<VulkanBackend>, compactedResourceCommands: [CompactedResourceCommand<VulkanCompactedResourceCommandType>]) { self.backend = backend self.queue = queue self.commandBuffer = queue.allocateCommandBuffer() self.commandInfo = commandInfo self.resourceMap = resourceMap self.compactedResourceCommands = compactedResourceCommands var beginInfo = VkCommandBufferBeginInfo() beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO beginInfo.flags = VkCommandBufferUsageFlags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) vkBeginCommandBuffer(self.commandBuffer, &beginInfo).check() } deinit { self.queue.depositCommandBuffer(self.commandBuffer) } var gpuStartTime: Double { return 0.0 } var gpuEndTime: Double { return 0.0 } func encodeCommands(encoderIndex: Int) { let encoderInfo = self.commandInfo.commandEncoders[encoderIndex] switch encoderInfo.type { case .draw: guard let renderEncoder = VulkanRenderCommandEncoder(device: backend.device, renderTarget: encoderInfo.renderTargetDescriptor!, commandBufferResources: self, shaderLibrary: backend.shaderLibrary, caches: backend.stateCaches, resourceMap: self.resourceMap) else { if _isDebugAssertConfiguration() { print("Warning: skipping passes for encoder \(encoderIndex) since the drawable for the render target could not be retrieved.") } return } for passRecord in self.commandInfo.passes[encoderInfo.passRange] { renderEncoder.executePass(passRecord, resourceCommands: self.compactedResourceCommands, passRenderTarget: (passRecord.pass as! DrawRenderPass).renderTargetDescriptor) } case .compute: let computeEncoder = VulkanComputeCommandEncoder(device: backend.device, commandBuffer: self, shaderLibrary: backend.shaderLibrary, caches: backend.stateCaches, resourceMap: resourceMap) for passRecord in self.commandInfo.passes[encoderInfo.passRange] { computeEncoder.executePass(passRecord, resourceCommands: self.compactedResourceCommands) } case .blit: let blitEncoder = VulkanBlitCommandEncoder(device: backend.device, commandBuffer: self, resourceMap: resourceMap) for passRecord in self.commandInfo.passes[encoderInfo.passRange] { blitEncoder.executePass(passRecord, resourceCommands: self.compactedResourceCommands) } case .external, .cpu: break } } func waitForEvent(_ event: VkSemaphore, value: UInt64) { // TODO: wait for more fine-grained pipeline stages. self.waitSemaphores.append(ResourceSemaphore(vkSemaphore: event, stages: VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)) self.waitSemaphoreWaitValues.append(value) } func signalEvent(_ event: VkSemaphore, value: UInt64) { self.signalSemaphores.append(event) self.signalSemaphoreSignalValues.append(value) } func presentSwapchains(resourceRegistry: VulkanTransientResourceRegistry) { // Only contains drawables applicable to the render passes in the command buffer... self.presentSwapchains.append(contentsOf: resourceRegistry.frameSwapChains) // because we reset the list after each command buffer submission. resourceRegistry.clearSwapChains() } func commit(onCompletion: @escaping (VulkanCommandBuffer) -> Void) { vkEndCommandBuffer(self.commandBuffer).check() var submitInfo = VkSubmitInfo() submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO submitInfo.commandBufferCount = 1 let waitSemaphores = self.waitSemaphores.map { $0.vkSemaphore as VkSemaphore? } + self.presentSwapchains.map { $0.acquisitionSemaphore } self.waitSemaphoreWaitValues.append(repeating: 0, count: self.presentSwapchains.count) var waitDstStageMasks = self.waitSemaphores.map { VkPipelineStageFlags($0.stages) } waitDstStageMasks.append(contentsOf: repeatElement(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT.rawValue, count: self.presentSwapchains.count)) // Add a binary semaphore to signal for each presentation swapchain. let signalTimelineSemaphoreCount = self.signalSemaphores.count self.signalSemaphores.append(contentsOf: self.presentSwapchains.map { $0.presentationSemaphore }) self.signalSemaphoreSignalValues.append(repeating: 0, count: self.presentSwapchains.count) var timelineInfo = VkTimelineSemaphoreSubmitInfo() timelineInfo.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO timelineInfo.pNext = nil timelineInfo.waitSemaphoreValueCount = UInt32(waitSemaphores.count) timelineInfo.pWaitSemaphoreValues = UnsafePointer(self.waitSemaphoreWaitValues.buffer) timelineInfo.signalSemaphoreValueCount = UInt32(self.signalSemaphores.count) timelineInfo.pSignalSemaphoreValues = UnsafePointer(self.signalSemaphoreSignalValues.buffer) withUnsafePointer(to: self.commandBuffer as VkCommandBuffer?) { commandBufferPtr in submitInfo.pCommandBuffers = commandBufferPtr submitInfo.signalSemaphoreCount = UInt32(self.signalSemaphores.count) waitSemaphores.withUnsafeBufferPointer { waitSemaphores in submitInfo.pWaitSemaphores = waitSemaphores.baseAddress submitInfo.waitSemaphoreCount = UInt32(waitSemaphores.count) waitDstStageMasks.withUnsafeBufferPointer { waitDstStageMasks in submitInfo.pWaitDstStageMask = waitDstStageMasks.baseAddress self.signalSemaphores.withUnsafeBufferPointer { signalSemaphores in submitInfo.pSignalSemaphores = signalSemaphores.baseAddress withUnsafePointer(to: timelineInfo) { timelineInfo in submitInfo.pNext = UnsafeRawPointer(timelineInfo) vkQueueSubmit(self.queue.vkQueue, 1, &submitInfo, nil).check() } } } } } if !self.presentSwapchains.isEmpty { for drawable in self.presentSwapchains { drawable.submit() } } Self.semaphoreSignalQueue.async { self.signalSemaphores.withUnsafeBufferPointer { signalSemaphores in var waitInfo = VkSemaphoreWaitInfo() waitInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO waitInfo.pSemaphores = signalSemaphores.baseAddress waitInfo.pValues = UnsafePointer(self.signalSemaphoreSignalValues.buffer) waitInfo.semaphoreCount = UInt32(signalTimelineSemaphoreCount) let timeout: UInt64 = 10_000_000_000 // 10s let result = vkWaitSemaphores(self.queue.device.vkDevice, &waitInfo, timeout) if result != VK_SUCCESS { self.error = Error(result: result) } } onCompletion(self) } } private(set) var error: Swift.Error? } #endif // canImport(Vulkan)
45.042654
275
0.664983
4af545144f9523e370673fb3f4c80433bd3a41b9
2,383
// // Map json value that may be optional using `optional: true` parameter. // If the value is null the mapping is considered successful. // // Examples // --------- // // "a string" // 123 // true // null // import UIKit import XCTest import JsonSwiftson class optionalTopLevelValueTests: XCTestCase { // Strings // ------------- func testOptionalString() { let p = JsonSwiftson(json: "\"Marsupials are cute\"") let result: String? = p.map(optional: true) XCTAssert(p.ok) XCTAssertEqual("Marsupials are cute", result!) } func testOptionalString_null() { let p = JsonSwiftson(json: "null") let result: String? = p.map(optional: true) XCTAssert(p.ok) XCTAssert(result == nil) } // ----- errors ----- func testError_optionalString_wrongType() { let p = JsonSwiftson(json: "123456") let result: String? = p.map(optional: true) XCTAssertFalse(p.ok) XCTAssert(result == nil) } func testError_optionalString_incorrectJson() { let p = JsonSwiftson(json: "{ icorrect") let result: String? = p.map(optional: true) XCTAssertFalse(p.ok) XCTAssert(result == nil) } // Numbers // ------------- func testOptionalInteger() { let p = JsonSwiftson(json: "423") let result: Int? = p.map(optional: true) XCTAssert(p.ok) XCTAssertEqual(423, result!) } func testOptionalInteger_null() { let p = JsonSwiftson(json: "null") let result: Int? = p.map(optional: true) XCTAssert(p.ok) XCTAssert(result == nil) } // ----- errors ----- func testError_optionalInteger_wrongType() { let p = JsonSwiftson(json: "\"not a number\"") let result: Int? = p.map(optional: true) XCTAssertFalse(p.ok) XCTAssert(result == nil) } // Booleans // ------------- func testOptionalBool() { let p = JsonSwiftson(json: "true") let result: Bool? = p.map(optional: true) XCTAssert(p.ok) XCTAssertEqual(true, result!) } func testOptionalBool_null() { let p = JsonSwiftson(json: "null") let result: Bool? = p.map(optional: true) XCTAssert(p.ok) XCTAssert(result == nil) } // ----- errors ----- func testError_optionalBool_wrongType() { let p = JsonSwiftson(json: "\"not a bool\"") let result: Bool? = p.map(optional: true) XCTAssertFalse(p.ok) XCTAssert(result == nil) } }
20.543103
73
0.614352
4800ce7b911cf8bf4a61107ecccc0d62a8c53f5e
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let h = [ { { } case let { func a { struct A { let a { class case ,
15.8
87
0.704641
d9ab7d779f017c3619281597216b742e23431efc
1,977
import Cocoa extension NSScreen { public var displayID: CGDirectDisplayID { return (self.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID)! } public var vendorNumber: UInt32? { switch self.displayID.vendorNumber { case 0xFFFF_FFFF: return nil case let vendorNumber: return vendorNumber } } public var modelNumber: UInt32? { switch self.displayID.modelNumber { case 0xFFFF_FFFF: return nil case let modelNumber: return modelNumber } } public var serialNumber: UInt32? { switch self.displayID.serialNumber { case 0x0000_0000: return nil case let serialNumber: return serialNumber } } public var displayName: String? { var servicePortIterator = io_iterator_t() let status = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &servicePortIterator) guard status == KERN_SUCCESS else { return nil } defer { assert(IOObjectRelease(servicePortIterator) == KERN_SUCCESS) } while case let object = IOIteratorNext(servicePortIterator), object != 0 { let dict = (IODisplayCreateInfoDictionary(object, UInt32(kIODisplayOnlyPreferredName)).takeRetainedValue() as NSDictionary as? [String: AnyObject])! if dict[kDisplayVendorID] as? UInt32 == self.vendorNumber, dict[kDisplayProductID] as? UInt32 == self.modelNumber, dict[kDisplaySerialNumber] as? UInt32 == self.serialNumber { if let productName = dict["DisplayProductName"] as? [String: String], let firstKey = Array(productName.keys).first { return productName[firstKey]! } } } return nil } public var isBuiltin: Bool { return CGDisplayIsBuiltin(self.displayID) != 0 } public static func getByDisplayID(displayID: CGDirectDisplayID) -> NSScreen? { return NSScreen.screens.first { $0.displayID == displayID } } }
27.84507
154
0.693475
2382a52525e780937791700f6aa76646d4223388
3,556
/* Copyright 2018 JDCLOUD.COM 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. 京东云官网公告API 提供公告操作的相关接口 OpenAPI spec version: v1 Contact: NOTE: This class is auto generated by the jdcloud code generator program. */ import Foundation import JDCloudSDKCore public class PortalJDCloudClient:NSObject,JDCloudClient{ private final var portalJDCloudClient:PortalJDCloudClient! public convenience init(credential:Credential,sdkEnvironment:SDKEnvironment) { self.init() self.credential = credential self.sdkEnvironment = sdkEnvironment portalJDCloudClient = self } public override init() { if(GlobalConfig.credential == nil) { GlobalConfig.credential = Credential(accessKeyId: "",secretAccessKey: "") } var sdkEnvironment:SDKEnvironment if(GlobalConfig.sdkEnvironment != nil) { sdkEnvironment = GlobalConfig.sdkEnvironment! }else{ sdkEnvironment = SDKEnvironment(endPoint: "portal.jdcloud-api.com"); } self.credential = GlobalConfig.credential! self.sdkEnvironment = sdkEnvironment super.init() portalJDCloudClient = self } public let userAgent: String = "JdcloudSdkSwift/" + "0.0.1/" + "portal/" + "v1" public let serviceName: String = "portal" public let version: String = "v1" public let contentType:String = "application/json" public var credential: Credential public var sdkEnvironment: SDKEnvironment public var customHeader: [String : String] = [String:String]() public var httpRequestProtocol: String = "https" public func addCustomer(key: String, value: String) { customHeader[key] = value } public func describeProductAsync(request:DescribeProductRequest,requestComplation:@escaping ExecuteResult<DescribeProductResult>) throws { portalJDCloudClient = self try DescribeProductExecutor(jdCloudClient: portalJDCloudClient).executeAsync(request: request) { (statusCode,result,error,data) in requestComplation(statusCode,result,error,data) } } public func describeProductsByIdAsync(request:DescribeProductsByIdRequest,requestComplation:@escaping ExecuteResult<DescribeProductsByIdResult>) throws { portalJDCloudClient = self try DescribeProductsByIdExecutor(jdCloudClient: portalJDCloudClient).executeAsync(request: request) { (statusCode,result,error,data) in requestComplation(statusCode,result,error,data) } } } public extension PortalJDCloudClient{ convenience init(credential: Credential) { var sdkEnvironment:SDKEnvironment if(GlobalConfig.sdkEnvironment != nil) { sdkEnvironment = GlobalConfig.sdkEnvironment! }else{ sdkEnvironment = SDKEnvironment(endPoint: "portal.jdcloud-api.com"); } self.init(credential: credential,sdkEnvironment: sdkEnvironment) } }
30.135593
157
0.694882
89a36e989e69042c010cbf8217435a6c5db56159
869
// // CategoryCollectionViewCell.swift // Mah Income // // Created by Van Luu on 4/17/17. // Copyright © 2017 Van Luu. All rights reserved. // import UIKit class CategoryCollectionViewCell: UICollectionViewCell { @IBOutlet weak var categoryLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() categoryLabel.layer.cornerRadius = min(bounds.width, bounds.height)/2 categoryLabel.layer.masksToBounds = true } func configure(model: CategoryModel) { categoryLabel.text = model._name } override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { guard let attribute = layoutAttributes as? CategoryLayoutAttribute else { return } categoryLabel.alpha = attribute.alphaFactor categoryLabel.transform = CGAffineTransform(scaleX: attribute.scaleFactor, y: attribute.scaleFactor) } }
26.333333
104
0.741082
e9591f9162453ac4c942fdd87b1c16fd6d625097
489
// // Extension + UITableView.swift // AppCenter // // Created by Medyannik Dmitri on 27.01.2020. // Copyright © 2020 Medyannik Dima. All rights reserved. // import UIKit extension UITableView { func registerNibForCell<T>(_ class: T) { var className = String(describing: T.self) className = String(className.dropLast(5)) // dropping ".Type" let nib = UINib(nibName: className, bundle: nil) register(nib, forCellReuseIdentifier: className) } }
25.736842
69
0.670757
5b43cf5676b9c8096282257d03301c6105423d07
65,664
// 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 // import CoreFoundation public typealias unichar = UInt16 extension unichar : ExpressibleByUnicodeScalarLiteral { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } #if os(OSX) || os(iOS) internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC #endif extension NSString { public struct EncodingConversionOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let allowLossy = EncodingConversionOptions(rawValue: 1) public static let externalRepresentation = EncodingConversionOptions(rawValue: 2) internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20) } public struct EnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let byLines = EnumerationOptions(rawValue: 0) public static let byParagraphs = EnumerationOptions(rawValue: 1) public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2) public static let byWords = EnumerationOptions(rawValue: 3) public static let bySentences = EnumerationOptions(rawValue: 4) public static let reverse = EnumerationOptions(rawValue: 1 << 8) public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9) public static let localized = EnumerationOptions(rawValue: 1 << 10) internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20) } } extension NSString { public struct CompareOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let caseInsensitive = CompareOptions(rawValue: 1) public static let literal = CompareOptions(rawValue: 2) public static let backwards = CompareOptions(rawValue: 4) public static let anchored = CompareOptions(rawValue: 8) public static let numeric = CompareOptions(rawValue: 64) public static let diacriticInsensitive = CompareOptions(rawValue: 128) public static let widthInsensitive = CompareOptions(rawValue: 256) public static let forcedOrdering = CompareOptions(rawValue: 512) public static let regularExpression = CompareOptions(rawValue: 1024) internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags { #if os(OSX) || os(iOS) return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral) #else return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral) #endif } } } internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? { struct local { static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = { let cache = NSCache<NSString, NSRegularExpression>() cache.name = "NSRegularExpressionCache" cache.countLimit = 10 return cache }() } let key = "\(options):\(pattern)" if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) { return regex } do { let regex = try NSRegularExpression(pattern: pattern, options: options) local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject) return regex } catch { } return nil } internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? { let theRange = NSMakeRange(0, str.length) var cLength = 0 var used = 0 var options: NSString.EncodingConversionOptions = [] if externalRep { options.formUnion(.externalRepresentation) } if lossy { options.formUnion(.allowLossy) } if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { if fatalOnError { fatalError("Conversion on encoding failed") } return nil } let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1) if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation") } buffer.advanced(by: cLength).initialize(to: 0) return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here } internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029 } internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x2029 } open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID()) internal var _storage: String open var length: Int { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } return _storage.utf16.count } open func character(at index: Int) -> unichar { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex return _storage.utf16[start.advanced(by: index)] } public override convenience init() { let characters = Array<unichar>(repeating: 0, count: 1) self.init(characters: characters, length: 0) } internal init(_ string: String) { _storage = string } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") { let str = aDecoder._decodePropertyListForKey("NS.string") as! String self.init(string: str) } else { let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") { guard let buffer = $0 else { return nil } return Data(buffer: buffer) } guard let data = decodedData else { return nil } self.init(data: data, encoding: String.Encoding.utf8.rawValue) } } public required convenience init(string aString: String) { self.init(aString) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSString.self || type(of: self) === NSMutableString.self { if let contents = _fastContents { return NSMutableString(characters: contents, length: length) } } let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length) getCharacters(characters, range: NSMakeRange(0, length)) let result = NSMutableString(characters: characters, length: length) characters.deinitialize() characters.deallocate(capacity: length) return result } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.string") } else { aCoder.encode(self) } } public init(characters: UnsafePointer<unichar>, length: Int) { _storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { _storage = String(describing: value) } public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { self.init(string: CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject) } internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._core.isASCII { return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self) } } return nil } internal var _fastContents: UnsafePointer<UniChar>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if !_storage._core.isASCII { return UnsafePointer<UniChar>(_storage._core.startUTF16) } } return nil } internal var _encodingCantBeStoredInEightBitCFString: Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return !_storage._core.isASCII } return false } override open var _cfTypeID: CFTypeID { return CFStringGetTypeID() } open override func isEqual(_ object: Any?) -> Bool { guard let string = (object as? NSString)?._swiftObject else { return false } return self.isEqual(to: string) } open override var description: String { return _swiftObject } open override var hash: Int { return Int(bitPattern:CFStringHashNSString(self._cfObject)) } } extension NSString { public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) { for idx in 0..<range.length { buffer[idx] = character(at: idx + range.location) } } public func substring(from: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.suffix(from: _storage.utf16.startIndex.advanced(by: from)))! } else { return substring(with: NSMakeRange(from, length - from)) } } public func substring(to: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.prefix(upTo: _storage.utf16.startIndex .advanced(by: to)))! } else { return substring(with: NSMakeRange(0, to)) } } public func substring(with range: NSRange) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { let start = _storage.utf16.startIndex let min = start.advanced(by: range.location) let max = start.advanced(by: range.location + range.length) return String(decoding: _storage.utf16[min..<max], as: UTF16.self) } else { let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length) getCharacters(buff, range: range) let result = String(describing: buff) buff.deinitialize() buff.deallocate(capacity: range.length) return result } } public func compare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSMakeRange(0, length)) } public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult { return compare(string, options: mask, range: NSMakeRange(0, length)) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult { return compare(string, options: mask, range: compareRange, locale: nil) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult { var res: CFComparisonResult if let loc = locale { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject) } else { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil) } return ComparisonResult._fromCF(res) } public func caseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length)) } public func localizedCompare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedStandardCompare(_ string: String) -> ComparisonResult { return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC()) } public func isEqual(to aString: String) -> Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return _storage == aString } else { return length == aString.length && compare(aString, options: .literal, range: NSMakeRange(0, length)) == .orderedSame } } public func hasPrefix(_ str: String) -> Bool { return range(of: str, options: .anchored, range: NSMakeRange(0, length)).location != NSNotFound } public func hasSuffix(_ str: String) -> Bool { return range(of: str, options: [.anchored, .backwards], range: NSMakeRange(0, length)).location != NSNotFound } public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String { var currentSubstring: CFMutableString? let isLiteral = mask.contains(.literal) var lastMatch = NSRange() let selfLen = length let otherLen = str.length var low = 0 var high = selfLen var probe = (low + high) / 2 if (probe > otherLen) { probe = otherLen // A little heuristic to avoid some extra work } if selfLen == 0 || otherLen == 0 { return "" } var numCharsBuffered = 0 var arrayBuffer = [unichar](repeating: 0, count: 100) let other = str._nsObject return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in // Now do the binary search. Note that the probe value determines the length of the substring to check. while true { let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence if range.length > numCharsBuffered { // Buffer more characters if needed getCharacters(selfChars, range: NSMakeRange(numCharsBuffered, range.length - numCharsBuffered)) numCharsBuffered = range.length } if currentSubstring == nil { currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull) } else { CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length) } if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSMakeRange(0, otherLen)).length != 0 { // Match lastMatch = range low = probe + 1 } else { high = probe } if low >= high { break } probe = (low + high) / 2 } return lastMatch.length != 0 ? substring(with: lastMatch) : "" } } public func contains(_ str: String) -> Bool { return range(of: str, options: [], range: NSMakeRange(0, length), locale: nil).location != NSNotFound } public func localizedCaseInsensitiveContains(_ str: String) -> Bool { return range(of: str, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound } public func localizedStandardContains(_ str: String) -> Bool { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound } public func localizedStandardRange(of str: String) -> NSRange { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current) } public func range(of searchString: String) -> NSRange { return range(of: searchString, options: [], range: NSMakeRange(0, length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange { return range(of: searchString, options: mask, range: NSMakeRange(0, length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { return range(of: searchString, options: mask, range: searchRange, locale: nil) } internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange { var matchedRange = NSMakeRange(NSNotFound, 0) let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSMatchingOptions = mask.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange) } return matchedRange } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange { let findStrLen = searchString.length let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") if mask.contains(.regularExpression) { return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale) } if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares return NSMakeRange(NSNotFound, 0) } var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if let loc = locale { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep) } else { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep) } } if res { return NSMakeRange(result.location, result.length) } else { return NSMakeRange(NSNotFound, 0) } } public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange { return rangeOfCharacter(from: searchSet, options: [], range: NSMakeRange(0, length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange { return rangeOfCharacter(from: searchSet, options: mask, range: NSMakeRange(0, length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep) } if res { return NSMakeRange(result.location, result.length) } else { return NSMakeRange(NSNotFound, 0) } } public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange { let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster) return NSMakeRange(range.location, range.length) } public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange { let length = self.length var start: Int var end: Int if range.location == length { start = length } else { start = rangeOfComposedCharacterSequence(at: range.location).location } var endOfRange = NSMaxRange(range) if endOfRange == length { end = length } else { if range.length > 0 { endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range. } end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange)) } return NSMakeRange(start, end - start) } public func appending(_ aString: String) -> String { return _swiftObject + aString } public var doubleValue: Double { var start: Int = 0 var result = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in result = value } return result } public var floatValue: Float { var start: Int = 0 var result: Float = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in result = value } return result } public var intValue: Int32 { return Scanner(string: _swiftObject).scanInt32() ?? 0 } public var integerValue: Int { let scanner = Scanner(string: _swiftObject) var value: Int = 0 let _ = scanner.scanInt(&value) return value } public var longLongValue: Int64 { return Scanner(string: _swiftObject).scanInt64() ?? 0 } public var boolValue: Bool { let scanner = Scanner(string: _swiftObject) // skip initial whitespace if present let _ = scanner.scanCharactersFromSet(.whitespaces) // scan a single optional '+' or '-' character, followed by zeroes if scanner.scanString("+") == nil { let _ = scanner.scanString("-") } // scan any following zeroes let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0")) return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil } public var uppercased: String { return uppercased(with: nil) } public var lowercased: String { return lowercased(with: nil) } public var capitalized: String { return capitalized(with: nil) } public var localizedUppercase: String { return uppercased(with: Locale.current) } public var localizedLowercase: String { return lowercased(with: Locale.current) } public var localizedCapitalized: String { return capitalized(with: Locale.current) } public func uppercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringUppercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func lowercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringLowercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func capitalized(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) { let len = length var ch: unichar precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)") if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often startPtr?.pointee = 0 endPtr?.pointee = range.length return } /* Find the starting point first */ if startPtr != nil { var start: Int = 0 if range.location == 0 { start = 0 } else { var buf = _NSStringBuffer(string: self, start: range.location, end: len) /* Take care of the special case where start happens to fall right between \r and \n */ ch = buf.currentCharacter buf.rewind() if ch == 0x0a && buf.currentCharacter == 0x0d { buf.rewind() } while true { if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) { start = buf.location + 1 break } else if buf.location <= 0 { start = 0 break } else { buf.rewind() } } startPtr!.pointee = start } } if (endPtr != nil || contentsEndPtr != nil) { var endOfContents = 1 var lineSeparatorLength = 1 var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len) /* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */ ch = buf.currentCharacter if ch == 0x0a { endOfContents = buf.location buf.rewind() if buf.currentCharacter == 0x0d { lineSeparatorLength = 2 endOfContents -= 1 } } else { while true { if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) { endOfContents = buf.location /* This is actually end of contentsRange */ buf.advance() /* OK for this to go past the end */ if ch == 0x0d && buf.currentCharacter == 0x0a { lineSeparatorLength = 2 } break } else if buf.location == len { endOfContents = len lineSeparatorLength = 0 break } else { buf.advance() ch = buf.currentCharacter } } } contentsEndPtr?.pointee = endOfContents endPtr?.pointee = endOfContents + lineSeparatorLength } } public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true) } public func lineRange(for range: NSRange) -> NSRange { var start = 0 var lineEnd = 0 getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range) return NSMakeRange(start, lineEnd - start) } public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false) } public func paragraphRange(for range: NSRange) -> NSRange { var start = 0 var parEnd = 0 getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range) return NSMakeRange(start, parEnd - start) } public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateSubstrings(in: NSMakeRange(0, length), options:.byLines) { substr, substrRange, enclosingRange, stop in block(substr!, stop) } } public var utf8String: UnsafePointer<Int8>? { return _bytesInEncoding(self, String.Encoding.utf8, false, false, false) } public var fastestEncoding: UInt { return String.Encoding.unicode.rawValue } public var smallestEncoding: UInt { if canBeConverted(to: String.Encoding.ascii.rawValue) { return String.Encoding.ascii.rawValue } return String.Encoding.unicode.rawValue } public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? { let len = length var reqSize = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) if !CFStringIsEncodingAvailable(cfStringEncoding) { return nil } let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize) if convertedLen != len { return nil // Not able to do it all... } if 0 < reqSize { var data = Data(count: reqSize) data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen { return reqSize } else { fatalError("didn't convert all characters") } } return data } return Data() } public func data(using encoding: UInt) -> Data? { return data(using: encoding, allowLossyConversion: false) } public func canBeConverted(to encoding: UInt) -> Bool { if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue { return true } return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length } public func cString(using encoding: UInt) -> UnsafePointer<Int8>? { return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false) } public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool { var used = 0 if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._core.isASCII { used = min(self.length, maxBufferCount - 1) _storage._core.startASCII.withMemoryRebound(to: Int8.self, capacity: used) { buffer.moveAssign(from: $0, count: used) } buffer.advanced(by: used).initialize(to: 0) return true } } if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) { buffer.advanced(by: used).initialize(to: 0) return true } return false } public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool { var totalBytesWritten = 0 var numCharsProcessed = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) var result = true if length > 0 { if CFStringIsEncodingAvailable(cfStringEncoding) { let lossyOk = options.contains(.allowLossy) let externalRep = options.contains(.externalRepresentation) let failOnPartial = options.contains(.failOnPartialEncodingConversion) let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount) numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten) if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 { result = false } } else { result = false /* ??? Need other encodings */ } } usedBufferCount?.pointee = totalBytesWritten leftover?.pointee = NSMakeRange(range.location + numCharsProcessed, range.length - numCharsProcessed) return result } public func maximumLengthOfBytes(using enc: UInt) -> Int { let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let result = CFStringGetMaximumSizeForEncoding(length, cfEnc) return result == kCFNotFound ? 0 : result } public func lengthOfBytes(using enc: UInt) -> Int { let len = length var numBytes: CFIndex = 0 let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes) return convertedLen != len ? 0 : numBytes } open class var availableStringEncodings: UnsafePointer<UInt> { struct once { static let encodings: UnsafePointer<UInt> = { let cfEncodings = CFStringGetListOfAvailableEncodings()! var idx = 0 var numEncodings = 0 while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId { idx += 1 numEncodings += 1 } let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1) theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator numEncodings -= 1 while numEncodings >= 0 { theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee) numEncodings -= 1 } return UnsafePointer<UInt>(theEncodingList) }() } return once.encodings } open class func localizedName(of encoding: UInt) -> String { if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) { // TODO: read the localized version from the Foundation "bundle" return theString._swiftObject } return "" } open class var defaultCStringEncoding: UInt { return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding()) } open var decomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormD) return string._swiftObject } open var precomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormC) return string._swiftObject } open var decomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKD) return string._swiftObject } open var precomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKC) return string._swiftObject } open func components(separatedBy separator: String) -> [String] { let len = length var lrange = range(of: separator, options: [], range: NSMakeRange(0, len)) if lrange.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSMakeRange(0, len) while true { let trange = NSMakeRange(srange.location, lrange.location - srange.location) array.append(substring(with: trange)) srange.location = lrange.location + lrange.length srange.length = len - srange.location lrange = range(of: separator, options: [], range: srange) if lrange.length == 0 { break } } array.append(substring(with: srange)) return array } } open func components(separatedBy separator: CharacterSet) -> [String] { let len = length var range = rangeOfCharacter(from: separator, options: [], range: NSMakeRange(0, len)) if range.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSMakeRange(0, len) while true { let trange = NSMakeRange(srange.location, range.location - srange.location) array.append(substring(with: trange)) srange.location = range.location + range.length srange.length = len - srange.location range = rangeOfCharacter(from: separator, options: [], range: srange) if range.length == 0 { break } } array.append(substring(with: srange)) return array } } open func trimmingCharacters(in set: CharacterSet) -> String { let len = length var buf = _NSStringBuffer(string: self, start: 0, end: len) while !buf.isAtEnd, let character = UnicodeScalar(buf.currentCharacter), set.contains(character) { buf.advance() } let startOfNonTrimmedRange = buf.location // This points at the first char not in the set if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line. return "" } else if startOfNonTrimmedRange < len - 1 { buf.location = len - 1 while let character = UnicodeScalar(buf.currentCharacter), set.contains(character), buf.location >= startOfNonTrimmedRange { buf.rewind() } let endOfNonTrimmedRange = buf.location return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange)) } else { return substring(with: NSMakeRange(startOfNonTrimmedRange, 1)) } } open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String { let len = length if newLength <= len { // The simple cases (truncation) return newLength == len ? _swiftObject : substring(with: NSMakeRange(0, newLength)) } let padLen = padString.length if padLen < 1 { fatalError("empty pad string") } if padIndex >= padLen { fatalError("out of range padIndex") } let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)! CFStringPad(mStr, padString._cfObject, newLength, padIndex) return mStr._swiftObject } open func folding(options: CompareOptions = [], locale: Locale?) -> String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringFold(string, options._cfValue(), locale?._cfObject) return string._swiftObject } internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement) } return "" } open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String { if options.contains(.regularExpression) { return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange) } let str = mutableCopy(with: nil) as! NSMutableString if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 { return _swiftObject } else { return str._swiftObject } } open func replacingOccurrences(of target: String, with replacement: String) -> String { return replacingOccurrences(of: target, with: replacement, options: [], range: NSMakeRange(0, length)) } open func replacingCharacters(in range: NSRange, with replacement: String) -> String { let str = mutableCopy(with: nil) as! NSMutableString str.replaceCharacters(in: range, with: replacement) return str._swiftObject } open func applyingTransform(_ transform: String, reverse: Bool) -> String? { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, _cfObject) if (CFStringTransform(string, nil, transform._cfObject, reverse)) { return string._swiftObject } else { return nil } } internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws { let length = self.length var numBytes = 0 let theRange = NSMakeRange(0, length) if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } var mData = Data(count: numBytes) // The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?) var used = 0 // This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers. try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } } data = mData } internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws { var data = Data() try _getExternalRepresentation(&data, url, enc) try data.write(to: url, options: useAuxiliaryFile ? .atomic : []) } open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(url, useAuxiliaryFile, enc) } open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc) } public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // ignore the no-copy-ness self.init(characters: characters, length: length) if freeBuffer { // cant take a hint here... free(UnsafeMutableRawPointer(characters)) } } public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) { let count = Int(strlen(nullTerminatedCString)) if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, { let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count) return String._fromCodeUnitSequence(UTF8.self, input: buffer) }) as String? { self.init(str) } else { return nil } } public convenience init(format: String, arguments argList: CVaListPointer) { let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)! self.init(str._swiftObject) } public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) { let str: CFString if let loc = locale { if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList) } else { fatalError("locale parameter must be a NSLocale or a NSDictionary") } } else { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList) } self.init(str._swiftObject) } public convenience init(format: NSString, _ args: CVarArg...) { let str = withVaList(args) { (vaPtr) -> CFString! in CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr) }! self.init(str._swiftObject) } public convenience init?(data: Data, encoding: UInt) { if data.isEmpty { self.init("") } else { guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true) }) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } } public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) { let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // just copy for now since the internal storage will be a copy anyhow self.init(bytes: bytes, length: len, encoding: encoding) if freeBuffer { // dont take the hint free(bytes) } } public convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { guard let cf = CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } public convenience init(contentsOf url: URL, encoding enc: UInt) throws { let readResult = try NSData(contentsOf: url, options: []) let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } } public convenience init(contentsOfFile path: String, encoding enc: UInt) throws { try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc) } public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { let readResult = try NSData(contentsOf: url, options:[]) let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length) if readResult.length >= 2 && bytePtr[0] == 254 && bytePtr[1] == 255 { enc?.pointee = String.Encoding.utf16BigEndian.rawValue } else if readResult.length >= 2 && bytePtr[0] == 255 && bytePtr[1] == 254 { enc?.pointee = String.Encoding.utf16LittleEndian.rawValue } else { //Need to work on more conditions. This should be the default enc?.pointee = String.Encoding.utf8.rawValue } guard let enc = enc, let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc.pointee), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } } public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { NSUnimplemented() } } extension NSString : ExpressibleByStringLiteral { } open class NSMutableString : NSString { open func replaceCharacters(in range: NSRange, with aString: String) { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)! let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)! _storage.replaceSubrange(min..<max, with: aString) } public required override init(characters: UnsafePointer<unichar>, length: Int) { super.init(characters: characters, length: length) } public required init(capacity: Int) { super.init(characters: [], length: 0) } public convenience required init?(coder aDecoder: NSCoder) { guard let str = NSString(coder: aDecoder) else { return nil } self.init(string: String._unconditionallyBridgeFromObjectiveC(str)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount)))) } else { var uintValue = value.unicodeScalar.value super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1))) } } public required init(string aString: String) { super.init(aString) } internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) { if type(of: self) == NSMutableString.self { _storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } else { replaceCharacters(in: NSMakeRange(self.length, 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } } internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) { if type(of: self) == NSMutableString.self { _storage.append(String(cString: characters)) } } } extension NSMutableString { public func insert(_ aString: String, at loc: Int) { replaceCharacters(in: NSMakeRange(loc, 0), with: aString) } public func deleteCharacters(in range: NSRange) { replaceCharacters(in: range, with: "") } public func append(_ aString: String) { replaceCharacters(in: NSMakeRange(length, 0), with: aString) } public func setString(_ aString: String) { replaceCharacters(in: NSMakeRange(0, length), with: aString) } internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement) } return 0 } public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int { let backwards = options.contains(.backwards) let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds") if options.contains(.regularExpression) { return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange) } if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) { let numOccurrences = CFArrayGetCount(findResults) for cnt in 0..<numOccurrences { let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1) replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement) } return numOccurrences } else { return 0 } } public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool { var cfRange = CFRangeMake(range.location, range.length) return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) { resultingRange?.pointee.location = rangep.pointee.location resultingRange?.pointee.length = rangep.pointee.length return true } return false } } } extension String { // this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters internal var length: Int { return utf16.count } } extension NSString : _CFBridgeable, _SwiftBridgeable { typealias SwiftType = String internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) } internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) } } extension NSMutableString { internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) } } extension CFString : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSString typealias SwiftType = String internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) } internal var _swiftObject: String { return _nsObject._swiftObject } } extension String : _NSBridgeable, _CFBridgeable { typealias NSType = NSString typealias CFType = CFString internal var _nsObject: NSType { return _bridgeToObjectiveC() } internal var _cfObject: CFType { return _nsObject._cfObject } } #if !(os(OSX) || os(iOS)) extension String { public func hasPrefix(_ prefix: String) -> Bool { if prefix.isEmpty { return true } let cfstring = self._cfObject let range = CFRangeMake(0, CFStringGetLength(cfstring)) let opts = CFStringCompareFlags( kCFCompareAnchored | kCFCompareNonliteral) return CFStringFindWithOptions(cfstring, prefix._cfObject, range, opts, nil) } public func hasSuffix(_ suffix: String) -> Bool { if suffix.isEmpty { return true } let cfstring = self._cfObject let range = CFRangeMake(0, CFStringGetLength(cfstring)) let opts = CFStringCompareFlags( kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral) return CFStringFindWithOptions(cfstring, suffix._cfObject, range, opts, nil) } } #endif extension NSString : _StructTypeBridgeable { public typealias _StructType = String public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
43.981246
274
0.642788
efb5ea7fd332f05425de0ad5ad4a4bf220abd5a5
276
// // AppDelegate.swift // IncentCleanerCheckerExample // // Created by Appbooster on 03/09/2019. // Copyright © 2019 Appbooster. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
16.235294
55
0.742754
898dc64fe5ced1dd46c15c0c23c1ef281cf9580b
5,317
// // DownloadtaskModel.swift // DownloadTask // // Created by recherst on 2021/8/10. // import Foundation import UIKit import SwiftUI class DownloadTaskModel: NSObject, ObservableObject, URLSessionDownloadDelegate, UIDocumentInteractionControllerDelegate { @Published var downloadURL: URL! // Alert @Published var alertMsg = "" @Published var showAlert = false // Saving download task reference for cancelling @Published var downloadTaskSession: URLSessionDownloadTask! // Progress @Published var downloadProgress: CGFloat = 0 // Show progress view @Published var showDownloadProgress = false // Download function func startDownload(urlString: String) { // Checking for valid URL guard let validURL = URL(string: urlString) else { reportError(error: "Invalid URL!!!") return } // Presenting downloading the same file again let directoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] if FileManager.default.fileExists(atPath: directoryPath.appendingPathComponent(validURL.lastPathComponent).path) { print("yes file found") let controller = UIDocumentInteractionController(url: directoryPath.appendingPathComponent(validURL.lastPathComponent)) controller.delegate = self controller.presentPreview(animated: true) } else { print("no file found") // Valid URL downloadProgress = 0 withAnimation { self.showDownloadProgress = true } // Download task // Since we're going to get the progress as well as location of file so we're using delegate let seesion = URLSession(configuration: .default, delegate: self, delegateQueue: nil) downloadTaskSession = seesion.downloadTask(with: validURL) downloadTaskSession.resume() } } func reportError(error: String) { alertMsg = error showAlert.toggle() } // Implementing URLSession Functions func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { // Since it will download it as temporay data // so we're going to save it in app document directory and showing it in document controller guard let url = downloadTask.originalRequest?.url else { DispatchQueue.main.async { self.reportError(error: "Something went wrong please try again later") } return } // Diretory path let directoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // Creating one for storing file // Destination URL // Get the mp4 let destinationURL = directoryPath.appendingPathComponent(url.lastPathComponent) // if already file is there removing that try? FileManager.default.removeItem(at: destinationURL) do { // Copying temp file to directory try FileManager.default.copyItem(at: location, to: destinationURL) // If success print("success") // Closing progress view DispatchQueue.main.async { withAnimation { self.showDownloadProgress = false } // presenting the file with the help of document interaction controller from UIKit let controller = UIDocumentInteractionController(url: destinationURL) // it needs a delegate controller.delegate = self controller.presentPreview(animated: true) } } catch { DispatchQueue.main.async { self.reportError(error: "Please try again later!!!") } } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { // Get progress let progress = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) // since url session will be running in BG thread // so UI updates will be done on main threads DispatchQueue.main.async { self.downloadProgress = progress } } // error func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { DispatchQueue.main.async { if let error = error { withAnimation { self.showDownloadProgress = true } self.reportError(error: error.localizedDescription) return } } } // Cancel task func cacelTask() { if let task = downloadTaskSession, task.state == .running { // Cancel downloadTaskSession.cancel() // Closing view withAnimation { self.showDownloadProgress = false } } } // Sub functions for presenting view func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return UIApplication.shared.windows.first!.rootViewController! } }
35.925676
176
0.638706
1cfd3e03305f8a69bfe60b18d148d0ca40dcf6a7
13,203
// // BBMetalVideoWriter.swift // BBMetalImage // // Created by Kaibo Lu on 4/30/19. // Copyright © 2019 Kaibo Lu. All rights reserved. // import AVFoundation public typealias BBMetalVideoWriterProgress = (BBMetalVideoWriterProgressType) -> Void public enum BBMetalVideoWriterProgressType { case video(CMTime, Bool) case audio(CMTime, Bool) } /// Video writer writing video file public class BBMetalVideoWriter { /// URL of video file public let url: URL /// Video frame size public let frameSize: BBMetalIntSize /// Video file type public let fileType: AVFileType /// Video settings public let outputSettings: [String : Any] private var computePipeline: MTLComputePipelineState! private var outputTexture: MTLTexture! private let threadgroupSize: MTLSize private var threadgroupCount: MTLSize private var writer: AVAssetWriter! private var videoInput: AVAssetWriterInput! private var videoPixelBufferInput: AVAssetWriterInputPixelBufferAdaptor! private var videoPixelBuffer: CVPixelBuffer! /// Whether the video contains audio track (true by default) public var hasAudioTrack: Bool { get { lock.wait() let h = _hasAudioTrack lock.signal() return h } set { lock.wait() _hasAudioTrack = newValue lock.signal() } } private var _hasAudioTrack: Bool /// A Boolean value (true by defaut) that indicates whether the input should tailor its processing of media data for real-time sources public var expectsMediaDataInRealTime: Bool { get { lock.wait() let e = _expectsMediaDataInRealTime lock.signal() return e } set { lock.wait() _expectsMediaDataInRealTime = newValue lock.signal() } } private var _expectsMediaDataInRealTime: Bool private var audioInput: AVAssetWriterInput! private var progress: BBMetalVideoWriterProgress? private let lock: DispatchSemaphore deinit { lock.wait() NotificationCenter.default.removeObserver(self) lock.signal() } public init(url: URL, frameSize: BBMetalIntSize, fileType: AVFileType = .mp4, outputSettings: [String : Any] = [AVVideoCodecKey : AVVideoCodecType.h264]) { self.url = url self.frameSize = frameSize self.fileType = fileType self.outputSettings = outputSettings let library = try! BBMetalDevice.sharedDevice.makeDefaultLibrary(bundle: Bundle(for: BBMetalVideoWriter.self)) let kernelFunction = library.makeFunction(name: "passThroughKernel")! computePipeline = try! BBMetalDevice.sharedDevice.makeComputePipelineState(function: kernelFunction) let descriptor = MTLTextureDescriptor() descriptor.pixelFormat = .bgra8Unorm descriptor.width = frameSize.width descriptor.height = frameSize.height descriptor.usage = [.shaderRead, .shaderWrite] outputTexture = BBMetalDevice.sharedDevice.makeTexture(descriptor: descriptor) threadgroupSize = MTLSize(width: 16, height: 16, depth: 1) threadgroupCount = MTLSize(width: (frameSize.width + threadgroupSize.width - 1) / threadgroupSize.width, height: (frameSize.height + threadgroupSize.height - 1) / threadgroupSize.height, depth: 1) _hasAudioTrack = true _expectsMediaDataInRealTime = true lock = DispatchSemaphore(value: 1) } /// Starts receiving Metal texture and writing video file public func start(progress: BBMetalVideoWriterProgress? = nil) { lock.wait() defer { lock.signal() } self.progress = progress if writer == nil { if !prepareAssetWriter() { reset() return } } else { print("Should not call \(#function) before last writing operation is finished") return } if !writer.startWriting() { reset() print("Asset writer can not start writing") } } /// Finishes writing video file /// /// - Parameter completion: a closure to call after writing video file public func finish(completion: (() -> Void)?) { lock.wait() defer { lock.signal() } if let videoInput = self.videoInput, let writer = self.writer, writer.status == .writing { videoInput.markAsFinished() if let audioInput = self.audioInput { audioInput.markAsFinished() } let name = "com.Kaibo.BBMetalImage.VideoWriter.Finish" let object = NSObject() NotificationCenter.default.addObserver(self, selector: #selector(finishWritingNotification(_:)), name: NSNotification.Name(name), object: object) writer.finishWriting { // The comment code below leads to memory leak even using [weak self]. // Using [unowned self] solves the memory leak, but not safe. // So use notification here. /* [weak self] in guard let self = self else { return } self.lock.wait() self.reset() self.lock.signal() */ NotificationCenter.default.post(name: NSNotification.Name(name), object: object, userInfo: nil) completion?() } } else { print("Should not call \(#function) while video writer is not writing") } } /// Cancels writing video file public func cancel() { lock.wait() defer { lock.signal() } if let videoInput = self.videoInput, let writer = self.writer, writer.status == .writing { videoInput.markAsFinished() if let audioInput = self.audioInput { audioInput.markAsFinished() } writer.cancelWriting() reset() } else { print("Should not call \(#function) while video writer is not writing") } } private func prepareAssetWriter() -> Bool { writer = try? AVAssetWriter(url: url, fileType: fileType) if writer == nil { print("Can not create asset writer") return false } var settings = outputSettings settings[AVVideoWidthKey] = frameSize.width settings[AVVideoHeightKey] = frameSize.height videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: settings) videoInput.expectsMediaDataInRealTime = _expectsMediaDataInRealTime if !writer.canAdd(videoInput) { print("Asset writer can not add video input") return false } writer.add(videoInput) let attributes: [String : Any] = [kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA, kCVPixelBufferWidthKey as String : frameSize.width, kCVPixelBufferHeightKey as String : frameSize.height] videoPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoInput, sourcePixelBufferAttributes: attributes) if _hasAudioTrack { let settings: [String : Any] = [AVFormatIDKey : kAudioFormatMPEG4AAC, AVNumberOfChannelsKey : 1, AVSampleRateKey : AVAudioSession.sharedInstance().sampleRate] audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: settings) audioInput.expectsMediaDataInRealTime = _expectsMediaDataInRealTime if !writer.canAdd(audioInput) { print("Asset writer can not add audio input") return false } writer.add(audioInput) } return true } private func reset() { writer = nil videoInput = nil videoPixelBufferInput = nil videoPixelBuffer = nil audioInput = nil progress = nil } @objc private func finishWritingNotification(_ notification: Notification) { lock.wait() reset() NotificationCenter.default.removeObserver(self, name: notification.name, object: notification.object) lock.signal() } } extension BBMetalVideoWriter: BBMetalImageConsumer { public func add(source: BBMetalImageSource) {} public func remove(source: BBMetalImageSource) {} public func newTextureAvailable(_ texture: BBMetalTexture, from source: BBMetalImageSource) { lock.wait() let progress = self.progress var result: Bool? defer { lock.signal() if let progress = progress, let result = result, let sampleTime = texture.sampleTime { progress(.video(sampleTime, result)) } } // Check nil guard let sampleTime = texture.sampleTime, let writer = self.writer, let videoInput = self.videoInput, let videoPixelBufferInput = self.videoPixelBufferInput else { return } if videoPixelBuffer == nil { // First frame writer.startSession(atSourceTime: sampleTime) guard let pool = videoPixelBufferInput.pixelBufferPool, CVPixelBufferPoolCreatePixelBuffer(nil, pool, &videoPixelBuffer) == kCVReturnSuccess else { print("Can not create pixel buffer") return } } // Render to output texture guard let commandBuffer = BBMetalDevice.sharedCommandQueue.makeCommandBuffer(), let encoder = commandBuffer.makeComputeCommandEncoder() else { CVPixelBufferUnlockBaseAddress(videoPixelBuffer, []) print("Can not create compute command buffer or encoder") return } encoder.setComputePipelineState(computePipeline) encoder.setTexture(outputTexture, index: 0) encoder.setTexture(texture.metalTexture, index: 1) encoder.dispatchThreadgroups(threadgroupCount, threadsPerThreadgroup: threadgroupSize) encoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Wait to make sure that output texture contains new data // Check status guard videoInput.isReadyForMoreMediaData, writer.status == .writing else { print("Asset writer or video input is not ready for writing this frame") return } // Copy data from metal texture to pixel buffer guard videoPixelBuffer != nil, CVPixelBufferLockBaseAddress(videoPixelBuffer, []) == kCVReturnSuccess else { print("Pixel buffer can not lock base address") return } guard let baseAddress = CVPixelBufferGetBaseAddress(videoPixelBuffer) else { CVPixelBufferUnlockBaseAddress(videoPixelBuffer, []) print("Can not get pixel buffer base address") return } let bytesPerRow = CVPixelBufferGetBytesPerRow(videoPixelBuffer) let region = MTLRegionMake2D(0, 0, outputTexture.width, outputTexture.height) outputTexture.getBytes(baseAddress, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0) result = videoPixelBufferInput.append(videoPixelBuffer, withPresentationTime: sampleTime) CVPixelBufferUnlockBaseAddress(videoPixelBuffer, []) } } extension BBMetalVideoWriter: BBMetalAudioConsumer { public func newAudioSampleBufferAvailable(_ sampleBuffer: CMSampleBuffer) { lock.wait() let progress = self.progress var result: Bool? defer { lock.signal() if let result = result, let progress = progress { progress(.audio(CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer), result)) } } // Check nil guard let audioInput = self.audioInput, let writer = self.writer else { return } // Check first frame guard videoPixelBuffer != nil else { return } // Check status guard audioInput.isReadyForMoreMediaData, writer.status == .writing else { print("Asset writer or audio input is not ready for writing this frame-\(writer.status.rawValue)---\(audioInput.isReadyForMoreMediaData)") return } result = audioInput.append(sampleBuffer) } }
36.777159
157
0.599106
d5fbe2c4727e5b51f9701182205b6ec2545d4e4f
924
// // PaperOnboardingDataSource.swift // PaperOnboardingDemo // // Created by Abdurahim Jauzee on 05/06/2017. // Copyright © 2017 Alex K. All rights reserved. // import Foundation /** * The PaperOnboardingDataSource protocol is adopted by an object that mediates the application’™s data model for a PaperOnboarding object. The data source information it needs to construct and modify a PaperOnboarding. */ public protocol PaperOnboardingDataSource { /** Asks the data source to return the number of items. - parameter index: An index of item in PaperOnboarding. - returns: The number of items in PaperOnboarding. */ func onboardingItemsCount() -> Int /** Asks the data source for configureation item. - parameter index: An index of item in PaperOnboarding. - returns: configuration info for item */ func onboardingItemAtIndex(_ index: Int) -> OnboardingItemInfo }
26.4
140
0.728355
e9153e9735a84924fc39c969140558cd2969218f
536
// // ARSelectModel.swift // ARSelectableView // // Created by Rohit Makwana on 05/10/20. // Copyright © 2020 Rohit Makwana. All rights reserved. // import UIKit public class ARSelectModel { var title: String var isSelected: Bool var selectionType: ARSelectionType? var width: CGFloat = 0.0 init(title: String, isSelected: Bool = false) { self.title = title self.isSelected = isSelected self.width = UILabel().sizeForLabel(text: title, font: ARSelectableCell.titleFont).width } }
22.333333
96
0.675373
f5e7031d9e929c96de221cbcea9be5ea75a01790
1,383
// // ChatMessage.swift // ChatAppOrigionalFiles // // Created by Ian Kohlert on 2017-07-19. // Copyright © 2017 aestusLabs. All rights reserved. // import Foundation import UIKit class ChatBubble: UIView { var text = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(red: 0.97254902, green: 0.97254902, blue: 0.97254902, alpha: 1.0) self.layer.cornerRadius = 2 } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } } func createChatBubble(text: String, textWidth: CGFloat, textHeight: CGFloat, isUser: Bool) -> ChatBubble{ let bubble = ChatBubble(frame: CGRect(x: 0, y: 0, width: 40 + textWidth + 20, height: textHeight + 20)) if isUser { bubble.text = UILabel(frame: CGRect(x: 10, y: 10, width: textWidth, height: textHeight)) bubble.backgroundColor = appColours.getMainAppColour() bubble.text.textColor = UIColor.white } else { bubble.text = UILabel(frame: CGRect(x: 40, y: 10, width: textWidth, height: textHeight)) } bubble.text.text = text bubble.text.numberOfLines = 0 bubble.text.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium) bubble.text.center.y = bubble.center.y bubble.addSubview(bubble.text) return bubble }
31.431818
107
0.665221
097f53aec72944da4f5ccd01fdb4f159724ad810
1,222
// // CategoryHome.swift // Landmarks // // Created by Retso Huang on 2021/9/12. // import SwiftUI public struct CategoryHome: View { @EnvironmentObject private var modelData: ModelData @State private var showingProfile = false public var body: some View { NavigationView { List { PageView(pages: modelData.features.map(FeatureCard.init)) .aspectRatio(3 / 2, contentMode: .fit) .listRowInsets(EdgeInsets()) ForEach(modelData.categories.keys.sorted(), id: \.self) { key in CategoryRow(categoryName: key, items: modelData.categories[key]!) } .listRowInsets(EdgeInsets()) } .listStyle(InsetListStyle()) .navigationBarTitle("Featured") .toolbar { Button(action: { showingProfile.toggle() }, label: { Image(systemName: "person.crop.circle") .accessibilityLabel("User Profile") }) } .sheet(isPresented: $showingProfile) { ProfileHost() .environmentObject(modelData) } } } } public struct CategoryHome_Previews: PreviewProvider { public static var previews: some View { CategoryHome() .environmentObject(ModelData()) } }
23.5
75
0.630933
ef214fe013f3201bb08f0aa1f4883f0832727860
3,472
// // ConcurrentDictionaryTests.swift // AmazonChimeSDK // // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // @testable import AmazonChimeSDK import XCTest class ConcurrentDictionaryTests: XCTestCase { private var dict: ConcurrentDictionary<String, Int>! override func setUp() { super.setUp() self.dict = ConcurrentDictionary() } func testPutNonNilAndGetShouldWork() { dict["1+1="] = 2 XCTAssertEqual(dict.getShallowDictCopy().count, 1) XCTAssertEqual(dict["1+1="], 2) } func testPutNilAndGetShouldWork() { dict["?+?="] = nil XCTAssertEqual(dict.getShallowDictCopy().count, 0) XCTAssertNil(dict["?+?="]) } func testForEachShouldWork() { dict["1+0="] = 1 dict["10+0="] = 10 dict["100+0="] = 100 var sum: Int = 0 var count: Int = 0 dict.forEach { (_, value) in count += 1 sum += value } XCTAssertEqual(sum, 111) XCTAssertEqual(count, 3) } func testSortedShouldWork() { dict["1+0="] = 1 dict["1+1="] = 2 let sortedAscending = dict.sorted(by: { $0.value > $1.value }) XCTAssertEqual(sortedAscending[0].value, 2) XCTAssertEqual(sortedAscending[1].value, 1) let sortedDecending = dict.sorted(by: { $0.value < $1.value }) XCTAssertEqual(sortedDecending[0].value, 1) XCTAssertEqual(sortedDecending[1].value, 2) } func testGetShallowDictCopyShouldReturnShallowCopy() { dict["1+1="] = 1 var dictCopy = dict.getShallowDictCopy() dictCopy["1+1="] = 2 XCTAssertEqual(dict["1+1="], 1) XCTAssertEqual(dictCopy["1+1="], 2) } func testThreadSafety() { dict["?"] = 0 let backgroundThreadEndedExpectation = XCTestExpectation( description: "The background thread was ended") let mainThreadEndedExpectation = XCTestExpectation( description: "The main thread was ended") DispatchQueue.global(qos: .background).async { self.dict.forEach { _ in sleep(2) self.dict["?"] = 1 } backgroundThreadEndedExpectation.fulfill() } DispatchQueue.main.async { sleep(1) self.dict["?"] = 2 mainThreadEndedExpectation.fulfill() } wait(for: [backgroundThreadEndedExpectation, mainThreadEndedExpectation], timeout: 5) XCTAssertEqual(self.dict["?"], 2) } func testThreadSafetyShouldFailForNormalDict() { var normalDict = ["?": 0] let backgroundThreadEndedExpectation = XCTestExpectation( description: "The background thread was ended") let mainThreadEndedExpectation = XCTestExpectation( description: "The main thread was ended") DispatchQueue.global(qos: .background).async { normalDict.forEach { _ in sleep(2) normalDict["?"] = 1 } backgroundThreadEndedExpectation.fulfill() } DispatchQueue.main.async { sleep(1) normalDict["?"] = 2 mainThreadEndedExpectation.fulfill() } wait(for: [backgroundThreadEndedExpectation, mainThreadEndedExpectation], timeout: 5) XCTAssertEqual(normalDict["?"], 1) } }
29.423729
93
0.586694
d66270bf9106e05f546049c75c539c71136775ae
4,331
// // CarouselContentNode.swift // Clark // // Created by Vladislav Zagorodnyuk on 7/8/17. // Copyright © 2017 Clark. All rights reserved. // import UIKit import NMessenger import AsyncDisplayKit protocol CarouselContentDelegate { func datasourceSelected(items: [CarouselItem]) } open class CarouselContentNode: ContentNode { /// Carousel Items var carouselItems: [CarouselItem] { didSet { /// Reload collectionViewNode.reloadData() } } /// Delegate var delegate: CarouselContentDelegate? /// Collection View node lazy var collectionViewNode: ASCollectionNode = { /// Layout let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 16 layout.minimumInteritemSpacing = 16 layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) /// Collection node let collectionNode = ASCollectionNode(frame: .zero, collectionViewLayout: layout) /// Node setup collectionNode.view.showsHorizontalScrollIndicator = false return collectionNode }() /// Inset for the node open var insets = UIEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) { didSet { setNeedsLayout() } } /// Initializer for the cell /// /// - Parameters: /// - carouselItem: carouselItem model /// - bubbleConfiguration: bubble setup init(carouselItems: [CarouselItem], bubbleConfiguration: BubbleConfigurationProtocol? = nil) { self.carouselItems = carouselItems super.init(bubbleConfiguration: bubbleConfiguration) self.setupCarouselNode() } /// Initializer for the cell /// /// - Parameters: /// - carouselItem: carouselItem model /// - currentViewController: controller for presentation /// - bubbleConfiguration: bubble setup init(carouselItems: [CarouselItem], currentViewController: UIViewController, bubbleConfiguration: BubbleConfigurationProtocol? = nil) { self.carouselItems = carouselItems super.init(bubbleConfiguration: bubbleConfiguration) self.currentViewController = currentViewController self.setupCarouselNode() } // MARK: Initializer helper /// Create carousel /// /// - Parameter carouselItem: carousel model fileprivate func setupCarouselNode() { /// Clear background bubble layer.backgroundColor = UIColor.clear.cgColor addSubnode(collectionViewNode) /// Collection node setup collectionViewNode.delegate = self collectionViewNode.dataSource = self } // MARK: - Collection layout open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let carouselMessageSize = ASAbsoluteLayoutSpec() carouselMessageSize.style.preferredSize = CGSize(width: constrainedSize.max.width, height: 160) carouselMessageSize.sizing = .sizeToFit carouselMessageSize.children = [collectionViewNode] return ASInsetLayoutSpec(insets: insets, child: carouselMessageSize) } } // MARK: - ASCollectionDataSource extension CarouselContentNode: ASCollectionDataSource { public func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode { let carouselItem = carouselItems[indexPath.row] return CarouselNode(with: carouselItem, count: carouselItems.count) } public func numberOfSections(in collectionNode: ASCollectionNode) -> Int { return 1 } public func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int { return carouselItems.count } } // MARK: - ASCollectionDelegate extension CarouselContentNode: ASCollectionDelegate { public func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) { delegate?.datasourceSelected(items: carouselItems) Analytics.trackEventWithID(.s1_6, eventParams: ["index": indexPath.row]) } }
31.158273
139
0.661972
87d943dc565ee7fe749919665480070e52a73e93
1,264
// // DNVFontPickerUITests.swift // DNVFontPickerUITests // // Created by Alexey Demin on 2017-02-28. // Copyright © 2017 Alexey Demin. All rights reserved. // import XCTest class DNVFontPickerUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.162162
182
0.667722
6298061068ad6a402d589f1186795b3d2e0e64b8
1,154
// // LayerLayout.swift // SwiftStreamgraph // // Created by Sean Zehnder on 3/3/17. // Based on Lee Byron and Martin Wattenberg's Processing Streamgraph code // Available here: https://github.com/leebyron/streamgraph_generato // AND obj_streamgraph-generator // Available here: https://github.com/dominikus/obj_streamgraph-generator // import Foundation class LayerLayout { var name:String { // must override return "" } func layout(layers:[Layer]) { // must override } /** * We define our stacked graphs by layers atop a baseline. * This method does the work of assigning the positions of each layer in an * ordered array of layers based on an initial baseline. */ func stackOnBaseline(layers:[Layer], baseline:[Double]) { var baseline = baseline for i in 0..<layers.count { let l = layers[i] l.yBottom = baseline for j in 0..<baseline.count { let nuvalue = baseline[i] - l.size[j] baseline[i] = nuvalue } l.yTop = baseline } } }
25.644444
79
0.594454
9cec5d6916ee01437760e8f92e40e9f048c166ea
12,703
// // AnimationAdding.swift // CoreAnimation // // Created by Franklyn on 20/02/2019. // Copyright © 2019 Franklyn. All rights reserved. // import UIKit // MARK: - Convenience functions to add animations to CALayers public extension CALayer { /// Adds a CAPropertyAnimation (CABasicAnimation, CAKeyframeAnimation, CASpringAnimation) to the layer /// /// - Parameters: /// - animation: a CAPropertyAnimation object /// - key: key for the animation /// - removeExistingAnimations: removes any existing layer animations if true /// - animationDidFinish: invoked when the animation completes public func addAnimation(_ animation: CAPropertyAnimation, forKey key: String? = nil, removeExistingAnimations: Bool = false, animationDidFinish: AnimationDidFinishAction? = nil) { self.removeExistingAnimationsIfNecessary(removeExistingAnimations) CALayer.addAnimationDidFinishAction(animationDidFinish, to: animation) self.add(animation, forKey: key ?? self.defaultKey) } /// Adds a CATransition to the layer /// /// - Parameters: /// - transition: a CATransition object /// - key: key for the animation /// - removeExistingAnimations: removes any existing layer animations if true /// - animationDidFinish: invoked when the animation completes public func addTransition(_ transition: CATransition, forKey key: String? = nil, removeExistingAnimations: Bool = false, animationDidFinish: AnimationDidFinishAction? = nil) { self.removeExistingAnimationsIfNecessary(removeExistingAnimations) CALayer.addAnimationDidFinishAction(animationDidFinish, to: transition) self.add(transition, forKey: key ?? self.defaultKey) } } extension CALayer { private var defaultKey: String { return UUID().uuidString } func addAnimation(_ animationDescriptor: Descriptor.Root & AnimationDescribing, removeExistingAnimations: Bool, animationDidFinish: AnimationDidFinishAction?) { self.removeExistingAnimationsIfNecessary(removeExistingAnimations) let animation: CAAnimation = animationDescriptor.animation CALayer.addAnimationDidBeginAction(animationDescriptor.animationDidBegin, to: animation) CALayer.addAnimationDidFinishAction(animationDidFinish, to: animation) CALayer.addAnimationDidFinishAction(animationDescriptor.animationDidFinish, to: animation) animationDescriptor.animationWillBegin?() self.add(animation, forKey: animationDescriptor.animationKey ?? self.defaultKey) } func addAnimationsGroup(_ animationDescriptor: Descriptor.Group, removeExistingAnimations: Bool, animationDidFinish: AnimationDidFinishAction?) { if let animationDescriptor = animationDescriptor as? Descriptor.Group.Concurrent { self.addConcurrentAnimations(animationDescriptor, removeExistingAnimations: removeExistingAnimations, animationDidFinish: animationDidFinish) } else { self.addAnimationSequence([animationDescriptor], removeExistingAnimations: removeExistingAnimations, animationDidFinish: animationDidFinish) } } func addAnimationSequence(_ animationDescriptors: [Descriptor.Root], removeExistingAnimations: Bool, animationDidFinish: AnimationDidFinishAction?) { self.removeExistingAnimationsIfNecessary(removeExistingAnimations) var descriptors = animationDescriptors // if any of the descriptors are for actions, we want to carry them out straight away, // in the animationDidFinish closure of the previous animation in the sequence; // we'd also remove their descriptors when we do this so they're not repeated while let nextActionDescriptor = descriptors.first as? Descriptor.Action { nextActionDescriptor.action() descriptors.removeFirst() } // the first descriptor for an actual animation (or group) guard let descriptor = descriptors.first else { // we've run out of items on the group animationDidFinish?(nil, true) return } descriptors.removeFirst() // we don't want it in the list any more if let concurrentAnimationsDescriptor = descriptor as? Descriptor.Group.Concurrent { self.addConcurrentAnimations(concurrentAnimationsDescriptor, removeExistingAnimations: removeExistingAnimations, animationDidFinish: { [weak self] _, _ in guard let self = self else { return } self.addAnimationSequence(descriptors, removeExistingAnimations: removeExistingAnimations, animationDidFinish: animationDidFinish) }) } else if let sequentialAnimationsDescriptor = descriptor as? Descriptor.Group.Sequential { descriptor.animationWillBegin?() // the sequence always begins now, with no option to change the beginTime let allDescriptors = sequentialAnimationsDescriptor.descriptors + descriptors self.addAnimationSequence(allDescriptors, removeExistingAnimations: removeExistingAnimations, animationDidFinish: { animation, finished in animationDidFinish?(animation, finished) descriptor.animationDidFinish?(animation, finished) }) } else if let animationDescriptor = descriptor as? AnimationDescribing { // in this case it's a normal animation let animation = animationDescriptor.animation CALayer.addAnimationDidBeginAction(animationDescriptor.animationDidBegin, to: animation) animation.addAnimationDidFinishAction { [weak self] animation, finished in guard let self = self else { return } self.addAnimationSequence(descriptors, removeExistingAnimations: removeExistingAnimations, animationDidFinish: animationDidFinish) descriptor.animationDidFinish?(animation, finished) } descriptor.animationWillBegin?() self.add(animation, forKey: animationDescriptor.animationKey) } } func addConcurrentAnimations(_ animationDescriptor: Descriptor.Group.Concurrent, removeExistingAnimations: Bool, animationDidFinish: AnimationDidFinishAction?) { self.removeExistingAnimationsIfNecessary(removeExistingAnimations) animationDescriptor.animationWillBegin?() let descriptors = animationDescriptor.descriptors let groupDuration: TimeInterval? = animationDescriptor.duration var animationFinishedActionAdded = false var actionCount = 0 // as we're re-creating CAAnimationGroup functionality, without creating a CAAnimationGroup, we need to handle any animationFinished actions // to do this we add it to the longest (including beginTime) of the group's animations, so it's only run once descriptors.forEach { descriptor in if let actionDescriptor = descriptor as? Descriptor.Action { actionDescriptor.action() actionCount += 1 return } var animationFinishedAction: AnimationDidFinishAction? = nil var animationDescriptorFinishedAction: AnimationDidFinishAction? = nil if let concurrentAnimationsDescriptor = descriptor as? Descriptor.Group.Concurrent { if animationFinishedActionAdded == false, let thisDuration = concurrentAnimationsDescriptor.duration, let groupDuration = groupDuration, thisDuration >= groupDuration { animationFinishedActionAdded = true animationFinishedAction = animationDidFinish // this is the action passed into this function animationDescriptorFinishedAction = animationDescriptor.animationDidFinish // this is the action added when the descriptor was created } self.addConcurrentAnimations(concurrentAnimationsDescriptor, removeExistingAnimations: removeExistingAnimations, animationDidFinish: { [animationFinishedAction, animationDescriptorFinishedAction] animation, finished in // these next two are invoked only if they haven't already been used animationFinishedAction?(animation, finished) animationDescriptorFinishedAction?(animation, finished) }) } else if let sequentialAnimationsDescriptor = descriptor as? Descriptor.Group.Sequential { if animationFinishedActionAdded == false, let thisDuration = sequentialAnimationsDescriptor.duration, let groupDuration = groupDuration, thisDuration >= groupDuration { animationFinishedActionAdded = true animationFinishedAction = animationDidFinish // this is the action passed into this function animationDescriptorFinishedAction = animationDescriptor.animationDidFinish // this is the action added when the descriptor was created } self.addAnimationSequence(sequentialAnimationsDescriptor.descriptors, removeExistingAnimations: removeExistingAnimations, animationDidFinish: { [animationFinishedAction, animationDescriptorFinishedAction] animation, finished in descriptor.animationDidFinish?(animation, finished) // each descriptor in the group can have its own animationFinished action // these next two are invoked only if they haven't already been used animationFinishedAction?(animation, finished) animationDescriptorFinishedAction?(animation, finished) }) } else if let singleAnimationDescriptor = descriptor as? AnimationDescribing { let animation = singleAnimationDescriptor.animation CALayer.addAnimationDidBeginAction(singleAnimationDescriptor.animationDidBegin, to: animation) CALayer.addAnimationDidFinishAction(descriptor.animationDidFinish, to: animation) // if it's the longest animation in the group, we add the group's animationFinished action to it (only if they haven't already been used) if animationFinishedActionAdded == false, let groupDuration = groupDuration, animation.duration + animation.beginTime >= groupDuration { animationFinishedActionAdded = true CALayer.addAnimationDidFinishAction(animationDidFinish, to: animation) CALayer.addAnimationDidFinishAction(animationDescriptor.animationDidFinish, to: animation) } descriptor.animationWillBegin?() self.add(animation, forKey: singleAnimationDescriptor.animationKey) } } if actionCount == descriptors.count { // it was only actions & no animations, so invoke the animationFinished closures animationDidFinish?(nil, true) animationDescriptor.animationDidFinish?(nil, true) } } private func removeExistingAnimationsIfNecessary(_ removeExistingAnimations: Bool) { if removeExistingAnimations { self.removeAllAnimations() } } private static func addAnimationDidBeginAction(_ action: AnimationBeginAction?, to animation: CAAnimation) { if let action = action { animation.addAnimationDidBeginAction(action) } } private static func addAnimationDidFinishAction(_ action: AnimationDidFinishAction?, to animation: CAAnimation) { if let action = action { animation.addAnimationDidFinishAction(action) } } }
47.399254
184
0.650712
790e1fa3413cfdb4acfaf4f75ab56c1d29808e89
6,479
// RUN: %{swiftc} %s -o %T/SkippingTestCase // RUN: %T/SkippingTestCase > %t || true // RUN: %{xctest_checker} %t %s #if os(macOS) import SwiftXCTest #else import XCTest #endif // CHECK: Test Suite 'All tests' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: Test Suite '.*\.xctest' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: Test Suite 'SkippingTestCase' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ class SkippingTestCase: XCTestCase { static var allTests = { return [ ("testSkip", testSkip), ("testSkip_withMessage", testSkip_withMessage), ("testSkip_viaSetUpWithError", testSkip_viaSetUpWithError), ("testSkipIf_pass", testSkipIf_pass), ("testSkipUnless_pass", testSkipUnless_pass), ("testSkipIf_fail", testSkipIf_fail), ("testSkipUnless_fail", testSkipUnless_fail), ("testSkipIf_fail_withMessage", testSkipIf_fail_withMessage), ("testSkipUnless_fail_withMessage", testSkipUnless_fail_withMessage), ("testSkipIf_fail_errorThrown", testSkipIf_fail_errorThrown), ] }() override func setUpWithError() throws { if name == "SkippingTestCase.testSkip_viaSetUpWithError" { throw XCTSkip("via setUpWithError") } } // CHECK: Test Case 'SkippingTestCase.testSkip' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkip : Test skipped // CHECK: Test Case 'SkippingTestCase.testSkip' skipped \(\d+\.\d+ seconds\) func testSkip() throws { throw XCTSkip() } // CHECK: Test Case 'SkippingTestCase.testSkip_withMessage' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkip_withMessage : Test skipped - some reason // CHECK: Test Case 'SkippingTestCase.testSkip_withMessage' skipped \(\d+\.\d+ seconds\) func testSkip_withMessage() throws { throw XCTSkip("some reason") } // CHECK: Test Case 'SkippingTestCase.testSkip_viaSetUpWithError' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE-19]]: SkippingTestCase.testSkip_viaSetUpWithError : Test skipped - via setUpWithError // CHECK: Test Case 'SkippingTestCase.testSkip_viaSetUpWithError' skipped \(\d+\.\d+ seconds\) func testSkip_viaSetUpWithError() { XCTFail("should not happen due to XCTSkip in setUpWithError()") } // CHECK: Test Case 'SkippingTestCase.testSkipIf_pass' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: Test Case 'SkippingTestCase.testSkipIf_pass' passed \(\d+\.\d+ seconds\) func testSkipIf_pass() throws { let expectation = self.expectation(description: "foo") try XCTSkipIf(false) expectation.fulfill() wait(for: [expectation], timeout: 0) } // CHECK: Test Case 'SkippingTestCase.testSkipUnless_pass' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: Test Case 'SkippingTestCase.testSkipUnless_pass' passed \(\d+\.\d+ seconds\) func testSkipUnless_pass() throws { let expectation = self.expectation(description: "foo") try XCTSkipUnless(true) expectation.fulfill() wait(for: [expectation], timeout: 0) } // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkipIf_fail : Test skipped: required true value but got false // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail' skipped \(\d+\.\d+ seconds\) func testSkipIf_fail() throws { try XCTSkipIf(true) } // CHECK: Test Case 'SkippingTestCase.testSkipUnless_fail' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkipUnless_fail : Test skipped: required false value but got true // CHECK: Test Case 'SkippingTestCase.testSkipUnless_fail' skipped \(\d+\.\d+ seconds\) func testSkipUnless_fail() throws { try XCTSkipUnless(false) } // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail_withMessage' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkipIf_fail_withMessage : Test skipped: required true value but got false - some reason // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail_withMessage' skipped \(\d+\.\d+ seconds\) func testSkipIf_fail_withMessage() throws { try XCTSkipIf(true, "some reason") } // CHECK: Test Case 'SkippingTestCase.testSkipUnless_fail_withMessage' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+3]]: SkippingTestCase.testSkipUnless_fail_withMessage : Test skipped: required false value but got true - some reason // CHECK: Test Case 'SkippingTestCase.testSkipUnless_fail_withMessage' skipped \(\d+\.\d+ seconds\) func testSkipUnless_fail_withMessage() throws { try XCTSkipUnless(false, "some reason") } // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail_errorThrown' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: .*[/\\]SkippingTestCase[/\\]main.swift:[[@LINE+7]]: SkippingTestCase.testSkipIf_fail_errorThrown : Test skipped: threw error "ContrivedError\(message: "foo"\)" - some reason // CHECK: Test Case 'SkippingTestCase.testSkipIf_fail_errorThrown' skipped \(\d+\.\d+ seconds\) func testSkipIf_fail_errorThrown() throws { func someCondition() throws -> Bool { throw ContrivedError(message: "foo") } try XCTSkipIf(someCondition(), "some reason") } } // CHECK: Test Suite 'SkippingTestCase' passed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: \t Executed 10 tests, with 8 tests skipped and 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds XCTMain([testCase(SkippingTestCase.allTests)]) // CHECK: Test Suite '.*\.xctest' passed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: \t Executed 10 tests, with 8 tests skipped and 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds // CHECK: Test Suite 'All tests' passed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+ // CHECK: \t Executed 10 tests, with 8 tests skipped and 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds private struct ContrivedError: Error { let message: String }
49.083333
187
0.649483
d936b0ac4784d76b4ce4aa7e619d7cf8fdd01a4c
846
import Combine import SwiftUI class ObservablePublishedModel: ObservableObject { @Published var searchText = "" @Published var updateCount = 0 var cancellable: Cancellable? init() { cancellable = $searchText .dropFirst() .receive(on: DispatchQueue.main) .sink() { [weak self] _ in self?.updateCount += 1 } } } struct ObservablePublishedTest: View { @ObservedObject var viewModel = ObservablePublishedModel() var body: some View { List { Text("Update count: \(viewModel.updateCount)") .accessibility(identifier: "countLabel") } .navigationBarSearch($viewModel.searchText) } } struct ObservablePublishedTest_Previews: PreviewProvider { static var previews: some View { ObservablePublishedTest() } }
24.882353
63
0.640662
e90a4802e0abbfa4adbb18cf117a3149c7dfdfd4
165
// // AproachViewModel.swift // Owner // // Created by Paolo Prodossimo Lopes on 12/01/22. // import Foundation final class AproachViewModel { }
11
50
0.636364
c19581740e0580fc8b34a2fcdbe895fa04c123d4
13,440
// Alamofire.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol AlamofireURLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: AlamofireURLStringConvertible { public var URLString: String { return self } } extension NSURL: AlamofireURLStringConvertible { public var URLString: String { return absoluteString } } extension NSURLComponents: AlamofireURLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: AlamofireURLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } struct Alamofire { // MARK: - Convenience static func URLRequest( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, headers: [String:String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ static func request( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, parameters: [String:AnyObject]? = nil, encoding: HTTPParameterEncoding = .URL, headers: [String:String]? = nil) -> HTTPRequest { return AlamofireManager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ static func request(URLRequest: URLRequestConvertible) -> HTTPRequest { return AlamofireManager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ static func upload( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, headers: [String:String]? = nil, file: NSURL) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ static func upload(URLRequest: URLRequestConvertible, file: NSURL) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ static func upload( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, headers: [String:String]? = nil, data: NSData) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ static func upload(URLRequest: URLRequestConvertible, data: NSData) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ static func upload( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, headers: [String:String]? = nil, stream: NSInputStream) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ static func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> HTTPRequest { return AlamofireManager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ static func upload( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, headers: [String:String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = AlamofireManager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (AlamofireManager.MultipartFormDataEncodingResult -> Void)?) { return AlamofireManager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ static func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = AlamofireManager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (AlamofireManager.MultipartFormDataEncodingResult -> Void)?) { return AlamofireManager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ static func download( method: HTTPMethod, _ URLString: AlamofireURLStringConvertible, parameters: [String:AnyObject]? = nil, encoding: HTTPParameterEncoding = .URL, headers: [String:String]? = nil, destination: HTTPRequest.DownloadFileDestination) -> HTTPRequest { return AlamofireManager.sharedInstance.download( method, URLString, parameters: parameters, encoding: encoding, headers: headers, destination: destination ) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ static func download(URLRequest: URLRequestConvertible, destination: HTTPRequest.DownloadFileDestination) -> HTTPRequest { return AlamofireManager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ static func download(resumeData data: NSData, destination: HTTPRequest.DownloadFileDestination) -> HTTPRequest { return AlamofireManager.sharedInstance.download(data, destination: destination) } }
36.721311
126
0.677753
9c38069eca38a29e86436a4087acc4537dc8c498
6,345
/* Copyright 2015 HiHex 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 XCTest import BinarySpec class BinarySpecParserTests: XCTestCase { func testSingleton() { XCTAssertEqual(BinarySpec(parse: "<b"), BinarySpec.Integer(.Byte)) XCTAssertEqual(BinarySpec(parse: "<h"), BinarySpec.Integer(.UInt16LE)) XCTAssertEqual(BinarySpec(parse: ">h"), BinarySpec.Integer(.UInt16BE)) XCTAssertEqual(BinarySpec(parse: "<t"), BinarySpec.Integer(.UInt24LE)) XCTAssertEqual(BinarySpec(parse: ">t"), BinarySpec.Integer(.UInt24BE)) XCTAssertEqual(BinarySpec(parse: "<i"), BinarySpec.Integer(.UInt32LE)) XCTAssertEqual(BinarySpec(parse: ">i"), BinarySpec.Integer(.UInt32BE)) XCTAssertEqual(BinarySpec(parse: "<q"), BinarySpec.Integer(.UInt64LE)) XCTAssertEqual(BinarySpec(parse: ">q"), BinarySpec.Integer(.UInt64BE)) } func testRepeat() { XCTAssertEqual(BinarySpec(parse: ">3Q<2Q"), BinarySpec.Seq([ .Integer(.UInt64BE), .Integer(.UInt64BE), .Integer(.UInt64BE), .Integer(.UInt64LE), .Integer(.UInt64LE), ])) } func testSkip() { XCTAssertEqual(BinarySpec(parse: "256x"), BinarySpec.Skip(256)) XCTAssertEqual(BinarySpec(parse: "0x"), BinarySpec.Skip(0)) XCTAssertEqual(BinarySpec(parse: "0x256x"), BinarySpec.Skip(0x256)) } func testHexDigit() { XCTAssertEqual(BinarySpec(parse: "2bx"), BinarySpec.Seq([.Integer(.Byte), .Integer(.Byte), .Skip(1)])) XCTAssertEqual(BinarySpec(parse: "0x2bx"), BinarySpec.Skip(0x2b)) XCTAssertEqual(BinarySpec(parse: "0x2 bx"), BinarySpec.Seq([.Integer(.Byte), .Integer(.Byte), .Skip(1)])) XCTAssertEqual(BinarySpec(parse: "00x2bx"), BinarySpec.Seq([.Skip(0), .Integer(.Byte), .Integer(.Byte), .Skip(1)])) XCTAssertEqual(BinarySpec(parse: "0 0x2bx"), BinarySpec.Skip(0x2b)) } func testVariable() { XCTAssertEqual(BinarySpec(parse: "%Is"), BinarySpec.Seq([ .Variable(.UInt32LE, "0", offset: 0), .Bytes("0") ])) XCTAssertEqual(BinarySpec(parse: "%I%Qss"), BinarySpec.Seq([ .Variable(.UInt32LE, "0", offset: 0), .Variable(.UInt64LE, "1", offset: 0), .Bytes("0"), .Bytes("1") ])) XCTAssertEqual(BinarySpec(parse: "%I%Qss", variablePrefix: "hello_"), BinarySpec.Seq([ .Variable(.UInt32LE, "hello_0", offset: 0), .Variable(.UInt64LE, "hello_1", offset: 0), .Bytes("hello_0"), .Bytes("hello_1") ])) } func testUntil() { XCTAssertEqual(BinarySpec(parse: "%T(I)"), BinarySpec.Seq([ .Variable(.UInt24LE, "0", offset: 0), .Until("0", .Integer(.UInt32LE)) ])) XCTAssertEqual(BinarySpec(parse: "%BB(BI)"), BinarySpec.Seq([ .Variable(.Byte, "0", offset: 0), .Integer(.Byte), .Until("0", .Seq([ .Integer(.Byte), .Integer(.UInt32LE), ])) ])) } func testSwitch() { XCTAssertEqual(BinarySpec(parse: "%I{1=T,2=B,0xa=QQ,*=H}"), BinarySpec.Seq([ .Variable(.UInt32LE, "0", offset: 0), .Switch(selector: "0", cases: [ 1: .Integer(.UInt24LE), 2: .Integer(.Byte), 0xa: .Seq([.Integer(.UInt64LE), .Integer(.UInt64LE)]) ], default: .Integer(.UInt16LE)) ])) } func testSampleADB() { XCTAssertEqual(BinarySpec(parse: "<3I%I2Is"), BinarySpec.Seq([ .Integer(.UInt32LE), .Integer(.UInt32LE), .Integer(.UInt32LE), .Variable(.UInt32LE, "0", offset: 0), .Integer(.UInt32LE), .Integer(.UInt32LE), .Bytes("0") ])) } func testSampleHTTP2() { XCTAssertEqual(BinarySpec(parse: ">%TBBIs"), BinarySpec.Seq([ .Variable(.UInt24BE, "0", offset: 0), .Integer(.Byte), .Integer(.Byte), .Integer(.UInt32BE), .Bytes("0"), ])) } func testVariableOffset() { XCTAssertEqual(BinarySpec(parse: ">%+1I%-0x13I"), BinarySpec.Seq([ .Variable(.UInt32BE, "0", offset: 1), .Variable(.UInt32BE, "1", offset: -0x13), ])) } func testVariableOverride() { XCTAssertEqual(BinarySpec(parse: ">%I%H1$s0$s", variablePrefix: "~"), BinarySpec.Seq([ .Variable(.UInt32BE, "~0", offset: 0), .Variable(.UInt16BE, "~1", offset: 0), .Bytes("~1"), .Bytes("~0"), ])) } func testUnlimitedLength() { XCTAssertEqual(BinarySpec(parse: "*s"), BinarySpec.Bytes(nil)) XCTAssertEqual(BinarySpec(parse: ">*(I)"), BinarySpec.Until(nil, .Integer(.UInt32BE))) XCTAssertEqual(BinarySpec(parse: ">%Is*s%Is"), BinarySpec.Seq([ .Variable(.UInt32BE, "0", offset: 0), .Bytes("0"), .Bytes(nil), .Variable(.UInt32BE, "1", offset: 0), .Bytes("1"), ])) } } class BinaryDataConvertibleTests: XCTestCase { func testNumbers() { XCTAssertEqual(«5», BinaryData.Integer(5)) XCTAssertEqual(«(-5)», BinaryData.Integer(UIntMax(bitPattern: -5))) } func testString() { XCTAssertEqual(«"Héĺĺó"», BinaryData.Bytes(createData([0x48, 0xc3, 0xa9, 0xc4, 0xba, 0xc4, 0xba, 0xc3, 0xb3]))) } func testSequence() { XCTAssertEqual(«[1, 2, 4]», BinaryData.Seq([.Integer(1), .Integer(2), .Integer(4)])) } func testComposite() { XCTAssertEqual(«[«1», «[«3», «""»]»]», BinaryData.Seq([.Integer(1), .Seq([.Integer(3), .Bytes(NSData())])])) } }
36.676301
123
0.568794
897598cd2a0f155e0af8cb2e52ef7ed1e93d9238
1,242
// // ItemCell.swift // InstaEat // // Created by Kunwar Vats on 14/03/22. // import UIKit class ItemCell: UITableViewCell { @IBOutlet weak var favImageView: UIImageView! @IBOutlet weak var quantityLabel: UILabel! @IBOutlet weak var quantityUpdateView: UIView! @IBOutlet weak var increaseCountButton: UIButton! @IBOutlet weak var decreaseCountButton: UIButton! @IBOutlet weak var favButton: UIButton! @IBOutlet weak var itemImageView: UIImageView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var borderView: UIView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descripLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code addButton.layer.cornerRadius = 5 itemImageView.layer.cornerRadius = 5 borderView.layer.cornerRadius = 10 borderView.layer.borderColor = UIColor.lightGray.cgColor borderView.layer.borderWidth = 0.5 quantityUpdateView.isHidden = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
28.883721
65
0.690821
2030425088a4161d2b24000c4b79e3986d336ff1
10,578
// // Container.swift // Swinject // // Created by Yoichi Tagaya on 7/23/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Foundation /// The `Container` class represents a dependency injection container, which stores registrations of services /// and retrieves registered services with dependencies injected. /// /// **Example to register:** /// /// let container = Container() /// container.register(A.self) { _ in B() } /// container.register(X.self) { r in Y(a: r.resolve(A.self)!) } /// /// **Example to retrieve:** /// /// let x = container.resolve(X.self)! /// /// where `A` and `X` are protocols, `B` is a type conforming `A`, and `Y` is a type conforming `X` /// and depending on `A`. public final class Container { fileprivate var services = [ServiceKey: ServiceEntryProtocol]() fileprivate let parent: Container? // Used by HierarchyObjectScope fileprivate var resolutionDepth = 0 fileprivate let debugHelper: DebugHelper internal let lock: SpinLock // Used by SynchronizedResolver. internal init(parent: Container? = nil, debugHelper: DebugHelper) { self.parent = parent self.debugHelper = debugHelper self.lock = parent.map { $0.lock } ?? SpinLock() } /// Instantiates a `Container` with its parent `Container`. The parent is optional. /// /// - Parameter parent: The optional parent `Container`. public convenience init(parent: Container? = nil) { self.init(parent: parent, debugHelper: LoggingDebugHelper()) } /// Instantiates a `Container` with its parent `Container` and a closure registering services. /// The parent is optional. /// /// - Parameters: /// - parent: The optional parent `Container`. /// - registeringClosure: The closure registering services to the new container instance. /// - Remark: Compile time may be long if you pass a long closure to this initializer. /// Use `init()` or `init(parent:)` instead. public convenience init(parent: Container? = nil, registeringClosure: (Container) -> Void) { self.init(parent: parent) registeringClosure(self) } /// Removes all registrations in the container. public func removeAll() { services.removeAll() } /// Discards instances for services registered in the given `ObjectsScopeType`. /// /// **Example usage:** /// container.resetObjectScope(ObjectScope.container) /// /// - Parameters: /// - objectScope: All instances registered in given `ObjectsScopeType` will be discarded. public func resetObjectScope(_ objectScope: ObjectScopeProtocol) { services.values .filter { $0.objectScope === objectScope } .forEach { $0.storage.instance = nil } parent?.resetObjectScope(objectScope) } /// Discards instances for services registered in the given `ObjectsScope`. It performs the same operation /// as `resetObjectScope(_:ObjectScopeProtocol)`, but provides more convenient usage syntax. /// /// **Example usage:** /// container.resetObjectScope(.container) /// /// - Parameters: /// - objectScope: All instances registered in given `ObjectsScope` will be discarded. public func resetObjectScope(_ objectScope: ObjectScope) { resetObjectScope(objectScope as ObjectScopeProtocol) } /// Adds a registration for the specified service with the factory closure to specify how the service is /// resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differentiate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the `Container` needs to instantiate the instance. /// It takes a `Resolver` to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered `ServiceEntry` to configure more settings with method chaining. @discardableResult public func register<Service>( _ serviceType: Service.Type, name: String? = nil, factory: @escaping (Resolver) -> Service ) -> ServiceEntry<Service> { return _register(serviceType, factory: factory, name: name) } /// This method is designed for the use to extend Swinject functionality. /// Do NOT use this method unless you intend to write an extension or plugin to Swinject framework. /// /// - Parameters: /// - serviceType: The service type to register. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the `Container` needs to instantiate the instance. /// It takes a `Resolver` to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// - name: A registration name. /// - option: A service key option for an extension/plugin. /// /// - Returns: A registered `ServiceEntry` to configure more settings with method chaining. @discardableResult // swiftlint:disable:next identifier_name public func _register<Service, Factory>( _ serviceType: Service.Type, factory: Factory, name: String? = nil, option: ServiceKeyOption? = nil ) -> ServiceEntry<Service> { let key = ServiceKey(factoryType: type(of: factory), name: name, option: option) let entry = ServiceEntry(serviceType: serviceType, factory: factory) services[key] = entry return entry } /// Returns a synchronized view of the container for thread safety. /// The returned container is `Resolver` type. Call this method after you finish all service registrations /// to the original container. /// /// - Returns: A synchronized container as `Resolver`. public func synchronize() -> Resolver { return SynchronizedResolver(container: self) } } // MARK: - _Resolver extension Container: _Resolver { // swiftlint:disable:next identifier_name public func _resolve<Service, Factory>( name: String?, option: ServiceKeyOption? = nil, invoker: (Factory) -> Service ) -> Service? { incrementResolutionDepth() defer { decrementResolutionDepth() } var resolvedInstance: Service? let key = ServiceKey(factoryType: Factory.self, name: name, option: option) if let entry = getEntry(key) as ServiceEntry<Service>? { resolvedInstance = resolve(entry: entry, key: key, invoker: invoker) } if resolvedInstance == nil { debugHelper.resolutionFailed( serviceType: Service.self, key: key, availableRegistrations: getRegistrations() ) } return resolvedInstance } private func getRegistrations() -> [ServiceKey: ServiceEntryProtocol] { var registrations = parent?.getRegistrations() ?? [:] services.forEach { key, value in registrations[key] = value } return registrations } private var maxResolutionDepth: Int { return 200 } private func incrementResolutionDepth() { guard resolutionDepth < maxResolutionDepth else { fatalError("Infinite recursive call for circular dependency has been detected. " + "To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.") } resolutionDepth += 1 } private func decrementResolutionDepth() { assert(resolutionDepth > 0, "The depth cannot be negative.") resolutionDepth -= 1 if resolutionDepth == 0 { resetObjectScope(.graph) } } } // MARK: - Resolver extension Container: Resolver { /// Retrieves the instance with the specified service type. /// /// - Parameter serviceType: The service type to resolve. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type /// is found in the `Container`. public func resolve<Service>(_ serviceType: Service.Type) -> Service? { return resolve(serviceType, name: nil) } /// Retrieves the instance with the specified service type and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type and name /// is found in the `Container`. public func resolve<Service>(_ serviceType: Service.Type, name: String?) -> Service? { typealias FactoryType = (Resolver) -> Service return _resolve(name: name) { (factory: FactoryType) in factory(self) } } fileprivate func getEntry<Service>(_ key: ServiceKey) -> ServiceEntry<Service>? { if let entry = services[key] as? ServiceEntry<Service> { return entry } else { return parent?.getEntry(key) } } fileprivate func resolve<Service, Factory>( entry: ServiceEntry<Service>, key: ServiceKey, invoker: (Factory) -> Service ) -> Service { if let persistedInstance = entry.storage.instance as? Service { return persistedInstance } let resolvedInstance = invoker(entry.factory as! Factory) if let persistedInstance = entry.storage.instance as? Service { // An instance for the key might be added by the factory invocation. return persistedInstance } entry.storage.instance = resolvedInstance as Any if let completed = entry.initCompleted as? (Resolver, Service) -> Void { completed(self, resolvedInstance) } return resolvedInstance } } // MARK: CustomStringConvertible extension Container: CustomStringConvertible { public var description: String { return "[" + services.map { "\n { \($1.describeWithKey($0)) }" }.sorted().joined(separator: ",") + "\n]" } }
39.32342
116
0.63859
e0ee79cda4dc735748e93dfaea24aa7e9d7c57ee
430
// // SelectImageCollectionViewCell.swift // instagator-prototype // // Created by Amanda McNary on 11/19/15. // Copyright © 2015 ThePenguins. All rights reserved. // import Foundation import UIKit class SelectImageCollectionViewCell: UICollectionViewCell { static let reuseIdentifier = "SelectImageCollectionViewCell" // TODO: set up interface outlets @IBOutlet weak var imageView: UIImageView! }
22.631579
64
0.737209
2365b657e8147cf64b37621b3bd8a9e313257ffb
436
import simd public struct Transform { public var position: float3 = [0, 0, 0] public var rotation: float3 = [0, 0, 0] public var scale: float3 = [1, 1, 1] public var matrix: float4x4 { let translateMatrix = float4x4(translation: position) let rotateMatrix = float4x4(rotation: rotation) let scaleMatrix = float4x4(scaling: scale) return translateMatrix * rotateMatrix * scaleMatrix } public init() {} }
25.647059
57
0.690367
64016cff0088c16e4857782d12619044936f4366
850
// // TestAPIClient.swift // DemoTests // // Created by Yosuke Ishikawa on 2019/01/14. // Copyright © 2019 Yosuke Ishikawa. All rights reserved. // import Foundation import RxSwift @testable import Demo final class TestAPIClient: APIClient { private var stubs = [] as [(request: Any, response: Any)] func stub<Request: APIRequest>(request: Request, response: Single<Request.Response>) { stubs.append((request: request, response: response)) } func sendRequest<Request: APIRequest>(_ request: Request) -> Single<Request.Response> { if let index = stubs.firstIndex(where: { ($0.request as? Request) == request }) { let stub = stubs.remove(at: index) return stub.response as! Single<Request.Response> } else { return Single.error(RxError.unknown) } } }
28.333333
91
0.650588
614ce0bc3675e58a506cb4e0b51b88e9f0abdb58
279
class Solution { func maximumWealth(_ accounts: [[Int]]) -> Int { var ans = 0 accounts.forEach { account in let curr = account.reduce(0, +) if (curr > ans) { ans = curr } } return ans } }
23.25
52
0.437276
b98fc39dcfdd823c8d09954d12e86bbd4ce9f767
3,566
// // SetSizeViewController.swift // IvyControl // // Created by RRRRR on 2021/8/5. // Copyright © 2021 iGEM Whittle. All rights reserved. // import UIKit import PencilKit class SetSizeViewController: UIViewController { @IBOutlet var widthTextField: UITextField! @IBOutlet var heightTextField: UITextField! @IBOutlet var createButton: UIButton! override func viewDidLoad() { super.viewDidLoad() widthTextField.delegate = self // Do any additional setup after loading the view. createButton.backgroundColor = .systemFill if #available(iOS 15, *) { sheetPresentationController?.detents = [.medium(), .large()] sheetPresentationController?.prefersGrabberVisible = true } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) widthTextField.becomeFirstResponder() } @IBAction func widthChanged() { if widthTextField.text! == "" { createButton.isEnabled = false createButton.backgroundColor = .systemFill } else { createButton.isEnabled = true createButton.backgroundColor = .systemGreen } } @IBAction func createCanvas() { let homePage = self.presentingViewController as! UINavigationController self.dismiss(animated: true, completion: { [self] in let canvasNav = self.storyboard!.instantiateViewController(withIdentifier: "CanvasNav") as! UINavigationController let canvasVC = canvasNav.viewControllers.first as! CanvasViewController let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let newDrawing = Drawing(context: context) newDrawing.title = "Untitled" newDrawing.width = Int64(widthTextField.text!)! newDrawing.height = Int64(heightTextField.text!)! newDrawing.data = PKDrawing().dataRepresentation() canvasVC.drawing = newDrawing appDelegate.saveContext() let drawingsVC = homePage.viewControllers.first as! DrawingsViewController drawingsVC.drawings.append(newDrawing) let indexPath = IndexPath(item: drawingsVC.drawings.count - 1, section: 0) drawingsVC.collectionView.insertItems(at: [indexPath]) DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { drawingsVC.collectionView(drawingsVC.collectionView, didSelectItemAt: indexPath) }) }) } @IBAction func close() { dismiss(animated: true) } /* // 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.destination. // Pass the selected object to the new view controller. } */ } extension SetSizeViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let numbers = NSCharacterSet(charactersIn: "0123456789").inverted let filtered = (string.components(separatedBy: numbers) as NSArray).componentsJoined(by: "") return string == filtered } }
34.621359
129
0.645541
7a766124e7df4531f66652012821ddb27a66e768
1,357
// // AppDelegate.swift // prework // // Created by [email protected] on 1/11/22. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.675676
179
0.745763
e2dbd0172bf00097805ecde1c14eecee04e0c310
4,273
// // FacebookSend.swift // VaporFacebookBot // // Created by Koray Koska on 25/05/2017. // // import Foundation import Vapor public final class FacebookSend: JSONConvertible { public var recipient: FacebookSendRecipient public var message: FacebookSendMessage? public var senderAction: FacebookSenderAction? public var notificationType: FacebookSendNotificationType? public init(recipient: FacebookSendRecipient, message: FacebookSendMessage, notificationType: FacebookSendNotificationType? = nil) { self.recipient = recipient self.message = message self.notificationType = notificationType } public init(recipient: FacebookSendRecipient, senderAction: FacebookSenderAction, notificationType: FacebookSendNotificationType? = nil) { self.recipient = recipient self.senderAction = senderAction self.notificationType = notificationType } public convenience init(json: JSON) throws { let recipient = try FacebookSendRecipient(json: json.get("recipient")) var notificationType: FacebookSendNotificationType? = nil if let notificationTypeString = json["notification_type"]?.string { notificationType = FacebookSendNotificationType(rawValue: notificationTypeString) } if let m = json["message"] { let message = try FacebookSendMessage(json: m) self.init(recipient: recipient, message: message, notificationType: notificationType) } else if let s = json["sender_action"]?.string, let senderAction = FacebookSenderAction(rawValue: s) { self.init(recipient: recipient, senderAction: senderAction, notificationType: notificationType) } else { throw Abort(.badRequest, metadata: "Either message or a valid sender_action (FacebookSenderAction) must be set for FacebookSend") } } public func makeJSON() throws -> JSON { var json = JSON() try json.set("recipient", recipient) if let message = message { try json.set("message", message) } else if let senderAction = senderAction { try json.set("sender_action", senderAction) } if let notificationType = notificationType { try json.set("notification_type", notificationType) } return json } } public final class FacebookSendRecipient: JSONConvertible { public var id: String? public var phoneNumber: String? public var name: (firstName: String, lastName: String)? public init(id: String) { self.id = id } public init(phoneNumber: String, name: (firstName: String, lastName: String)? = nil) { self.phoneNumber = phoneNumber self.name = name } public convenience init(json: JSON) throws { if let id = json["id"]?.string { self.init(id: id) } else if let phoneNumber = json["phone_number"]?.string { if let firstName = json["name"]?["first_name"]?.string, let lastName = json["name"]?["last_name"]?.string { let name = (firstName: firstName, lastName: lastName) self.init(phoneNumber: phoneNumber, name: name) } else { self.init(phoneNumber: phoneNumber) } } else { throw Abort(.badRequest, metadata: "FacebookSendObjectRecipient must contain either id or phone_number!") } } public func makeJSON() throws -> JSON { var json = JSON() if let id = id { try json.set("id", id) } else if let phoneNumber = phoneNumber { try json.set("phone_number", phoneNumber) if let name = name { var nameJson = JSON() try nameJson.set("first_name", name.firstName) try nameJson.set("last_name", name.lastName) try json.set("name", nameJson) } } return json } } public enum FacebookSenderAction: String { case typingOn = "typing_on" case typingOff = "typing_off" case markSeen = "mark_seen" } public enum FacebookSendNotificationType: String { case regular = "REGULAR" case silentPush = "SILENT_PUSH" case noPush = "NO_PUSH" }
32.618321
142
0.640768
fe8b5a2e6df3481f86d9d277601b8a5d24dd3520
4,873
// // Copyright (c) 2017. Uber Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Combine import UIKit /// Protocol defining the activeness of an interactor's scope. public protocol InteractorScope: AnyObject { // The following properties must be declared in the base protocol, since `Router` internally invokes these methods. // In order to unit test router with a mock interactor, the mocked interactor first needs to conform to the custom // subclass interactor protocol, and also this base protocol to allow the `Router` implementation to execute base // class logic without error. /// Indicates if the interactor is active. var isActive: Bool { get } /// The lifecycle of this interactor. /// /// - note: Subscription to this stream always immediately returns the last event. This stream terminates after /// the interactor is deallocated. var isActiveStream: AnyPublisher<Bool, Never> { get } } /// The base protocol for all interactors. public protocol Interactable: InteractorScope { // The following methods must be declared in the base protocol, since `Router` internally invokes these methods. // In order to unit test router with a mock interactor, the mocked interactor first needs to conform to the custom // subclass interactor protocol, and also this base protocol to allow the `Router` implementation to execute base // class logic without error. /// Activate this interactor. /// /// - note: This method is internally invoked by the corresponding router. Application code should never explicitly /// invoke this method. func activate() /// Deactivate this interactor. /// /// - note: This method is internally invoked by the corresponding router. Application code should never explicitly /// invoke this method. func deactivate() } /// An `Interactor` defines a unit of business logic that corresponds to a router unit. /// /// An `Interactor` has a lifecycle driven by its owner router. When the corresponding router is attached to its /// parent, its interactor becomes active. And when the router is detached from its parent, its `Interactor` resigns /// active. /// /// An `Interactor` should only perform its business logic when it's currently active. open class Interactor: Interactable { /// Indicates if the interactor is active. public final var isActive: Bool { return isActiveSubject.value } /// A stream notifying on the lifecycle of this interactor. public final var isActiveStream: AnyPublisher<Bool, Never> { return isActiveSubject.eraseToAnyPublisher() } /// Initializer. public init() { // No-op } /// Activate the `Interactor`. /// /// - note: This method is internally invoked by the corresponding router. Application code should never explicitly /// invoke this method. public final func activate() { guard !isActive else { return } isActiveSubject.send(true) didBecomeActive() } /// The interactor did become active. /// /// - note: This method is driven by the attachment of this interactor's owner router. Subclasses should override /// this method to setup subscriptions and initial states. open func didBecomeActive() { // No-op } /// Deactivate this `Interactor`. /// /// - note: This method is internally invoked by the corresponding router. Application code should never explicitly /// invoke this method. public final func deactivate() { guard isActive else { return } willResignActive() isActiveSubject.send(false) } /// Callend when the `Interactor` will resign the active state. /// /// This method is driven by the detachment of this interactor's owner router. Subclasses should override this /// method to cleanup any resources and states of the `Interactor`. The default implementation does nothing. open func willResignActive() { // No-op } // MARK: - Private private let isActiveSubject = CurrentValueSubject<Bool, Never>(false) deinit { if isActive { deactivate() } isActiveSubject.send(completion: .finished) } }
34.807143
119
0.69054
c1075bf1ef1d58cb0693d14c69f7fc7614468b01
152
// // Adaptation.swift // AudioVisual // // Created by winpower on 2020/8/27. // Copyright © 2020 yasuo. All rights reserved. // import Foundation
15.2
48
0.677632
8f6a7f7351c29cf996a3131d10be22e53d095c68
455
// // LocationListCollectionViewCell.swift // TripModule // // Created by Gabriel Elfassi on 12/08/2019. // Copyright © 2019 Gabriel Elfassi. All rights reserved. // import UIKit class LocationListCollectionViewCell: UICollectionViewCell { // MARK: IBOutlet @IBOutlet weak var label_id:UILabel! @IBOutlet weak var label_adress:UILabel! @IBOutlet weak var image_icon:UIImageView! @IBOutlet weak var button_delete:UIButton! }
23.947368
60
0.738462
119006821a43e794ddd6d3d952f5b44932ad88ff
362
import XCTest import InputReader import Year2021 class Day6Tests: XCTestCase { let input = Input("Day6.input", Year2021.bundle) func test_part1() { // XCTAssertEqual(381699, Day1.findMatch(input: input, value: 2020)) } func test_part2() { // XCTAssertEqual(111605670, Day1.findMatch2(input: input, value: 2020)) } }
21.294118
79
0.660221
e6dd5120ce275c6934132ca01aea5c6ab2303590
1,909
// // File.swift // // // Created by Everaldlee Johnson on 10/25/20. // import Foundation /** * Standard error domain object that can also be used as the response from an API call. */ public struct Errors: Codable{ public var fieldErrors: fieldError? public var generalErrors: [generalError]? public struct fieldError: Codable { public var errorName: [String: [errorDescription]] public struct errorDescription: Codable { public let message: String public let code: String } private struct CustomCodingKeys: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? init?(intValue: Int) { return nil } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CustomCodingKeys.self) self.errorName = [String: [errorDescription]]() for key in container.allKeys { let value = try container.decode([errorDescription].self, forKey: CustomCodingKeys(stringValue: key.stringValue)!) self.errorName[key.stringValue] = value } } } public struct generalError: Codable { public let code:String public let message:String } public func Empty() -> Bool{ return fieldErrors == nil && generalErrors == nil } /** * Return the total count of all errors. All field errors and general errors */ public func Size() -> Int{ return (generalErrors?.count ?? 0) + (fieldErrors?.errorName.count ?? 0) } public func ToString() -> String{ let json = try! JSONEncoder().encode(self) return String(bytes: json, encoding: String.Encoding.utf8)! } }
26.150685
130
0.5956
e4661434729167b9bc8ad8c2795d798f0b04ff7e
719
// // Library // // Created by Otto Suess on 07.08.18. // Copyright © 2018 Zap. All rights reserved. // import UIKit extension UIStackView { convenience init(elements: [StackViewElement]) { self.init() set(elements: elements) } func set(elements: [StackViewElement]) { clear() for element in elements { addArrangedSubview(element.view()) } } @discardableResult func addArrangedElement(_ element: StackViewElement) -> UIView { let view = element.view() addArrangedSubview(view) return view } func clear() { for view in arrangedSubviews { view.removeFromSuperview() } } }
19.432432
68
0.589708
9bdf24dbe1353da21f6be878ad906ff6354e71d2
2,914
// // XDLWelcomViewController.swift // WeiBo // // Created by DalinXie on 16/9/17. // Copyright © 2016年 itcast. All rights reserved. // import UIKit import SDWebImage class XDLWelcomViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. let url = URL(string: (XDLUserAccountViewModel.shareModel.countModel?.profile_image_url)!) imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default")) } private func setupUI(){ self.view.backgroundColor = UIColor(white: 237/255, alpha: 1) view.addSubview(imageView) view.addSubview(buttomLabel) imageView.snp_makeConstraints { (make) in make.size.equalTo(CGSize(width: 90, height: 90)) make.top.equalTo(200) make.centerX.equalTo(self.view) } buttomLabel.snp_makeConstraints { (make) in make.centerX.equalTo(imageView) make.top.equalTo(imageView.snp_bottom).offset(15) } } //MARK: - lazy imageView and Label lazy var imageView :UIImageView = {()-> UIImageView in let imageView = UIImageView(image:UIImage(named:"avatar_default")) imageView.layer.cornerRadius = 45 imageView.layer.masksToBounds = true //label.textColor = UIcolor.red imageView.layer.borderColor = UIColor.gray.cgColor imageView.layer.borderWidth = 1 return imageView }() lazy var buttomLabel:UILabel = {()-> UILabel in let label = UILabel(textColor: UIColor.darkGray, fontSize: 16) label.alpha = 0 label.text = "welcome back" // label.sizeToFit() return label }() //MARK: - animation for welcomeView override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.imageView.snp_updateConstraints { (make) in make.top.equalTo(100) } UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [], animations: { self.view.layoutIfNeeded() }) { (_) in UIView.animate(withDuration: 1, animations: { self.buttomLabel.alpha = 1 }, completion: { (_) in NotificationCenter.default.post(name: NSNotification.Name(XDLChangeRootController), object: nil) }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
27.233645
132
0.573782
118518744d55de43f79c73155ffb474d006d34d8
3,492
// RUN: %target-run-stdlib-swift // REQUIRES: executable_test,optimized_stdlib // UNSUPPORTED: freestanding // Some targetted tests for the breadcrumbs path. There is some overlap with // UTF16View tests for huge strings, but we want a simpler suite that targets // some corner cases specifically. import Swift import StdlibUnittest let smallASCII = "abcdefg" let smallUnicode = "abéÏ𓀀" let largeASCII = "012345678901234567890" let largeUnicode = "abéÏ012345678901234567890𓀀" let emoji = "😀😃🤢🤮👩🏿‍🎤🧛🏻‍♂️🧛🏻‍♂️👩‍👩‍👦‍👦" let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。" let nonBMP = String(repeating: "𓀀", count: 1 + (64 / 2)) let largeString: String = { var result = "" result += smallASCII result += smallUnicode result += largeASCII result += chinese result += largeUnicode result += emoji result += smallASCII result += result.reversed() return result }() extension FixedWidthInteger { var hexStr: String { return "0x\(String(self, radix: 16, uppercase: true))" } } let StringBreadcrumbsTests = TestSuite("StringBreadcrumbsTests") func validateBreadcrumbs(_ str: String) { var utf16CodeUnits = Array(str.utf16) var outputBuffer = Array<UInt16>(repeating: 0, count: utf16CodeUnits.count) // Include the endIndex, so we can test end conversions var utf16Indices = Array(str.utf16.indices) + [str.utf16.endIndex] for i in 0...utf16CodeUnits.count { for j in i...utf16CodeUnits.count { let range = Range(uncheckedBounds: (i, j)) let indexRange = str._toUTF16Indices(range) // Range<String.Index> <=> Range<Int> expectEqual(utf16Indices[i], indexRange.lowerBound) expectEqual(utf16Indices[j], indexRange.upperBound) expectEqualSequence( utf16CodeUnits[i..<j], str.utf16[indexRange]) let roundTripOffsets = str._toUTF16Offsets(indexRange) expectEqualSequence(range, roundTripOffsets) // Single Int <=> String.Index expectEqual(indexRange.lowerBound, str._toUTF16Index(i)) expectEqual(indexRange.upperBound, str._toUTF16Index(j)) expectEqual(i, str._toUTF16Offset(indexRange.lowerBound)) expectEqual(j, str._toUTF16Offset(indexRange.upperBound)) // Copy characters outputBuffer.withUnsafeMutableBufferPointer { str._copyUTF16CodeUnits(into: $0, range: range) } expectEqualSequence(utf16CodeUnits[i..<j], outputBuffer[..<range.count]) } } } StringBreadcrumbsTests.test("uniform strings") { validateBreadcrumbs(smallASCII) validateBreadcrumbs(largeASCII) validateBreadcrumbs(smallUnicode) validateBreadcrumbs(largeUnicode) } StringBreadcrumbsTests.test("largeString") { validateBreadcrumbs(largeString) } // Test various boundary conditions with surrogate pairs aligning or not // aligning StringBreadcrumbsTests.test("surrogates-heavy") { // Mis-align the hieroglyphics by 1,2,3 UTF-8 and UTF-16 code units validateBreadcrumbs(nonBMP) validateBreadcrumbs("a" + nonBMP) validateBreadcrumbs("ab" + nonBMP) validateBreadcrumbs("abc" + nonBMP) validateBreadcrumbs("é" + nonBMP) validateBreadcrumbs("是" + nonBMP) validateBreadcrumbs("aé" + nonBMP) } // Test bread-crumb invalidation StringBreadcrumbsTests.test("stale breadcrumbs") { var str = nonBMP + "𓀀" let oldLen = str.utf16.count str.removeLast() expectEqual(oldLen - 2, str.utf16.count) str += "a" expectEqual(oldLen - 1, str.utf16.count) str += "𓀀" expectEqual(oldLen + 1, str.utf16.count) } runAllTests()
29.846154
79
0.724227
f4a0f83209ac2937c08371d3d77d404f371e5538
4,860
// // Day1018.swift // AdventOfCode // // Created by Jon Shier on 12/10/18. // Copyright © 2018 Jon Shier. All rights reserved. // import Foundation final class Day1018: Day { override func perform() async { let input = String.input(forDay: 10, year: 2018) // let input = """ // position=< 9, 1> velocity=< 0, 2> // position=< 7, 0> velocity=<-1, 0> // position=< 3, -2> velocity=<-1, 1> // position=< 6, 10> velocity=<-2, -1> // position=< 2, -4> velocity=< 2, 2> // position=<-6, 10> velocity=< 2, -2> // position=< 1, 8> velocity=< 1, -1> // position=< 1, 7> velocity=< 1, 0> // position=<-3, 11> velocity=< 1, -2> // position=< 7, 6> velocity=<-1, -1> // position=<-2, 3> velocity=< 1, 0> // position=<-4, 3> velocity=< 2, 0> // position=<10, -3> velocity=<-1, 1> // position=< 5, 11> velocity=< 1, -2> // position=< 4, 7> velocity=< 0, -1> // position=< 8, -2> velocity=< 0, 1> // position=<15, 0> velocity=<-2, 0> // position=< 1, 6> velocity=< 1, 0> // position=< 8, 9> velocity=< 0, -1> // position=< 3, 3> velocity=<-1, 1> // position=< 0, 5> velocity=< 0, -1> // position=<-2, 2> velocity=< 2, 0> // position=< 5, -2> velocity=< 1, 2> // position=< 1, 4> velocity=< 2, 1> // position=<-2, 7> velocity=< 2, -2> // position=< 3, 6> velocity=<-1, -1> // position=< 5, 0> velocity=< 1, 0> // position=<-6, 0> velocity=< 2, 0> // position=< 5, 9> velocity=< 1, -2> // position=<14, 7> velocity=<-2, 0> // position=<-3, 6> velocity=< 2, -1> // """ let stars = Stars(input) stars.simulateUntilText() print(stars) } final class Stars { var stars: [Star] var time = 0 init(_ string: String) { stars = string.byLines().map(Star.init).sorted { $0.position < $1.position } } func simulateUntilText() { var keepGoing = true var minHeight = Int.max while keepGoing { let newStars = stars.map { Star(position: $0.position + $0.velocity, velocity: $0.velocity) } let maxX = newStars.max { $0.position.x < $1.position.x }!.position.x let minX = newStars.min { $0.position.x < $1.position.x }!.position.x let lastHeight = maxX - minX if lastHeight < minHeight { minHeight = lastHeight stars = newStars time += 1 } else { keepGoing = false } } } } } extension Day1018.Stars: CustomStringConvertible { var description: String { let positions = stars.map(\.position).sorted() let largestY = positions.map(\.y).max()! let furthestPoint = Point(positions.last!.x, largestY) let allPoints = PointSequence(start: positions.first!, end: furthestPoint).map { $0 } let xs = Array(Set(allPoints.map(\.x))).sorted() let ys = Array(Set(allPoints.map(\.y))).sorted() var output = "" for y in ys { for x in xs { if positions.contains(Point(x, y)) { output.append("X") } else { output.append(" ") } } output.append("\n") } return output + "\nTime: \(time)" } } struct Star { let position: Point let velocity: Vector2D } extension Star { init(_ string: String) { let pointString = string.drop { $0 != "<" } .dropFirst() .prefix { $0 != ">" } .filter { $0 != " " } position = Point(pointString) let velocityString = string.reversed() .dropFirst() .prefix { $0 != "<" } .reversed() .filter { $0 != " " } velocity = Vector2D(String(velocityString)) } } struct Vector2D { let dx: Int let dy: Int init(_ string: String) { let components = string.trimmingCharacters(in: .whitespaces).split(separator: ",") dx = Int(components[0])! dy = Int(components[1].trimmingCharacters(in: .whitespaces))! } } func + (lhs: Point, rhs: Vector2D) -> Point { Point(lhs.x + rhs.dx, lhs.y + rhs.dy) }
34.714286
109
0.448148
ef3cd9f17a4a22336f45c316272aa2dd96a3e91a
1,568
// // MultiMap.swift // LispKit // // Created by Matthias Zenger on 18/09/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// /// Minimalistic multi map implementation. /// public struct MultiMap<Key: Hashable, Value>: CustomStringConvertible { private var map: [Key : [Value]] public init() { self.map = [:] } public var keys: Dictionary<Key, [Value]>.Keys { return map.keys } public func hasValues(for key: Key) -> Bool { return self.map[key] != nil } public func values(for key: Key) -> [Value] { return self.map[key] ?? [] } public mutating func insert(_ key: Key, mapsTo value: Value) { if self.map[key] == nil { self.map[key] = [value] } else { self.map[key]!.append(value) } } public var description: String { var builder = StringBuilder(prefix: "{", postfix: "}", separator: ", ") for (key, value) in self.map { builder.append("\(key) → \(value)") } return builder.description } }
26.576271
76
0.651786
4b72bdcb2ab497f71948bf638411e1d3790eff6d
5,281
// Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment type_body_length // -- Generated Code; do not edit -- // // AWSRDSClientGenerator.swift // RDSClient // import Foundation import RDSModel import SmokeAWSCore import SmokeHTTPClient import SmokeAWSHttp import NIO import NIOHTTP1 import AsyncHTTPClient import Logging private extension Swift.Error { func isRetriable() -> Bool { if let typedError = self as? RDSError { return typedError.isRetriable() } else { return true } } } /** AWS Client Generator for the RDS service. */ public struct AWSRDSClientGenerator { let httpClient: HTTPOperationsClient let awsRegion: AWSRegion let service: String let apiVersion: String let target: String? let retryConfiguration: HTTPClientRetryConfiguration let retryOnErrorProvider: (Swift.Error) -> Bool let credentialsProvider: CredentialsProvider let operationsReporting: RDSOperationsReporting public init(credentialsProvider: CredentialsProvider, awsRegion: AWSRegion, endpointHostName: String, endpointPort: Int = 443, requiresTLS: Bool? = nil, service: String = "rds", contentType: String = "application/octet-stream", apiVersion: String = "2014-10-31", connectionTimeoutSeconds: Int64 = 10, retryConfiguration: HTTPClientRetryConfiguration = .default, eventLoopProvider: HTTPClient.EventLoopGroupProvider = .createNew, reportingConfiguration: SmokeAWSClientReportingConfiguration<RDSModelOperations> = SmokeAWSClientReportingConfiguration<RDSModelOperations>() ) { let useTLS = requiresTLS ?? AWSHTTPClientDelegate.requiresTLS(forEndpointPort: endpointPort) let clientDelegate = XMLAWSHttpClientDelegate<RDSError>(requiresTLS: useTLS) self.httpClient = HTTPOperationsClient( endpointHostName: endpointHostName, endpointPort: endpointPort, contentType: contentType, clientDelegate: clientDelegate, connectionTimeoutSeconds: connectionTimeoutSeconds, eventLoopProvider: eventLoopProvider) self.awsRegion = awsRegion self.service = service self.target = nil self.credentialsProvider = credentialsProvider self.retryConfiguration = retryConfiguration self.retryOnErrorProvider = { error in error.isRetriable() } self.apiVersion = apiVersion self.operationsReporting = RDSOperationsReporting(clientName: "AWSRDSClient", reportingConfiguration: reportingConfiguration) } /** Gracefully shuts down this client. This function is idempotent and will handle being called multiple times. */ public func close() throws { try httpClient.close() } public func with<NewInvocationReportingType: HTTPClientCoreInvocationReporting>( reporting: NewInvocationReportingType) -> AWSRDSClient<NewInvocationReportingType> { return AWSRDSClient<NewInvocationReportingType>( credentialsProvider: self.credentialsProvider, awsRegion: self.awsRegion, reporting: reporting, httpClient: self.httpClient, service: self.service, apiVersion: self.apiVersion, retryOnErrorProvider: self.retryOnErrorProvider, retryConfiguration: self.retryConfiguration, operationsReporting: self.operationsReporting) } public func with<NewTraceContextType: InvocationTraceContext>( logger: Logging.Logger, internalRequestId: String = "none", traceContext: NewTraceContextType) -> AWSRDSClient<StandardHTTPClientCoreInvocationReporting<NewTraceContextType>> { let reporting = StandardHTTPClientCoreInvocationReporting( logger: logger, internalRequestId: internalRequestId, traceContext: traceContext) return with(reporting: reporting) } public func with( logger: Logging.Logger, internalRequestId: String = "none") -> AWSRDSClient<StandardHTTPClientCoreInvocationReporting<AWSClientInvocationTraceContext>> { let reporting = StandardHTTPClientCoreInvocationReporting( logger: logger, internalRequestId: internalRequestId, traceContext: AWSClientInvocationTraceContext()) return with(reporting: reporting) } }
39.410448
141
0.694187
9c8c64996c517d1f21c07a18dd5c2524d3a2edc4
1,530
// // AcceptTermsViewController.swift // Chatter // // Created by Benjamin Hendricks on 7/4/15. // Copyright (c) 2015 Eddy Borja. All rights reserved. // import UIKit class AcceptTermsViewController: UIViewController { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var acceptButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let url : NSURL = NSURL(string: "http://chatterapp.parseapp.com/")!; let urlRequest : NSURLRequest = NSURLRequest(URL: url); self.webView.scalesPageToFit = true; self.webView.loadRequest(urlRequest); self.navigationItem.title = "Accept Terms of Use" } 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. } */ @IBAction func acceptButtonPressed(sender: AnyObject) { var defaults = NSUserDefaults.standardUserDefaults() defaults.setBool(true, forKey:"acceptedTerms") self.navigationController?.popToRootViewControllerAnimated(true) } }
31.22449
106
0.688235
d5e069450732d68ca66e3169c9a9fe88b3b8894a
424
// // JNoticeInputCodeView.swift // GMKit_Example // // Created by 顾玉玺 on 2018/5/23. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit class JNoticeInputCodeView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
19.272727
78
0.667453
ccf2831739468fe83e6c2c215a1d3f3d72e7ac81
8,713
// // Created by Serhii Butenko on 26/9/16. // Copyright (c) 2015 Yalantis. All rights reserved. // // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at https://github.com/Yalantis/PullToMakeFlight // import Foundation import PullToRefresh public class FlightAnimator: RefreshViewAnimator { fileprivate let refreshView: FlightView init(refreshView: FlightView) { self.refreshView = refreshView } public func animate(_ state: State) { switch state { case .initial: layoutInitialState() case .releasing(let progress): layoutReleasingState(with: progress) case .loading: layoutLoadingState() case .finished: layoutFinishState() } } } fileprivate extension FlightAnimator { fileprivate func layoutInitialState() { initialLayoutForCenterClouds() initialLayoutForLeftClouds() initialLayoutForRightClouds() initialLayoutForAirplane() initialLayoutForArrows() } fileprivate func layoutReleasingState(with progress: CGFloat) { if progress <= 1 { refreshView.cloudsCenter.layer.timeOffset = Double(progress) * 0.3 refreshView.cloudsLeft.layer.timeOffset = Double(progress) * 0.3 refreshView.cloudsRight.layer.timeOffset = Double(progress) * 0.3 refreshView.airplane.layer.timeOffset = Double(progress) * 0.3 } refreshView.leftArrow.frame = CGRect( x: refreshView.leftArrow.frame.origin.x, y: refreshView.cloudsRight.layer.presentation()!.frame.origin.y - refreshView.leftArrow.frame.height, width: refreshView.leftArrow.frame.width, height: refreshView.leftArrow.frame.height ) refreshView.leftArrowStick.frame = CGRect( x: refreshView.leftArrowStick.frame.origin.x, y: refreshView.leftArrow.frame.origin.y - refreshView.leftArrowStick.frame.height + 5, width: refreshView.leftArrowStick.frame.width, height: 60 * progress ) refreshView.rightArrow.frame = CGRect( x: refreshView.rightArrow.frame.origin.x, y: refreshView.leftArrow.frame.origin.y, width: refreshView.rightArrow.frame.width, height: refreshView.rightArrow.frame.height ) refreshView.rightArrowStick.frame = CGRect( x: refreshView.rightArrowStick.frame.origin.x, y: refreshView.leftArrowStick.frame.origin.y, width: refreshView.rightArrowStick.frame.width, height: refreshView.leftArrowStick.frame.height ) } fileprivate func layoutLoadingState() { refreshView.airplane.center = CGPoint(x: refreshView.frame.width / 2, y: 50) let airplaneAnimation = CAKeyframeAnimation.animation( for: .positionY, values: [50, 45, 50, 55, 50], keyTimes: [0, 0.25, 0.5, 0.75, 1], duration: 2, beginTime: 0, timingFunctions: [.linear] ) airplaneAnimation.repeatCount = FLT_MAX; refreshView.airplane.layer.removeAllAnimations() refreshView.airplane.layer.add(airplaneAnimation, forKey: "") refreshView.airplane.layer.speed = 1 refreshView.leftArrowStick.layer.anchorPoint = CGPoint(x: 0.5, y: 0) refreshView.rightArrowStick.layer.anchorPoint = CGPoint(x: 0.5, y: 0) UIView.animate( withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 7.0, options: .curveEaseIn, animations: { var frame = self.refreshView.leftArrowStick.frame frame.size.height = 0 frame.origin.y = self.refreshView.leftArrow.frame.origin.y self.refreshView.leftArrowStick.frame = frame frame = self.refreshView.rightArrowStick.frame frame.size.height = 0 frame.origin.y = self.refreshView.leftArrow.frame.origin.y self.refreshView.rightArrowStick.frame = frame }, completion: nil ) } fileprivate func layoutFinishState() { refreshView.airplane.removeAllAnimations() refreshView.airplane.layer.timeOffset = 0.0 refreshView.airplane.addAnimation(CAKeyframeAnimation.animation( for: .position, values: [NSValue(cgPoint: CGPoint(x: refreshView.frame.width / 2, y: 50)), NSValue(cgPoint: CGPoint(x: refreshView.frame.width, y: -50))], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.airplane.layer.speed = 1 } } // Layout fileprivate extension FlightAnimator { func initialLayoutForCenterClouds() { refreshView.cloudsCenter.removeAllAnimations() refreshView.cloudsCenter.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) refreshView.cloudsCenter.layer.timeOffset = 0.0 refreshView.cloudsCenter.addAnimation(CAKeyframeAnimation.animation( for: AnimationType.positionY, values: [110, 95], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsCenter.addAnimation(CAKeyframeAnimation.animation( for: AnimationType.scaleX, values: [1, 1.2], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsCenter.addAnimation(CAKeyframeAnimation.animation( for: AnimationType.scaleY, values: [1, 1.2], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) } func initialLayoutForLeftClouds() { refreshView.cloudsLeft.removeAllAnimations() refreshView.cloudsLeft.transform = CGAffineTransform(scaleX: 1, y: 1) refreshView.cloudsLeft.layer.timeOffset = 0.0 refreshView.cloudsLeft.addAnimation(CAKeyframeAnimation.animation( for: .positionY, values: [140, 100], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsLeft.addAnimation(CAKeyframeAnimation.animation( for: .scaleX, values: [1, 1.3], keyTimes: [0.5, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsLeft.addAnimation(CAKeyframeAnimation.animation( for: .scaleY, values: [1, 1.3], keyTimes: [0.5, 1], duration: 0.3, beginTime:0) ) } func initialLayoutForRightClouds() { refreshView.cloudsRight.removeAllAnimations() refreshView.cloudsRight.transform = CGAffineTransform(scaleX: 1, y: 1) refreshView.cloudsRight.layer.timeOffset = 0.0 refreshView.cloudsRight.addAnimation(CAKeyframeAnimation.animation( for: .positionY, values: [140, 100], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsRight.addAnimation(CAKeyframeAnimation.animation( for: .scaleX, values: [1, 1.3], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.cloudsRight.addAnimation(CAKeyframeAnimation.animation( for: .scaleY, values: [1, 1.3], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) } func initialLayoutForAirplane() { refreshView.airplane.layer.removeAllAnimations() refreshView.airplane.frame = CGRect(x: 77, y: 140, width: refreshView.airplane.frame.width, height: refreshView.airplane.frame.height) refreshView.airplane.addAnimation(CAKeyframeAnimation.animation( for: .position, values: [NSValue(cgPoint: CGPoint(x: 77, y: 140)), NSValue(cgPoint: CGPoint(x: refreshView.frame.width / 2, y: 50))], keyTimes: [0, 1], duration: 0.3, beginTime:0) ) refreshView.airplane.layer.timeOffset = 0.0 } func initialLayoutForArrows() { refreshView.leftArrowStick.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) refreshView.rightArrowStick.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) } }
35.133065
150
0.590841
482ad7a48ca51dd96575f6c9708355c5463e267f
407
// // MphSystem.swift // MiningPoolHubDemo // // Created by Matthew York on 12/19/17. // Copyright © 2017 Matthew York. All rights reserved. // import Foundation import ObjectMapper public class MphSystem : Mappable { public var load: [Double] = [] init() { } // Mappable required public init?(map: Map) { } public func mapping(map: Map) { load <- map["load"] } }
16.958333
55
0.616708
46467462f7255857834caff1cb2fde6f26ca66aa
6,214
// // Matcher.swift // Split // // Created by Brian Sztamfater on 28/9/17. // // import Foundation // swiftlint:disable cyclomatic_complexity function_body_length inclusive_language class Matcher: NSObject, Codable { var keySelector: KeySelector? var matcherType: MatcherType? var negate: Bool? var userDefinedSegmentMatcherData: UserDefinedSegmentMatcherData? var whitelistMatcherData: WhitelistMatcherData? var unaryNumericMatcherData: UnaryNumericMatcherData? var betweenMatcherData: BetweenMatcherData? var dependencyMatcherData: DependencyMatcherData? var booleanMatcherData: Bool? var stringMatcherData: String? weak var client: InternalSplitClient? enum CodingKeys: String, CodingKey { case keySelector case matcherType case negate case userDefinedSegmentMatcherData case whitelistMatcherData case unaryNumericMatcherData case betweenMatcherData case dependencyMatcherData case booleanMatcherData case stringMatcherData } override init() { super.init() } required init(from decoder: Decoder) throws { if let values = try? decoder.container(keyedBy: CodingKeys.self) { keySelector = try? values.decode(KeySelector.self, forKey: .keySelector) matcherType = try? values.decode(MatcherType.self, forKey: .matcherType) negate = (try? values.decode(Bool.self, forKey: .negate)) ?? false userDefinedSegmentMatcherData = try? values.decode(UserDefinedSegmentMatcherData.self, forKey: .userDefinedSegmentMatcherData) whitelistMatcherData = try? values.decode(WhitelistMatcherData.self, forKey: .whitelistMatcherData) unaryNumericMatcherData = try? values.decode(UnaryNumericMatcherData.self, forKey: .unaryNumericMatcherData) betweenMatcherData = try? values.decode(BetweenMatcherData.self, forKey: .betweenMatcherData) dependencyMatcherData = try? values.decode(DependencyMatcherData.self, forKey: .dependencyMatcherData) booleanMatcherData = try? values.decode(Bool.self, forKey: .booleanMatcherData) stringMatcherData = try? values.decode(String.self, forKey: .stringMatcherData) } } func getMatcher() throws -> MatcherProtocol { if self.matcherType == nil { throw EvaluatorError.matcherNotFound } switch self.matcherType! { case .allKeys: return AllKeysMatcher() case .containsAllOfSet: return ContainsAllOfSetMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .containsString: return ContainsStringMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .endsWith: return EndsWithMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .startsWith: return StartWithMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .equalTo: return EqualToMatcher( data: self.unaryNumericMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .equalToBoolean: return EqualToBooleanMatcher( data: self.booleanMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .equalToSet: return EqualToSetMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .inSegment: return InSegmentMatcher( data: self.userDefinedSegmentMatcherData, splitClient: self.client, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .matchesString: return MatchesStringMatcher( data: self.stringMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .whitelist: return Whitelist( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .dependency: return DependencyMatcher( splitClient: self.client, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType, dependencyData: self.dependencyMatcherData) case .containsAnyOfSet: return ContainsAnyOfSetMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .partOfSet: return PartOfSetMatcher( data: whitelistMatcherData?.whitelist, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .lessThanOrEqualTo: return LessThanOrEqualToMatcher( data: self.unaryNumericMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .greaterThanOrEqualTo: return GreaterThanOrEqualToMatcher( data: self.unaryNumericMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) case .between: return BetweenMatcher( data: self.betweenMatcherData, negate: self.negate, attribute: self.keySelector?.attribute, type: self.matcherType) } } }
46.02963
120
0.655455