repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
darina/omim
iphone/Maps/Classes/CustomViews/MapViewControls/GuidesNavigationBar/GuidesNavigationBarViewController.swift
4
2723
class GuidesNavigationBarViewController: UIViewController { private var availableArea = CGRect.zero private var mapViewController = MapViewController.shared() private var category: BookmarkGroup @IBOutlet var navigationBar: UINavigationBar! @IBOutlet var navigationBarItem: UINavigationItem! @objc init(categoryId: MWMMarkGroupID) { category = BookmarksManager.shared().category(withId: categoryId) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationBarItem.title = category.title let leftButton: UIButton = UIButton(type: .custom) leftButton.setImage(UIImage(named: "ic_nav_bar_back")?.withRenderingMode(.alwaysTemplate), for: .normal) leftButton.setTitle(L("bookmarks_groups"), for: .normal) leftButton.addTarget(self, action: #selector(onBackPressed), for: .touchUpInside) leftButton.contentHorizontalAlignment = .left leftButton.styleName = "FlatNormalTransButton" navigationBarItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) navigationBarItem.rightBarButtonItem = UIBarButtonItem(title: L("cancel"), style: .plain, target: self, action: #selector(onCancelPessed)) refreshLayout(false) } @objc func configLayout() { guard let superview = view.superview else { fatalError() } NSLayoutConstraint.activate([ view.topAnchor.constraint(equalTo: superview.topAnchor), view.leftAnchor.constraint(equalTo: superview.leftAnchor), view.rightAnchor.constraint(equalTo: superview.rightAnchor) ]) } func refreshLayout(_ animated: Bool = true) { DispatchQueue.main.async { let availableArea = self.availableArea self.view.alpha = min(1, availableArea.height / self.view.height) } } class func updateAvailableArea(_ frame: CGRect) { guard let controller = MWMMapViewControlsManager.manager()?.guidesNavigationBar, !controller.availableArea.equalTo(frame) else { return } controller.availableArea = frame controller.refreshLayout() } @objc func onBackPressed(_ sender: Any) { MapViewController.shared()?.bookmarksCoordinator.open() Statistics.logEvent(kStatBackClick, withParameters: [kStatFrom: kStatMap, kStatTo: kStatBookmarks]) } @objc func onCancelPessed(_ sender: Any) { MapViewController.shared()?.bookmarksCoordinator.close() } }
apache-2.0
47b4f9dce62169d40dae72b9a26af42d
35.797297
108
0.672787
4.987179
false
false
false
false
hffmnn/Swiftz
Swiftz/JSONKeypath.swift
2
1151
// // JSONKeypath.swift // Swiftz // // Created by Robert Widmann on 1/29/15. // Copyright (c) 2015 TypeLift. All rights reserved. // /// Represents a subscript into a nested set of dictionaries. When used in conjunction with the /// JSON decoding machinery, this class can be used to combine strings into keypaths to target /// values inside nested JSON objects. public struct JSONKeypath : StringLiteralConvertible { typealias StringLiteralType = String public let path : [String] public init(_ path : [String]) { self.path = path } public init(unicodeScalarLiteral value : UnicodeScalar) { self.path = ["\(value)"] } public init(extendedGraphemeClusterLiteral value : String) { self.path = [value] } public init(stringLiteral value : String) { self.path = [value] } } extension JSONKeypath : Monoid { public static var mzero : JSONKeypath { return JSONKeypath([]) } public func op(other : JSONKeypath) -> JSONKeypath { return JSONKeypath(self.path + other.path) } } extension JSONKeypath : Printable { public var description : String { return intersperse(".", self.path).reduce("", combine: +) } }
bsd-3-clause
e5fd87bbd7039d3353f4428710923ab7
22.979167
96
0.705474
3.77377
false
false
false
false
exponent/exponent
packages/expo-modules-core/ios/Swift/Records/Record.swift
2
2276
/** A protocol that allows initializing the object with a dictionary. */ public protocol Record: ConvertibleArgument { /** The dictionary type that the record can be created from or converted back. */ typealias Dict = [String: Any] /** The default initializer. It enforces the structs not to have any uninitialized properties. */ init() /** Initializes a record from given dictionary. Only members wrapped by `@Field` will be set in the object. */ init(from: Dict) throws /** Converts the record back to the dictionary. Only members wrapped by `@Field` will be set in the dictionary. */ func toDictionary() -> Dict } /** Provides the default implementation of `Record` protocol. */ public extension Record { static func convert(from value: Any?) throws -> Self { if let value = value as? Dict { return try Self(from: value) } throw Conversions.ConvertingException<Self>(value) } init(from dict: Dict) throws { self.init() let dictKeys = dict.keys try fieldsOf(self).forEach { field in guard let key = field.key else { // This should never happen, but just in case skip fields without the key. return } if dictKeys.contains(key) || field.isRequired { try field.set(dict[key]) } } } func toDictionary() -> Dict { return fieldsOf(self).reduce(into: Dict()) { result, field in result[field.key!] = field.get() } } } /** Returns an array of fields found in record's mirror. If the field is missing the `key`, it gets assigned to the property label, so after all it's safe to enforce unwrapping it (using `key!`). */ private func fieldsOf(_ record: Record) -> [AnyFieldInternal] { return Mirror(reflecting: record).children.compactMap { (label: String?, value: Any) in guard var field = value as? AnyFieldInternal, let key = field.key ?? convertLabelToKey(label) else { return nil } field.options.insert(.keyed(key)) return field } } /** Converts mirror's label to field's key by dropping the "_" prefix from wrapped property label. */ private func convertLabelToKey(_ label: String?) -> String? { return (label != nil && label!.starts(with: "_")) ? String(label!.dropFirst()) : label }
bsd-3-clause
b34753e796a3b59f82f23339afedb6ff
27.810127
110
0.666081
4.100901
false
false
false
false
arbitur/Func
source/UI/KeyboardControl.swift
1
15278
// // KeyboardControl.swift // Test // // Created by Philip Fryklund on 8/Dec/16. // Copyright © 2016 Philip Fryklund. All rights reserved. // import UIKit public class KeyboardControl: NSObject { public typealias EventHandler = (_ event: KeyboardEvent) -> () public typealias KeyboardDisplayableClass = KeyboardDisplayable private var toolbar: UIToolbar? private var leftArrow: UIBarButtonItem? private var rightArrow: UIBarButtonItem? private let containerView: UIView? private let inputs: [KeyboardDisplayableClass] private var individualDelegates = [Weak<NSObjectProtocol>]() private let handler: EventHandler private weak var currentInput: KeyboardDisplayableClass? { didSet { updateToolbar() } } private var selectedIndex: Int? { return inputs.firstIndex { $0 === currentInput } } private var _isMoving: Bool = false private func handleNotification(_ notification: Notification, isOpening: Bool) { let data = KeyboardNotificationData(notification) if isOpening { UIView.performWithoutAnimation { toolbar?.frame.size.width = data.frame.width } } UIView.animate(withDuration: data.duration, delay: 0, options: data.options, animations: { if isOpening { guard let projectedInput = self.currentInput?.projectedFrame(to: self.containerView) else { return } let top = data.frame.top - 16 let distance = top - projectedInput.bottom print("Event: Opening, keyboard: \(Int(data.frame.top)), limit: \(Int(top)), input: \(Int(projectedInput.bottom)), distance: \(Int(distance))") self.handler(KeyboardEvent(isOpening: true, keyboardFrame: data.frame, input: self.currentInput!, distance: distance)) } else if !self._isMoving { print("Event: Closing, keyboardFrame: \(data.frame)") self.handler(KeyboardEvent(isOpening: false, keyboardFrame: data.frame, input: nil, distance: nil)) } }, completion: nil) } @objc private func keyboardWillShow(_ notification: Notification) { handleNotification(notification, isOpening: true) } @objc private func keyboardWillHide(_ notification: Notification) { DispatchQueue.main.async() { [self] in if currentInput == nil { handleNotification(notification, isOpening: false) } } } @objc private func keyboardDidShow(_ notification: Notification) { _isMoving = false } @objc private func keyboardDidHide(_ notification: Notification) { } private func moveToInput(_ input: KeyboardDisplayableClass) { guard input !== currentInput else { return } switch input { case let textField as UITextField: _isMoving = textField.isEnabled default: _isMoving = true } currentInput?.resignFirstResponder() input.becomeFirstResponder() } @objc private func back() { if let input = inputs[safe: selectedIndex! - 1] { moveToInput(input) } } @objc private func forward() { if let input = inputs[safe: selectedIndex! + 1] { moveToInput(input) } } @objc private func done() { currentInput?.resignFirstResponder() } private func updateToolbar() { guard let index = selectedIndex, let toolbar = toolbar else { return } switch index { case 0: leftArrow?.isEnabled = false rightArrow?.isEnabled = true case self.inputs.count - 1: leftArrow?.isEnabled = true rightArrow?.isEnabled = false default: leftArrow?.isEnabled = true rightArrow?.isEnabled = true } let input = inputs[index] switch input.keyboardAppearance! { case .dark: toolbar.barStyle = .black toolbar.items!.forEach { $0.tintColor = .white } default: toolbar.barStyle = .default toolbar.items!.forEach { $0.tintColor = UIColor(hex: 0x34AADC) } } } public func deactivate() { print("KeyboardControl deactvated") currentInput?.resignFirstResponder() NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil) } public func activate() { print("KeyboardControl activated") NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil) } /// Remember, `handler` with `self` WILL cause retain-cycle, add [unowned/weak self] in closure public init(containerView: UIView? = nil, inputs: [KeyboardDisplayableClass], inputAccessoryView: Bool = true, arrows: Bool = true, handler: @escaping EventHandler) { self.containerView = containerView self.handler = handler self.inputs = inputs super.init() // Replace inputs delegates with self and store them separatelly inputs.forEach { input in self.individualDelegates ++= Weak(data: input._delegate) input._delegate = self } if inputAccessoryView { toolbar = UIToolbar() toolbar!.isTranslucent = true toolbar!.frame.size.height = 44 toolbar!.items = [] if arrows && inputs.count > 1 { let bundle = Bundle(for: self.classForCoder) let leftImage = UIImage(named: "arrow-up", in: bundle, compatibleWith: nil) let rightImage = UIImage(named: "arrow-down", in: bundle, compatibleWith: nil) leftArrow = UIBarButtonItem(image: leftImage, style: .done, target: self, action: #selector(back)) rightArrow = UIBarButtonItem(image: rightImage, style: .done, target: self, action: #selector(forward)) toolbar!.items!.append(leftArrow!) toolbar!.items!.append(rightArrow!) } toolbar!.items!.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) toolbar!.items!.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))) for input in inputs { input.inputAccessoryView = toolbar } } } public convenience init(superview: UIView, inputAccessoryView: Bool = true, handler: @escaping EventHandler) { let inputs = superview.descendants.compactMap { $0 as? KeyboardDisplayable } self.init(containerView: superview, inputs: inputs, inputAccessoryView: inputAccessoryView, handler: handler) } deinit { print("~\(type(of: self))") } } public struct KeyboardEvent { public let isOpening: Bool public let keyboardFrame: CGRect public let input: KeyboardControl.KeyboardDisplayableClass! /// Negative distance means input is covered by keyboard public let distance: CGFloat! } private struct KeyboardNotificationData { let frame: CGRect let curve: UInt let duration: TimeInterval // let belongsToMe: Bool var options: UIView.AnimationOptions { return UIView.AnimationOptions(rawValue: curve) } init(_ notification: Notification) { let userInfo = notification.userInfo! frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval // belongsToMe = userInfo[UIResponder.keyboardIsLocalUserInfoKey] as! Bool } } private struct Weak<T: AnyObject> { weak var data: T? } public protocol KeyboardDisplayable: UIView, UITextInputTraits { var inputAccessoryView: UIView? { get set } var isFirstResponder: Bool { get } var _delegate: NSObjectProtocol? { get set } } extension UITextField: KeyboardDisplayable { public var _delegate: NSObjectProtocol? { get { return self.delegate } set { self.delegate = newValue as? UITextFieldDelegate } } } extension UITextView: KeyboardDisplayable { public var _delegate: NSObjectProtocol? { get { return self.delegate } set { self.delegate = newValue as? UITextViewDelegate } } } extension UISearchBar: KeyboardDisplayable { public var _delegate: NSObjectProtocol? { get { return self.delegate } set { self.delegate = newValue as? UISearchBarDelegate } } } extension KeyboardControl: UITextFieldDelegate { private func delegate(for textField: UITextField) -> UITextFieldDelegate? { if let index = self.inputs.firstIndex(where: { textField === $0 }) { return self.individualDelegates[index].data as? UITextFieldDelegate } return nil } public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { let shouldBeginEditing = delegate(for: textField)?.textFieldShouldBeginEditing?(textField) ?? true if shouldBeginEditing { self.currentInput = textField } return shouldBeginEditing } public func textFieldDidBeginEditing(_ textField: UITextField) { delegate(for: textField)?.textFieldDidBeginEditing?(textField) self.currentInput = textField } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return delegate(for: textField)?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(_ textField: UITextField) { delegate(for: textField)?.textFieldDidEndEditing?(textField) if textField === currentInput { self.currentInput = nil } } @available(iOS 10.0, *) public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { let d = delegate(for: textField) if d?.textFieldDidEndEditing?(textField, reason: reason) == nil { d?.textFieldDidEndEditing?(textField) } if textField === currentInput { self.currentInput = nil } } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return delegate(for: textField)?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true } public func textFieldShouldClear(_ textField: UITextField) -> Bool { return delegate(for: textField)?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField.returnKeyType { case .next: self.forward() default: self.done() } return delegate(for: textField)?.textFieldShouldReturn?(textField) ?? true } } extension KeyboardControl: UISearchBarDelegate { private func delegate(for searchBar: UISearchBar) -> UISearchBarDelegate? { if let index = self.inputs.firstIndex(where: { searchBar === $0 }) { return self.individualDelegates[index].data as? UISearchBarDelegate } return nil } public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { let shouldBegin = delegate(for: searchBar)?.searchBarShouldBeginEditing?(searchBar) ?? true if shouldBegin { self.currentInput = searchBar } return shouldBegin } public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarTextDidBeginEditing?(searchBar) currentInput = searchBar } public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { return delegate(for: searchBar)?.searchBarShouldEndEditing?(searchBar) ?? true } public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarTextDidEndEditing?(searchBar) if searchBar === currentInput { self.currentInput = nil } } public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { delegate(for: searchBar)?.searchBar?(searchBar, textDidChange: searchText) } public func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return delegate(for: searchBar)?.searchBar?(searchBar, shouldChangeTextIn: range, replacementText: text) ?? true } public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarSearchButtonClicked?(searchBar) } public func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarBookmarkButtonClicked?(searchBar) } public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarCancelButtonClicked?(searchBar) } public func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) { delegate(for: searchBar)?.searchBarResultsListButtonClicked?(searchBar) } public func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { delegate(for: searchBar)?.searchBar?(searchBar, selectedScopeButtonIndexDidChange: selectedScope) } } extension KeyboardControl: UITextViewDelegate { private func delegate(for textView: UITextView) -> UITextViewDelegate? { if let index = self.inputs.firstIndex(where: { textView === $0 }) { return self.individualDelegates[index].data as? UITextViewDelegate } return nil } public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { let shouldBeginEditing = delegate(for: textView)?.textViewShouldBeginEditing?(textView) ?? true if shouldBeginEditing { self.currentInput = textView } return shouldBeginEditing } public func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return delegate(for: textView)?.textViewShouldEndEditing?(textView) ?? true } public func textViewDidBeginEditing(_ textView: UITextView) { delegate(for: textView)?.textViewDidBeginEditing?(textView) self.currentInput = textView } public func textViewDidEndEditing(_ textView: UITextView) { delegate(for: textView)?.textViewDidEndEditing?(textView) if textView === currentInput { self.currentInput = nil } } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return delegate(for: textView)?.textView?(textView, shouldChangeTextIn: range, replacementText: text) ?? true } public func textViewDidChange(_ textView: UITextView) { delegate(for: textView)?.textViewDidChange?(textView) } public func textViewDidChangeSelection(_ textView: UITextView) { delegate(for: textView)?.textViewDidChangeSelection?(textView) } @available(iOS 10, *) public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return delegate(for: textView)?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction: interaction) ?? true } @available(iOS 10, *) public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return delegate(for: textView)?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) ?? true } }
mit
36b71845c3b0dd8a127227080439dca6
29.98783
172
0.742489
4.382387
false
false
false
false
TG908/iOS
Pods/Sweeft/Sources/Sweeft/Networking/OAuth.swift
1
4418
// // OAuth.swift // Pods // // Created by Mathias Quintero on 1/4/17. // // import Foundation public final class OAuth: Auth, Observable { public var listeners = [Listener]() var token: String var tokenType: String var refreshToken: String? var expirationDate: Date? var manager: OAuthManager<OAuthEndpoint>? var endpoint: OAuthEndpoint? private var refreshPromise: OAuth.Result? init(token: String, tokenType: String, refreshToken: String?, expirationDate: Date?, manager: OAuthManager<OAuthEndpoint>? = nil, endpoint: OAuthEndpoint? = nil) { self.token = token self.tokenType = tokenType self.refreshToken = refreshToken self.expirationDate = expirationDate self.manager = manager self.endpoint = endpoint } public func update(with auth: OAuth) { token = auth.token tokenType = auth.tokenType refreshToken = auth.refreshToken expirationDate = auth.expirationDate hasChanged() } public var isExpired: Bool { guard let expirationDate = expirationDate else { return false } return expirationDate < .now } public var isRefreshable: Bool { return ??refreshToken && ??expirationDate } public func refresh() -> OAuth.Result { guard let manager = manager, let endpoint = endpoint else { return .errored(with: .cannotPerformRequest) } return manager.refresh(at: endpoint, with: self) } public func apply(to request: URLRequest) -> Promise<URLRequest, APIError> { if isExpired { refreshPromise = self.refreshPromise ?? refresh() return refreshPromise?.onSuccess { (auth: OAuth) -> Promise<URLRequest, APIError> in self.refreshPromise = nil self.update(with: auth) return self.apply(to: request) } .future ?? .errored(with: .cannotPerformRequest) } var request = request request.addValue("\(tokenType) \(token)", forHTTPHeaderField: "Authorization") return .successful(with: request) } } extension OAuth: Deserializable { public convenience init?(from json: JSON) { guard let token = json["access_token"].string, let tokenType = json["token_type"].string else { return nil } self.init(token: token, tokenType: tokenType, refreshToken: json["refresh_token"].string, expirationDate: json["expires_in"].dateInDistanceFromNow, manager: nil, endpoint: nil) } } extension OAuth: StatusSerializable { public convenience init?(from status: [String : Any]) { guard let token = status["token"] as? String, let tokenType = status["tokenType"] as? String else { return nil } let managerStatus = status["manager"] as? [String:Any] ?? .empty let endpoint = (status["endpoint"] as? String) | OAuthEndpoint.init(rawValue:) self.init(token: token, tokenType: tokenType, refreshToken: (status["refresh"] as? String), expirationDate: (status["expiration"] as? String)?.date(), manager: OAuthManager<OAuthEndpoint>(from: managerStatus), endpoint: endpoint) } public var serialized: [String : Any] { var dict: [String:Any] = [ "token": token, "tokenType": tokenType ] dict["refresh"] <- refreshToken dict["expiration"] <- expirationDate?.string() dict["endpoint"] <- endpoint?.rawValue dict["manager"] <- manager?.serialized return dict } } extension OAuth { public func store(using key: String) { OAuthStatus.key = OAUTHStatusKey(name: key) OAuthStatus.value = self } public static func stored(with key: String) -> OAuth? { OAuthStatus.key = OAUTHStatusKey(name: key) return OAuthStatus.value } } struct OAUTHStatusKey: StatusKey { let name: String var rawValue: String { return "OAUTH-\(name)" } } struct OAuthStatus: OptionalStatus { typealias Value = OAuth static var key = OAUTHStatusKey(name: "shared") }
gpl-3.0
4ddac2eca7df528f211fe088b1dbf090
29.260274
167
0.593481
4.760776
false
false
false
false
zisko/swift
test/stdlib/StringAPI.swift
1
20958
// RUN: %target-run-simple-swift // REQUIRES: executable_test // // Tests for the non-Foundation API of String // import StdlibUnittest #if _runtime(_ObjC) import Foundation #endif var StringTests = TestSuite("StringTests") struct ComparisonTest { let expectedUnicodeCollation: ExpectedComparisonResult let lhs: String let rhs: String let loc: SourceLoc let xfail: TestRunPredicate init( _ expectedUnicodeCollation: ExpectedComparisonResult, _ lhs: String, _ rhs: String, xfail: TestRunPredicate = .never, file: String = #file, line: UInt = #line ) { self.expectedUnicodeCollation = expectedUnicodeCollation self.lhs = lhs self.rhs = rhs self.loc = SourceLoc(file, line, comment: "test data") self.xfail = xfail } func replacingPredicate(_ xfail: TestRunPredicate) -> ComparisonTest { return ComparisonTest(expectedUnicodeCollation, lhs, rhs, xfail: xfail, file: loc.file, line: loc.line) } } // List test cases for comparisons and prefix/suffix. Ideally none fail. let tests = [ ComparisonTest(.eq, "", ""), ComparisonTest(.lt, "", "a"), // ASCII cases ComparisonTest(.lt, "t", "tt"), ComparisonTest(.gt, "t", "Tt"), ComparisonTest(.gt, "\u{0}", ""), ComparisonTest(.eq, "\u{0}", "\u{0}"), ComparisonTest(.lt, "\r\n", "t"), ComparisonTest(.gt, "\r\n", "\n"), ComparisonTest(.lt, "\u{0}", "\u{0}\u{0}"), // Whitespace // U+000A LINE FEED (LF) // U+000B LINE TABULATION // U+000C FORM FEED (FF) // U+0085 NEXT LINE (NEL) // U+2028 LINE SEPARATOR // U+2029 PARAGRAPH SEPARATOR ComparisonTest(.gt, "\u{0085}", "\n"), ComparisonTest(.gt, "\u{000b}", "\n"), ComparisonTest(.gt, "\u{000c}", "\n"), ComparisonTest(.gt, "\u{2028}", "\n"), ComparisonTest(.gt, "\u{2029}", "\n"), ComparisonTest(.gt, "\r\n\r\n", "\r\n"), // U+0301 COMBINING ACUTE ACCENT // U+00E1 LATIN SMALL LETTER A WITH ACUTE ComparisonTest(.eq, "a\u{301}", "\u{e1}"), ComparisonTest(.lt, "a", "a\u{301}"), ComparisonTest(.lt, "a", "\u{e1}"), // U+304B HIRAGANA LETTER KA // U+304C HIRAGANA LETTER GA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK ComparisonTest(.eq, "\u{304b}", "\u{304b}"), ComparisonTest(.eq, "\u{304c}", "\u{304c}"), ComparisonTest(.lt, "\u{304b}", "\u{304c}"), ComparisonTest(.lt, "\u{304b}", "\u{304c}\u{3099}"), ComparisonTest(.eq, "\u{304c}", "\u{304b}\u{3099}"), ComparisonTest(.lt, "\u{304c}", "\u{304c}\u{3099}"), // U+212B ANGSTROM SIGN // U+030A COMBINING RING ABOVE // U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE ComparisonTest(.eq, "\u{212b}", "A\u{30a}"), ComparisonTest(.eq, "\u{212b}", "\u{c5}"), ComparisonTest(.eq, "A\u{30a}", "\u{c5}"), ComparisonTest(.gt, "A\u{30a}", "a"), ComparisonTest(.lt, "A", "A\u{30a}"), // U+2126 OHM SIGN // U+03A9 GREEK CAPITAL LETTER OMEGA ComparisonTest(.eq, "\u{2126}", "\u{03a9}"), // U+0323 COMBINING DOT BELOW // U+0307 COMBINING DOT ABOVE // U+1E63 LATIN SMALL LETTER S WITH DOT BELOW // U+1E69 LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE ComparisonTest(.eq, "\u{1e69}", "s\u{323}\u{307}"), ComparisonTest(.eq, "\u{1e69}", "s\u{307}\u{323}"), ComparisonTest(.eq, "\u{1e69}", "\u{1e63}\u{307}"), ComparisonTest(.eq, "\u{1e63}", "s\u{323}"), ComparisonTest(.eq, "\u{1e63}\u{307}", "s\u{323}\u{307}"), ComparisonTest(.eq, "\u{1e63}\u{307}", "s\u{307}\u{323}"), ComparisonTest(.lt, "s\u{323}", "\u{1e69}"), // U+FB01 LATIN SMALL LIGATURE FI ComparisonTest(.eq, "\u{fb01}", "\u{fb01}"), ComparisonTest(.lt, "fi", "\u{fb01}"), // U+1F1E7 REGIONAL INDICATOR SYMBOL LETTER B // \u{1F1E7}\u{1F1E7} Flag of Barbados ComparisonTest(.lt, "\u{1F1E7}", "\u{1F1E7}\u{1F1E7}"), // Test that Unicode collation is performed in deterministic mode. // // U+0301 COMBINING ACUTE ACCENT // U+0341 COMBINING ACUTE TONE MARK // U+0954 DEVANAGARI ACUTE ACCENT // // Collation elements from DUCET: // 0301 ; [.0000.0024.0002] # COMBINING ACUTE ACCENT // 0341 ; [.0000.0024.0002] # COMBINING ACUTE TONE MARK // 0954 ; [.0000.0024.0002] # DEVANAGARI ACUTE ACCENT // // U+0301 and U+0954 don't decompose in the canonical decomposition mapping. // U+0341 has a canonical decomposition mapping of U+0301. ComparisonTest(.eq, "\u{0301}", "\u{0341}"), ComparisonTest(.lt, "\u{0301}", "\u{0954}"), ComparisonTest(.lt, "\u{0341}", "\u{0954}"), ] func checkStringComparison( _ expected: ExpectedComparisonResult, _ lhs: String, _ rhs: String, _ stackTrace: SourceLocStack ) { // String / String expectEqual(expected.isEQ(), lhs == rhs, stackTrace: stackTrace) expectEqual(expected.isNE(), lhs != rhs, stackTrace: stackTrace) checkHashable( expectedEqual: expected.isEQ(), lhs, rhs, stackTrace: stackTrace.withCurrentLoc()) expectEqual(expected.isLT(), lhs < rhs, stackTrace: stackTrace) expectEqual(expected.isLE(), lhs <= rhs, stackTrace: stackTrace) expectEqual(expected.isGE(), lhs >= rhs, stackTrace: stackTrace) expectEqual(expected.isGT(), lhs > rhs, stackTrace: stackTrace) checkComparable(expected, lhs, rhs, stackTrace: stackTrace.withCurrentLoc()) #if _runtime(_ObjC) // NSString / NSString let lhsNSString = lhs as NSString let rhsNSString = rhs as NSString let expectedEqualUnicodeScalars = Array(lhs.unicodeScalars) == Array(rhs.unicodeScalars) // FIXME: Swift String and NSString comparison may not be equal. expectEqual( expectedEqualUnicodeScalars, lhsNSString == rhsNSString, stackTrace: stackTrace) expectEqual( !expectedEqualUnicodeScalars, lhsNSString != rhsNSString, stackTrace: stackTrace) checkHashable( expectedEqual: expectedEqualUnicodeScalars, lhsNSString, rhsNSString, stackTrace: stackTrace.withCurrentLoc()) #endif } // Mark the test cases that are expected to fail in checkStringComparison let comparisonTests = tests for test in comparisonTests { StringTests.test("String.{Equatable,Hashable,Comparable}: line \(test.loc.line)") .xfail(test.xfail) .code { checkStringComparison( test.expectedUnicodeCollation, test.lhs, test.rhs, test.loc.withCurrentLoc()) checkStringComparison( test.expectedUnicodeCollation.flip(), test.rhs, test.lhs, test.loc.withCurrentLoc()) } } func checkCharacterComparison( _ expected: ExpectedComparisonResult, _ lhs: Character, _ rhs: Character, _ stackTrace: SourceLocStack ) { // Character / Character expectEqual(expected.isEQ(), lhs == rhs, stackTrace: stackTrace) expectEqual(expected.isNE(), lhs != rhs, stackTrace: stackTrace) checkHashable( expectedEqual: expected.isEQ(), lhs, rhs, stackTrace: stackTrace.withCurrentLoc()) expectEqual(expected.isLT(), lhs < rhs, stackTrace: stackTrace) expectEqual(expected.isLE(), lhs <= rhs, stackTrace: stackTrace) expectEqual(expected.isGE(), lhs >= rhs, stackTrace: stackTrace) expectEqual(expected.isGT(), lhs > rhs, stackTrace: stackTrace) checkComparable(expected, lhs, rhs, stackTrace: stackTrace.withCurrentLoc()) } for test in comparisonTests { if test.lhs.count == 1 && test.rhs.count == 1 { StringTests.test("Character.{Equatable,Hashable,Comparable}: line \(test.loc.line)") .xfail(test.xfail) .code { let lhsCharacter = Character(test.lhs) let rhsCharacter = Character(test.rhs) checkCharacterComparison( test.expectedUnicodeCollation, lhsCharacter, rhsCharacter, test.loc.withCurrentLoc()) checkCharacterComparison( test.expectedUnicodeCollation.flip(), rhsCharacter, lhsCharacter, test.loc.withCurrentLoc()) } } } func checkHasPrefixHasSuffix( _ lhs: String, _ rhs: String, _ stackTrace: SourceLocStack ) { #if _runtime(_ObjC) if rhs == "" { expectTrue(lhs.hasPrefix(rhs), stackTrace: stackTrace) expectTrue(lhs.hasSuffix(rhs), stackTrace: stackTrace) return } if lhs == "" { expectFalse(lhs.hasPrefix(rhs), stackTrace: stackTrace) expectFalse(lhs.hasSuffix(rhs), stackTrace: stackTrace) return } // To determine the expected results, compare grapheme clusters, // scalar-to-scalar, of the NFD form of the strings. let lhsNFDGraphemeClusters = lhs.decomposedStringWithCanonicalMapping.map { Array(String($0).unicodeScalars) } let rhsNFDGraphemeClusters = rhs.decomposedStringWithCanonicalMapping.map { Array(String($0).unicodeScalars) } let expectHasPrefix = lhsNFDGraphemeClusters.starts( with: rhsNFDGraphemeClusters, by: (==)) let expectHasSuffix = lhsNFDGraphemeClusters.lazy.reversed() .starts(with: rhsNFDGraphemeClusters.lazy.reversed(), by: (==)) expectEqual(expectHasPrefix, lhs.hasPrefix(rhs), stackTrace: stackTrace) expectEqual(expectHasSuffix, lhs.hasSuffix(rhs), stackTrace: stackTrace) #endif } StringTests.test("LosslessStringConvertible") { checkLosslessStringConvertible(comparisonTests.map { $0.lhs }) checkLosslessStringConvertible(comparisonTests.map { $0.rhs }) } // Mark the test cases that are expected to fail in checkHasPrefixHasSuffix let substringTests = tests.map { (test: ComparisonTest) -> ComparisonTest in switch (test.expectedUnicodeCollation, test.lhs, test.rhs) { case (.eq, "\u{0}", "\u{0}"): return test.replacingPredicate(.objCRuntime( "https://bugs.swift.org/browse/SR-332")) case (.gt, "\r\n", "\n"): return test.replacingPredicate(.objCRuntime( "blocked on rdar://problem/19036555")) case (.eq, "\u{0301}", "\u{0341}"): return test.replacingPredicate(.objCRuntime( "https://bugs.swift.org/browse/SR-243")) case (.lt, "\u{1F1E7}", "\u{1F1E7}\u{1F1E7}"): return test.replacingPredicate(.objCRuntime( "https://bugs.swift.org/browse/SR-367")) default: return test } } for test in substringTests { StringTests.test("hasPrefix,hasSuffix: line \(test.loc.line)") .skip(.nativeRuntime( "String.has{Prefix,Suffix} defined when _runtime(_ObjC)")) .xfail(test.xfail) .code { checkHasPrefixHasSuffix(test.lhs, test.rhs, test.loc.withCurrentLoc()) checkHasPrefixHasSuffix(test.rhs, test.lhs, test.loc.withCurrentLoc()) let fragment = "abc" let combiner = "\u{0301}" // combining acute accent checkHasPrefixHasSuffix(test.lhs + fragment, test.rhs, test.loc.withCurrentLoc()) checkHasPrefixHasSuffix(fragment + test.lhs, test.rhs, test.loc.withCurrentLoc()) checkHasPrefixHasSuffix(test.lhs + combiner, test.rhs, test.loc.withCurrentLoc()) checkHasPrefixHasSuffix(combiner + test.lhs, test.rhs, test.loc.withCurrentLoc()) } } StringTests.test("SameTypeComparisons") { // U+0323 COMBINING DOT BELOW // U+0307 COMBINING DOT ABOVE // U+1E63 LATIN SMALL LETTER S WITH DOT BELOW let xs = "\u{1e69}" expectTrue(xs == "s\u{323}\u{307}") expectFalse(xs != "s\u{323}\u{307}") expectTrue("s\u{323}\u{307}" == xs) expectFalse("s\u{323}\u{307}" != xs) expectTrue("\u{1e69}" == "s\u{323}\u{307}") expectFalse("\u{1e69}" != "s\u{323}\u{307}") expectTrue(xs == xs) expectFalse(xs != xs) } StringTests.test("CompareStringsWithUnpairedSurrogates") .xfail( .always("<rdar://problem/18029104> Strings referring to underlying " + "storage with unpaired surrogates compare unequal")) .code { let donor = "abcdef" let acceptor = "\u{1f601}\u{1f602}\u{1f603}" expectEqual("\u{fffd}\u{1f602}\u{fffd}", acceptor[ donor.index(donor.startIndex, offsetBy: 1) ..< donor.index(donor.startIndex, offsetBy: 5) ] ) } StringTests.test("[String].joined() -> String") { let s = ["hello", "world"].joined() _ = s == "" // should compile without error } StringTests.test("UnicodeScalarView.Iterator.Lifetime") { // Tests that String.UnicodeScalarView.Iterator is maintaining the lifetime of // an underlying String buffer. https://bugs.swift.org/browse/SR-5401 // // WARNING: it is very easy to write this test so it produces false negatives // (i.e. passes even when the code is broken). The array, for example, seems // to be a requirement. So perturb this test with care! let sources = ["𝓣his 𝓘s 𝓜uch 𝓛onger 𝓣han 𝓐ny 𝓢mall 𝓢tring 𝓑uffer"] for s in sources { // Append something to s so that it creates a dynamically-allocated buffer. let i = (s + "X").unicodeScalars.makeIterator() expectEqualSequence(s.unicodeScalars, IteratorSequence(i).dropLast(), "Actual Contents: \(Array(IteratorSequence(i)))") } } StringTests.test("Regression/rdar-33276845") { // These two cases fail slightly differently when the code is broken // See rdar://33276845 do { let s = String(repeating: "x", count: 0xffff) let a = Array(s.utf8) expectNotEqual(0, a.count) } do { let s = String(repeating: "x", count: 0x1_0010) let a = Array(s.utf8) expectNotEqual(0, a.count) } } StringTests.test("Regression/corelibs-foundation") { struct NSRange { var location, length: Int } func NSFakeRange(_ location: Int, _ length: Int) -> NSRange { return NSRange(location: location, length: length) } func substring(of _storage: String, with range: NSRange) -> String { let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location) let max = _storage.utf16.index( start, offsetBy: range.location + range.length) if let substr = String(_storage.utf16[min..<max]) { return substr } //If we come here, then the range has created unpaired surrogates on either end. //An unpaired surrogate is replaced by OXFFFD - the Unicode Replacement Character. //The CRLF ("\r\n") sequence is also treated like a surrogate pair, but its constinuent //characters "\r" and "\n" can exist outside the pair! let replacementCharacter = String(describing: UnicodeScalar(0xFFFD)!) let CR: UInt16 = 13 //carriage return let LF: UInt16 = 10 //new line //make sure the range is of non-zero length guard range.length > 0 else { return "" } //if the range is pointing to a single unpaired surrogate if range.length == 1 { switch _storage.utf16[min] { case CR: return "\r" case LF: return "\n" default: return replacementCharacter } } //set the prefix and suffix characters let prefix = _storage.utf16[min] == LF ? "\n" : replacementCharacter let suffix = _storage.utf16[_storage.utf16.index(before: max)] == CR ? "\r" : replacementCharacter let postMin = _storage.utf16.index(after: min) //if the range breaks a surrogate pair at the beginning of the string if let substrSuffix = String( _storage.utf16[postMin..<max]) { return prefix + substrSuffix } let preMax = _storage.utf16.index(before: max) //if the range breaks a surrogate pair at the end of the string if let substrPrefix = String(_storage.utf16[min..<preMax]) { return substrPrefix + suffix } //the range probably breaks surrogate pairs at both the ends guard postMin <= preMax else { return prefix + suffix } let substr = String(_storage.utf16[postMin..<preMax])! return prefix + substr + suffix } let trivial = "swift.org" expectEqual(substring(of: trivial, with: NSFakeRange(0, 5)), "swift") let surrogatePairSuffix = "Hurray🎉" expectEqual(substring(of: surrogatePairSuffix, with: NSFakeRange(0, 7)), "Hurray�") let surrogatePairPrefix = "🐱Cat" expectEqual(substring(of: surrogatePairPrefix, with: NSFakeRange(1, 4)), "�Cat") let singleChar = "😹" expectEqual(substring(of: singleChar, with: NSFakeRange(0,1)), "�") let crlf = "\r\n" expectEqual(substring(of: crlf, with: NSFakeRange(0,1)), "\r") expectEqual(substring(of: crlf, with: NSFakeRange(1,1)), "\n") expectEqual(substring(of: crlf, with: NSFakeRange(1,0)), "") let bothEnds1 = "😺😺" expectEqual(substring(of: bothEnds1, with: NSFakeRange(1,2)), "��") let s1 = "😺\r\n" expectEqual(substring(of: s1, with: NSFakeRange(1,2)), "�\r") let s2 = "\r\n😺" expectEqual(substring(of: s2, with: NSFakeRange(1,2)), "\n�") let s3 = "😺cats😺" expectEqual(substring(of: s3, with: NSFakeRange(1,6)), "�cats�") let s4 = "😺cats\r\n" expectEqual(substring(of: s4, with: NSFakeRange(1,6)), "�cats\r") let s5 = "\r\ncats😺" expectEqual(substring(of: s5, with: NSFakeRange(1,6)), "\ncats�") } var CStringTests = TestSuite("CStringTests") func getNullUTF8() -> UnsafeMutablePointer<UInt8>? { return nil } func getASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x61 up[1] = 0x62 up[2] = 0 return (up, { up.deallocate() }) } func getNonASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0xd0 up[1] = 0xb0 up[2] = 0xd0 up[3] = 0xb1 up[4] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func getIllFormedUTF8String1( ) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x41 up[1] = 0xed up[2] = 0xa0 up[3] = 0x80 up[4] = 0x41 up[5] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func getIllFormedUTF8String2( ) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x41 up[0] = 0x41 up[1] = 0xed up[2] = 0xa0 up[3] = 0x81 up[4] = 0x41 up[5] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func asCCharArray(_ a: [UInt8]) -> [CChar] { return a.map { CChar(bitPattern: $0) } } func getUTF8Length(_ cString: UnsafePointer<UInt8>) -> Int { var length = 0 while cString[length] != 0 { length += 1 } return length } func bindAsCChar(_ utf8: UnsafePointer<UInt8>) -> UnsafePointer<CChar> { return UnsafeRawPointer(utf8).bindMemory(to: CChar.self, capacity: getUTF8Length(utf8)) } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: UnsafePointer<UInt8>) { var index = 0 while lhs[index] != 0 { expectEqual(lhs[index], rhs[index]) index += 1 } expectEqual(0, rhs[index]) } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: ContiguousArray<UInt8>) { rhs.withUnsafeBufferPointer { expectEqualCString(lhs, $0.baseAddress!) } } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: ContiguousArray<CChar>) { rhs.withUnsafeBufferPointer { $0.baseAddress!.withMemoryRebound( to: UInt8.self, capacity: rhs.count) { expectEqualCString(lhs, $0) } } } CStringTests.test("String.init(validatingUTF8:)") { do { let (s, dealloc) = getASCIIUTF8() expectOptionalEqual("ab", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getNonASCIIUTF8() expectOptionalEqual("аб", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() expectNil(String(validatingUTF8: bindAsCChar(s))) dealloc() } } CStringTests.test("String(cString:)") { do { let (s, dealloc) = getASCIIUTF8() let result = String(cString: s) expectEqual("ab", result) let su = bindAsCChar(s) expectEqual("ab", String(cString: su)) dealloc() } do { let (s, dealloc) = getNonASCIIUTF8() let result = String(cString: s) expectEqual("аб", result) let su = bindAsCChar(s) expectEqual("аб", String(cString: su)) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() let result = String(cString: s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) let su = bindAsCChar(s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", String(cString: su)) dealloc() } } CStringTests.test("String.decodeCString") { do { let s = getNullUTF8() let result = String.decodeCString(s, as: UTF8.self) expectNil(result) } do { // repairing let (s, dealloc) = getIllFormedUTF8String1() if let (result, repairsMade) = String.decodeCString( s, as: UTF8.self, repairingInvalidCodeUnits: true) { expectOptionalEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) expectTrue(repairsMade) } else { expectUnreachable("Expected .some()") } dealloc() } do { // non repairing let (s, dealloc) = getIllFormedUTF8String1() let result = String.decodeCString( s, as: UTF8.self, repairingInvalidCodeUnits: false) expectNil(result) dealloc() } } CStringTests.test("String.utf8CString") { do { let (cstr, dealloc) = getASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) dealloc() } do { let (cstr, dealloc) = getNonASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) dealloc() } } runAllTests()
apache-2.0
36a03223d9f9ba694c67a569a176b2ac
30.573374
91
0.668328
3.663975
false
true
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Guide/UserGuideViewController.swift
1
2989
// // UserGuideViewController.swift // WePeiYang // // Created by Allen X on 4/29/16. // Copyright © 2016 Qin Yubo. All rights reserved. // import UIKit class UserGuideViewController: UIViewController { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var startButton: UIButton! @IBAction func startButton(sender: UIButton) { } private var scrollView: UIScrollView! private let numberOfPages = 3 override func viewDidLoad() { super.viewDidLoad() let frame = self.view.bounds scrollView = UIScrollView(frame: frame) scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false scrollView.contentOffset = CGPointZero scrollView.contentSize = CGSize(width: frame.size.width * CGFloat(numberOfPages), height: frame.size.height) scrollView.delegate = self for page in 0..<numberOfPages { var imageView = UIImageView() if frame.size.height == 480.0 { imageView = UIImageView(image: UIImage(named: "guideFor4s\(page + 1)")) } else { imageView = UIImageView(image: UIImage(named: "guide\(page + 1)")) } imageView.frame = CGRect(x: frame.size.width * CGFloat(page), y: 0, width: frame.size.width, height: frame.size.height) scrollView.addSubview(imageView) } self.view.insertSubview(scrollView, atIndex: 0) startButton.layer.cornerRadius = 2.0 startButton.alpha = 0.0 } override func prefersStatusBarHidden() -> Bool { return true } override func shouldAutorotate() -> Bool { return false } 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. } */ } // MARK: - UIScrollViewDelegate extension UserGuideViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { let offset = scrollView.contentOffset pageControl.currentPage = Int(offset.x / view.bounds.width) if pageControl.currentPage == numberOfPages - 1 { UIView.animateWithDuration(0.5) { self.startButton.alpha = 1.0 } } else { UIView.animateWithDuration(0.2) { self.startButton.alpha = 0.0 } } } }
mit
a16759a0746e6018a47c0cd8f75297ae
30.452632
131
0.631191
5.125214
false
false
false
false
J-Mendes/Bliss-Assignement
Bliss-Assignement/Bliss-Assignement/Core Layer/Network/Client/NetworkClient+Share.swift
1
1548
// // NetworkClient+Share.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import Foundation extension NetworkClient { // MARK: - Dhare internal func shareViaEmail(email: String, url: String, completion: (response: AnyObject, error: NSError?) -> Void) { self.httpManager.POST(NetworkClient.baseUrl + "share?destination_email=" + email + "&content_url=" + url) .responseJSON { (response) -> Void in self.httpManager.manager?.session.invalidateAndCancel() let jsonParse: (json: AnyObject?, error: NSError?) = NetworkClient.jsonObjectFromData(response.data) switch response.result { case .Success: if let json: AnyObject = jsonParse.json { completion(response: json, error: nil) } else { completion(response: "", error: jsonParse.error) } break case .Failure: var errorCode: Int = -1 if let httpResponse: NSHTTPURLResponse = response.response { errorCode = httpResponse.statusCode } completion(response: "", error: NSError(domain: NetworkClient.domain + ".Share", code: errorCode, userInfo: nil)) break } } } }
lgpl-3.0
273d29e8e4134cc419a39f7f469db4e1
35.833333
133
0.523594
5.173913
false
false
false
false
Look-ARound/LookARound2
lookaround2/Views/AnnotationView.swift
1
4562
// // AnnotationView.swift // lookaround2 // // Created by Angela Yu on 11/9/17. // Copyright © 2017 Angela Yu. All rights reserved. // // Forked from ARAnnotationView.swift // HDAugmentedRealityDemo // // Created by Danijel Huis on 23/04/15. // Copyright (c) 2015 Danijel Huis. All rights reserved. // import UIKit import HDAugmentedReality protocol AnnotationViewDelegate { func didTouch(annotationView: AnnotationView) } class AnnotationView: ARAnnotationView { var titleLabel: UILabel? var subtitleLabel: UILabel? var pinImage: UIImageView? var likeImage: UIImageView? var checkinImage: UIImageView? var delegate: AnnotationViewDelegate? let xpos1: CGFloat = 61 override func didMoveToSuperview() { super.didMoveToSuperview() loadUI() } override func layoutSubviews() { super.layoutSubviews() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { delegate?.didTouch(annotationView: self) } func loadUI() { titleLabel?.removeFromSuperview() subtitleLabel?.removeFromSuperview() titleLabel = UILabel(frame: CGRect(x: xpos1, y: 10, width: self.frame.size.width-20, height: 30)) // titleLabel?.backgroundColor = UIColor.yellow subtitleLabel = UILabel(frame: CGRect(x: xpos1+30, y: 40, width: self.frame.size.width-20, height: 30)) // subtitleLabel?.backgroundColor = UIColor.cyan let image: UIImage = UIImage(named: "pin" )! pinImage = UIImageView(image: image) pinImage!.frame = CGRect( x:10, y:12, width: 37, height: 60 ) self.addSubview(pinImage!) let image2: UIImage = UIImage(named: "like" )! likeImage = UIImageView(image: image2) likeImage?.tintColor = UIColor.white likeImage!.frame = CGRect( x: xpos1, y: 42, width: 20, height: 20 ) let image3: UIImage = UIImage(named: "checkin" )! checkinImage = UIImageView(image: image3) checkinImage?.tintColor = UIColor.white checkinImage!.frame = CGRect( x: xpos1, y: 42, width: 20, height: 20 ) if let annotation = annotation { titleLabel?.text = annotation.title subtitleLabel?.text = annotation.identifier if (annotation.identifier?.containsIgnoreCase("like"))! { self.addSubview(likeImage!) } else { self.addSubview(checkinImage!) } } if let titleLabel = titleLabel { titleLabel.font = UIFont.boldSystemFont(ofSize: 16) titleLabel.numberOfLines = 0 titleLabel.textColor = UIColor.white updateTitleFrame(label: titleLabel) self.addSubview(titleLabel) } if let subtitleLabel = subtitleLabel { subtitleLabel.font = UIFont.systemFont(ofSize: 16) subtitleLabel.textColor = UIColor.white updateSubtitleFrame(label: subtitleLabel) self.addSubview(subtitleLabel) } //self.backgroundColor = UIColor(red:0.15, green:0.78, blue:0.85, alpha:0.6) self.backgroundColor = UIColor.darkGray self.alpha = 0.8 self.layer.cornerRadius = 5 self.clipsToBounds = true updateViewFrame(view: self) } fileprivate func updateTitleFrame(label: UILabel) { let maxSize = CGSize(width: 400-50, height: 30) let size = label.sizeThatFits(maxSize) label.frame = CGRect(x: xpos1, y: label.frame.origin.y, width: size.width, height: label.frame.size.height) } fileprivate func updateSubtitleFrame(label: UILabel) { let maxSize = CGSize(width: 400-200, height: 30) let size = label.sizeThatFits(maxSize) label.frame = CGRect(x: xpos1+30, y: label.frame.origin.y, width: size.width+30, height: label.frame.size.height) } fileprivate func updateViewFrame(view: UIView) { var maxWidth = 0 for v in view.subviews { let vw = v.frame.origin.x + v.frame.size.width + v.frame.origin.x maxWidth = max(maxWidth, Int(vw)) } view.frame.size.width = CGFloat(maxWidth) - 50 } } extension String { func contains(_ find: String) -> Bool{ return self.range(of: find) != nil } func containsIgnoreCase(_ find: String) -> Bool{ return self.range(of: find, options: .caseInsensitive) != nil } }
apache-2.0
8e7abc8eff48563926b3c373d5890f67
32.050725
121
0.618285
4.327324
false
false
false
false
wvteijlingen/Spine
Spine/Logging.swift
1
2495
// // Logging.swift // Spine // // Created by Ward van Teijlingen on 05-04-15. // Copyright (c) 2015 Ward van Teijlingen. All rights reserved. // import Foundation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } public enum LogLevel: Int { case debug = 0 case info = 1 case warning = 2 case error = 3 case none = 4 var description: String { switch self { case .debug: return "Debug " case .info: return "Info " case .warning: return "Warning " case .error: return "Error " case .none: return "None " } } } /// Logging domains /// /// - spine: The main Spine component. /// - networking: The networking component, requests, responses etc. /// - serializing: The (de)serializing component. public enum LogDomain { case spine, networking, serializing } private var logLevels: [LogDomain: LogLevel] = [.spine: .none, .networking: .none, .serializing: .none] /// Extension regarding logging. extension Spine { public static var logger: Logger = ConsoleLogger() public class func setLogLevel(_ level: LogLevel, forDomain domain: LogDomain) { logLevels[domain] = level } class func shouldLog(_ level: LogLevel, domain: LogDomain) -> Bool { return (level.rawValue >= logLevels[domain]?.rawValue) } class func logDebug<T>(_ domain: LogDomain, _ object: T) { if shouldLog(.debug, domain: domain) { logger.log(object, level: .debug) } } class func logInfo<T>(_ domain: LogDomain, _ object: T) { if shouldLog(.info, domain: domain) { logger.log(object, level: .info) } } class func logWarning<T>(_ domain: LogDomain, _ object: T) { if shouldLog(.warning, domain: domain) { logger.log(object, level: .warning) } } class func logError<T>(_ domain: LogDomain, _ object: T) { if shouldLog(.error, domain: domain) { logger.log(object, level: .error) } } } public protocol Logger { /// Logs the textual representations of `object`. func log<T>(_ object: T, level: LogLevel) } /// Logger that logs to the console using the Swift built in `print` function. struct ConsoleLogger: Logger { func log<T>(_ object: T, level: LogLevel) { print("\(level.description) - \(object)") } }
mit
95f5f0615a1f885389f4fa27d72bfe3a
22.317757
103
0.644489
3.244473
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Runtime/SyntaxRules.swift
1
16258
// // SyntaxRules.swift // LispKit // // Created by Matthias Zenger on 28/11/2015. // 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. // /// /// A `Rules` object defines syntax rules for a symbol. Class `Rules` is used to implement /// hygienic Scheme macros based on the "syntax-rules" standard. /// public final class SyntaxRules { private unowned let context: Context internal let name: Symbol? private let ellipsis: Symbol private let reserved: Set<Symbol> private let literals: Set<Symbol> private let patterns: Exprs private let templates: Exprs private let lexicalEnv: Env public init(context: Context, name: Symbol?, literals: Set<Symbol>, ellipsis: Symbol? = nil, patterns: Exprs, templates: Exprs, in env: Env) { self.context = context self.name = name self.ellipsis = ellipsis ?? context.symbols.ellipsis self.reserved = [context.symbols.wildcard, self.ellipsis] self.literals = literals self.patterns = patterns self.templates = templates self.lexicalEnv = env } internal func expand(_ input: Expr) throws -> Expr { // Swift.print("---- EXPAND: \(Expr.pair(.symbol(self.name ?? self.context.symbols.wildcard), input))") //DEBUG for index in self.patterns.indices { if let matches = self.match(self.patterns[index], with: input) { let res = try self.instantiate(template: self.templates[index], with: matches, at: 0) // Swift.print("---- RES: \(res)") return res } } throw RuntimeError.eval(.noExpansion, .pair(.symbol(self.name ?? self.context.symbols.wildcard), input)) } private func match(_ pattern: Expr, with input: Expr) -> Matches? { // print("MATCH: \(pattern) WITH: \(input)") //DEBUG let matches = Matches(self.variables(in: pattern)) return self.match(pattern, with: input, in: matches, at: 0) ? matches : nil } private func match(_ pattern: Expr, with input: Expr, in matches: Matches, at depth: Int) -> Bool { // print(String(repeating: " ", count: depth * 2) + // "MATCH: \(pattern) WITH: \(input) MATCHING: \(matches)") //DEBUG switch pattern { case .symbol(let sym): if self.literals.contains(sym.root) { if case .symbol(let inputSym) = input { return sym.root == inputSym.root } else { return false } } else { matches.put(sym, input) return true } case .pair(_, _): switch input { case .null, .pair(_, _): break default: return false } var pat = pattern var inp = input while case .pair(let token, let rest) = pat { if case .symbol(let s) = token, s.root == self.ellipsis { // ignore ellipsis } else { if case .pair(.symbol(let s), let tail) = rest, s.root == self.ellipsis { // Register variable matches.register(self.variables(in: token), at: depth + 1) // Determine maximum number of matches var maxMatchCount = inp.length - tail.length // Match input while case .pair(let car, let cdr) = inp, maxMatchCount > 0, self.match(token, with: car, in: matches, at: depth + 1) { maxMatchCount -= 1 inp = cdr } } else if case .pair(let car, let cdr) = inp, self.match(token, with: car, in: matches, at: depth) { inp = cdr } else { return false } } pat = rest } return self.match(pat, with: inp, in: matches, at: depth) case .vector(let patVector): guard case .vector(let inpVector) = input else { return false } var inpIndex = 0 for patIndex in patVector.exprs.indices { let token = patVector.exprs[patIndex] if case .symbol(let s) = token, s.root == self.ellipsis { // ignore ellipsis } else { if patIndex < patVector.exprs.count - 1, case .symbol(let s) = patVector.exprs[patIndex + 1], s.root == self.ellipsis { // Register variable matches.register(self.variables(in: token), at: depth + 1) // Determine maximum number of matches var maxMatchCount = (inpVector.exprs.count - inpIndex) - (patVector.exprs.count - patIndex - 2) // Match input while inpIndex < inpVector.exprs.count, maxMatchCount > 0, self.match(token, with: inpVector.exprs[inpIndex], in: matches, at: depth + 1) { maxMatchCount -= 1 inpIndex += 1 } } else if inpIndex < inpVector.exprs.count && self.match(token, with: inpVector.exprs[inpIndex], in: matches, at: depth) { inpIndex += 1 } else { return false } } } return inpIndex == inpVector.exprs.count default: return pattern == input } } fileprivate func instantiate(template: Expr, with matches: Matches, at depth: Int) throws -> Expr { // print(String(repeating: " ", count: depth * 2) + // "INSTANTIATE: \(template) USING: \(matches) DEPTH: \(depth)")//DEBUG switch template { case .symbol(let sym): return matches.get(sym, in: self.lexicalEnv) case .pair(.symbol(let s), let rest) where s.root == self.ellipsis: guard case .pair(let car, _) = rest else { throw RuntimeError.type(rest, expected: [.pairType]) } return self.instantiateRaw(template: car, with: matches) case .pair(_, _): var res = Exprs() var templ = template var repeater: Expr? = nil while case .pair(let token, let rest) = templ { if case .pair(.symbol(let s), _) = rest, s.root == self.ellipsis { if case .symbol(let s) = token, s.root == self.ellipsis { throw RuntimeError.eval(.macroMismatchedRepetitionPatterns, .symbol(self.ellipsis)) } repeater = token } else if case .symbol(let s) = token, s.root == self.ellipsis { guard let repeaterTemplate = repeater else { throw RuntimeError.eval(.macroMismatchedRepetitionPatterns, .symbol(self.ellipsis)) } try matches.instantiate(template: repeaterTemplate, with: self, at: depth + 1, appendingTo: &res) repeater = nil } else { res.append(try self.instantiate(template: token, with: matches, at: depth)) } templ = rest } return Expr.makeList(res, append: try self.instantiate(template: templ, with: matches, at: depth)) case .vector(let vector): var res = Exprs() for i in vector.exprs.indices { if (i < vector.exprs.count - 1), case .symbol(let s) = vector.exprs[i + 1], s.root == self.ellipsis { if case .symbol(let s) = vector.exprs[i], s.root == self.ellipsis { throw RuntimeError.eval(.macroMismatchedRepetitionPatterns, .symbol(self.ellipsis)) } } else if case .symbol(let s) = vector.exprs[i], s.root == self.ellipsis { guard i > 0 else { throw RuntimeError.eval(.macroMismatchedRepetitionPatterns, .symbol(self.ellipsis)) } try matches.instantiate(template: vector.exprs[i - 1], with: self, at: depth + 1, appendingTo: &res) } else { res.append( try self.instantiate(template: vector.exprs[i], with: matches, at: depth).datum) } } return Expr.vector( self.context.objects.manage(Collection(kind: .immutableVector, exprs: res))) default: return template } } fileprivate func instantiateRaw(template: Expr, with matches: Matches) -> Expr { switch template { case .symbol(let sym): return matches.get(sym, in: self.lexicalEnv) case .pair(_, _): var res = Exprs() var templ = template while case .pair(let token, let rest) = templ { res.append(self.instantiateRaw(template: token, with: matches)) templ = rest } return Expr.makeList(res, append: self.instantiateRaw(template: templ, with: matches)) case .vector(let vector): var res = Exprs() for i in vector.exprs.indices { res.append(self.instantiateRaw(template: vector.exprs[i], with: matches)) } return .vector(self.context.objects.manage(Collection(kind: .immutableVector, exprs: res))) default: return template } } fileprivate func variables(in pattern: Expr) -> Set<Symbol> { var vars = Set<Symbol>() func traverse(_ pattern: Expr) { switch pattern { case .symbol(let sym): if !self.literals.contains(sym.root) && !self.reserved.contains(sym.root) { vars.insert(sym) } case .pair(let car, let cdr): traverse(car) traverse(cdr) case .vector(let vector): for expr in vector.exprs { traverse(expr) } default: break } } traverse(pattern) return vars } } /// /// Class `Matches` represents the result of matching an input expression with a template. /// Objects of class `Matches` contain a mapping from symbols to values in the input expression /// as well as symbols to generated symbols. Generated symbols are needed to guarantee the /// hygiene property of Scheme's macros. /// private final class Matches: CustomStringConvertible { private var generatedSym: [Symbol : Symbol] private var matchedVal: [Symbol : MatchTree] fileprivate init(_ syms: Set<Symbol>) { self.generatedSym = [Symbol : Symbol]() self.matchedVal = [Symbol : MatchTree]() for sym in syms { self.matchedVal[sym] = MatchTree() } } fileprivate func get(_ sym: Symbol, in lexicalEnv: Env) -> Expr { guard let value = self.matchedVal[sym]?.value else { if let gensym = self.generatedSym[sym] { return .symbol(gensym) } else { let gensym = Symbol(sym, lexicalEnv) self.generatedSym[sym] = gensym return .symbol(gensym) } } return value } fileprivate func put(_ sym: Symbol, _ expr: Expr) { self.matchedVal[sym]?.enter(expr) } fileprivate func register(_ syms: Set<Symbol>, at depth: Int) { for sym in syms { self.matchedVal[sym]?.descendAt(depth) } } fileprivate func instantiate(template: Expr, with rules: SyntaxRules, at depth: Int, appendingTo exprs: inout Exprs) throws { let syms = rules.variables(in: template) for _ in 0..<(try self.numChildren(of: syms, at: depth)) { exprs.append(try rules.instantiate(template: template, with: self, at: depth)) for sym in syms { self.matchedVal[sym]?.rotateAt(depth) } } } private func numChildren(of syms: Set<Symbol>, at depth: Int) throws -> Int { var res = 0 for sym in syms { if let tree = self.matchedVal[sym] { let s = tree.numChildren(depth) if s > 0 { guard res == 0 || res == s else { throw RuntimeError.eval(.macroMismatchedRepetitionPatterns, .symbol(sym)) } res = s } } } return res } fileprivate var description: String { var res = "{", sep = "" for (sym, tree) in self.matchedVal { res += sep + sym.description + " => " + tree.description sep = ", " } return res + "}" } } /// /// A match tree is a data structure that is used to construct the value matching a particular /// pattern variable /// private final class MatchTree: CustomStringConvertible { private var root: Node = Node() private var depth: Int = 0 private var complete: Bool = false lazy var pos: [Int] = { [unowned self] in self.complete = true return [Int](repeating: 0, count: self.depth + 1) }() fileprivate enum Node: CustomStringConvertible { case leaf(Expr) case parent(MutableBox<[Node]>) fileprivate init() { self = .parent(MutableBox([Node]())) } fileprivate func appendChild(_ node: Node) { guard case .parent(let children) = self else { preconditionFailure("cannot append child to a leaf") } children.value.append(node) } fileprivate var lastChild: Node { guard case .parent(let children) = self else { preconditionFailure("a leaf does not have children") } return children.value.last! } fileprivate var numChildren: Int { switch self { case .leaf(_): return 0 case .parent(let children): return children.value.count } } fileprivate var description: String { switch self { case .leaf(let expr): return expr.description case .parent(let children): var res = "[" var sep = "" for child in children.value { res += sep res += child.description sep = ", " } return res + "]" } } } fileprivate var value: Expr? { guard case .some(.parent(let children)) = self.currentNode(self.depth) else { return nil } guard case .leaf(let expr) = children.value[self.pos[self.depth]] else { return nil } return expr } fileprivate func enter(_ expr: Expr) { self.tailNode(self.depth).appendChild(.leaf(expr)) } fileprivate func tailNode(_ depth: Int) -> Node { var res = self.root for _ in 0..<depth { res = res.lastChild } return res } private func currentNode(_ depth: Int) -> Node? { var res = self.root for i in 0..<depth { guard case .parent(let children) = res else { return nil } res = children.value[self.pos[i]] } return res } fileprivate func numChildren(_ depth: Int) -> Int { guard depth <= self.depth else { return 0 } return self.currentNode(depth)?.numChildren ?? 0 } fileprivate func descendAt(_ depth: Int) { self.tailNode(depth - 1).appendChild(Node()) self.depth = max(self.depth, depth) } fileprivate func rotateAt(_ depth: Int) { if depth <= self.depth { self.pos[depth] += 1 if self.pos[depth] >= self.currentNode(depth)!.numChildren { self.pos[depth] = 0 } } } fileprivate var description: String { var res = "(\(self.depth); \(self.root); " if self.complete { for idx in self.pos { res += " \(idx)" } } return res + ")" } }
apache-2.0
aa1616a875875c9ea713b807ef124e24
32.450617
115
0.555761
4.257988
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Timeslice.swift
1
1881
/** * Copyright IBM Corporation 2018 * * 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 /** Timeslice. */ public struct Timeslice: Decodable { /// The type of aggregation command used. For example: term, filter, max, min, etc. public var type: String? public var results: [AggregationResult]? /// Number of matching results. public var matchingResults: Int? /// Aggregations returned by the Discovery service. public var aggregations: [QueryAggregation]? /// The field where the aggregation is located in the document. public var field: String? /// Interval of the aggregation. Valid date interval values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, month/months, and year/years. public var interval: String? /// Used to inducate that anomaly detection should be performed. Anomaly detection is used to locate unusual datapoints within a time series. public var anomaly: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" case results = "results" case matchingResults = "matching_results" case aggregations = "aggregations" case field = "field" case interval = "interval" case anomaly = "anomaly" } }
mit
888777577fd44deedc4a7531138cce23
34.490566
162
0.707071
4.478571
false
false
false
false
KrishMunot/swift
test/decl/protocol/req/optional.swift
2
5968
// RUN: %target-parse-verify-swift // ----------------------------------------------------------------------- // Declaring optional requirements // ----------------------------------------------------------------------- @objc class ObjCClass { } @objc protocol P1 { optional func method(_ x: Int) // expected-note 2{{requirement 'method' declared here}} optional var prop: Int { get } // expected-note 2{{requirement 'prop' declared here}} optional subscript (i: Int) -> ObjCClass? { get } // expected-note 2{{requirement 'subscript' declared here}} } // ----------------------------------------------------------------------- // Providing witnesses for optional requirements // ----------------------------------------------------------------------- // One does not have provide a witness for an optional requirement class C1 : P1 { } // ... but it's okay to do so. class C2 : P1 { @objc func method(_ x: Int) { } @objc var prop: Int = 0 @objc subscript (c: ObjCClass) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // "Near" matches. // ----------------------------------------------------------------------- class C3 : P1 { func method(_ x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int = 0 // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C4 { } extension C4 : P1 { func method(_ x: Int) { } // expected-warning@-1{{non-@objc method 'method' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} var prop: Int { return 5 } // expected-warning@-1{{non-@objc property 'prop' cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} // expected-warning@+1{{non-@objc subscript cannot satisfy optional requirement of @objc protocol 'P1'}}{{3-3=@objc }} subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C5 : P1 { } extension C5 { func method(_ x: Int) { } var prop: Int { return 5 } subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C6 { } extension C6 : P1 { @nonobjc func method(_ x: Int) { } @nonobjc var prop: Int { return 5 } @nonobjc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // Using optional requirements // ----------------------------------------------------------------------- // Optional method references in generics. func optionalMethodGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in generics. func optionalPropertyGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in generics. func optionalSubscriptGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // Optional method references in existentials. func optionalMethodExistential(_ t: P1) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in existentials. func optionalPropertyExistential(_ t: P1) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in existentials. func optionalSubscriptExistential(_ t: P1) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // ----------------------------------------------------------------------- // Restrictions on the application of optional // ----------------------------------------------------------------------- // optional cannot be used on non-protocol declarations optional var optError: Int = 10 // expected-error{{'optional' can only be applied to protocol members}} optional struct optErrorStruct { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } optional class optErrorClass { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int = 0 // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } protocol optErrorProtocol { optional func foo(_ x: Int) // expected-error{{'optional' can only be applied to members of an @objc protocol}} optional associatedtype Assoc // expected-error{{'optional' modifier cannot be applied to this declaration}} {{3-12=}} } @objc protocol optionalInitProto { optional init() // expected-error{{'optional' cannot be applied to an initializer}} }
apache-2.0
af3dffa11eb14721e013b0546525fb94
27.555024
126
0.578921
4.135828
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/GutenbergViewController+Localization.swift
1
1628
import Foundation extension GutenbergViewController { enum Localization { static let fileName = "Localizable" } func parseGutenbergTranslations(in bundle: Bundle = Bundle.main) -> [String: [String]]? { guard let fileURL = bundle.url( forResource: Localization.fileName, withExtension: "strings", subdirectory: nil, localization: currentLProjFolderName(in: bundle) ) else { return nil } if let dictionary = NSDictionary(contentsOf: fileURL) as? [String: String] { var resultDict: [String: [String]] = [:] for (key, value) in dictionary { resultDict[key] = [value] } return resultDict } return nil } private func currentLProjFolderName(in bundle: Bundle) -> String? { // Localizable.strings file path use dashes for languages and regions (e.g. pt-BR) // We cannot use Locale.current.identifier directly because it uses underscores // Bundle.preferredLocalizations matches what NS-LocalizedString uses // and is safer than parsing and converting identifiers ourselves. // // Notice the - in the NSLocalized... method. There seem to be a bug in genstrings where // it tries to parse lines coming from comments, too: // // genstrings: error: bad entry in file WordPress/Classes/ViewRelated/Gutenberg/GutenbergViewController+Localization.swift (line = 31): Argument is not a literal string. return bundle.preferredLocalizations.first } }
gpl-2.0
e73fe3027ce34c05ef96d57bd2e7291c
39.7
177
0.632678
5.024691
false
false
false
false
invoy/CoreDataQueryInterface
CoreDataQueryInterface/Protocols.swift
1
5455
// // Protocols.swift // CoreDataQueryInterface // // Created by Gregory Higley on 9/25/16. // Copyright © 2016 Prosumma LLC. All rights reserved. // import CoreData import Foundation public protocol Entity { associatedtype CDQIAttribute: EntityAttribute } extension Entity where Self: NSManagedObject { public static func cdqiQuery(managedObjectContext: NSManagedObjectContext? = nil) -> Query<Self, Self> { var query = Query<Self, Self>() if let managedObjectContext = managedObjectContext { query = query.context(managedObjectContext: managedObjectContext) } return query } } public protocol Typed { static var cdqiStaticType: NSAttributeType { get } var cdqiType: NSAttributeType { get } } extension Typed { public static var cdqiStaticType: NSAttributeType { return .undefinedAttributeType } public var cdqiType: NSAttributeType { return type(of: self).cdqiStaticType } } public protocol ExpressionConvertible { var cdqiExpression: NSExpression { get } } extension NSExpression: ExpressionConvertible { public var cdqiExpression: NSExpression { return self } } extension NSManagedObject: ExpressionConvertible { public var cdqiExpression: NSExpression { return NSExpression(forConstantValue: self) } } extension NSManagedObjectID: ExpressionConvertible { public var cdqiExpression: NSExpression { return NSExpression(forConstantValue: self) } } public protocol TypedExpressionConvertible: ExpressionConvertible, Typed { associatedtype CDQIComparisonType: Typed } public protocol PredicateComparableTypedExpressionConvertible: TypedExpressionConvertible { } public protocol TypedConstantExpressionConvertible: TypedExpressionConvertible { } extension TypedConstantExpressionConvertible { public var cdqiExpression: NSExpression { return NSExpression(forConstantValue: (self as AnyObject)) } } public protocol PropertyConvertible { var cdqiProperty: Any { get } } extension NSPropertyDescription: PropertyConvertible { public var cdqiProperty: Any { return self } } extension String: PropertyConvertible { public var cdqiProperty: Any { return self } } public protocol SortDescriptorConvertible { func cdqiSortDescriptor(ascending: Bool) -> NSSortDescriptor } extension String: SortDescriptorConvertible { public func cdqiSortDescriptor(ascending: Bool) -> NSSortDescriptor { return NSSortDescriptor(key: self, ascending: ascending) } } extension NSSortDescriptor: SortDescriptorConvertible { public func cdqiSortDescriptor(ascending: Bool) -> NSSortDescriptor { return self } } public protocol KeyPathExpressionConvertible: ExpressionConvertible, PropertyConvertible, SortDescriptorConvertible { var cdqiKey: String? { get } var cdqiParent: KeyPathExpressionConvertible? { get } } extension KeyPathExpressionConvertible { private var cdqiRawKeyPath: String? { if cdqiKey == nil && cdqiParent == nil { return nil } guard let key = cdqiKey else { assertionFailure("Can't build cdqiKeyPath: Missing cdqiKey in KeyPathExpressionConvertible.") return nil } if let parentKeyPath = cdqiParent?.cdqiRawKeyPath { return "\(parentKeyPath).\(key)" } return key } public var cdqiKeyPath: String { if let keyPath = cdqiRawKeyPath { return keyPath } return "SELF" } private var cdqiRawName: String? { if cdqiKey == nil && cdqiParent == nil { return nil } guard let key = cdqiKey else { assertionFailure("Can't build cdqiName: Missing cdqiKey in KeyPathExpressionConvertible.") return nil } if let parentName = cdqiParent?.cdqiRawName { let index = key.index(key.startIndex, offsetBy: 1) let start = key[..<index] let remainder = key[index...] let name = "\(start.uppercased())\(remainder)" return "\(parentName)\(name)" } return key } public var cdqiName: String { return cdqiRawName! } public var cdqiExpression: NSExpression { if let key = cdqiKey, key.hasPrefix("$") { return NSExpression(forVariable: String(key[key.index(key.startIndex, offsetBy: 1)...])) } else if cdqiKeyPath == "SELF" { return NSExpression(format: "SELF") } return NSExpression(forKeyPath: cdqiKeyPath) } public var cdqiProperty: Any { let property = NSExpressionDescription() property.expression = cdqiExpression property.name = cdqiName if let typed = self as? Typed { property.expressionResultType = typed.cdqiType } return property } public func cdqiSortDescriptor(ascending: Bool) -> NSSortDescriptor { return NSSortDescriptor(key: cdqiKeyPath, ascending: ascending) } } public protocol Subqueryable: KeyPathExpressionConvertible { func cdqiSubquery(_ query: (Self) -> NSPredicate) -> ExpressionConvertible } extension Subqueryable where Self: EntityAttribute { public func cdqiSubquery(_ query: (Self) -> NSPredicate) -> ExpressionConvertible { return subquery(self, query) } }
mit
63d61638862fce6e360ffcdded8c4df8
27.554974
117
0.677301
4.882722
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Home/View/BTCoverView.swift
1
1087
// // BTCoverView.swift // BanTang // // Created by 张灿 on 16/6/13. // Copyright © 2016年 张灿. All rights reserved. // 遮盖 import UIKit class BTCoverView: UIView { //闭包作为属性 var click: () -> Void = { } class func show() -> BTCoverView { let cover = BTCoverView() cover.frame = UIScreen.mainScreen().bounds cover.backgroundColor = UIColor.blackColor() cover.alpha = 0.4 UIApplication.sharedApplication().keyWindow?.addSubview(cover) return cover } /** popShow, */ class func popShow() -> BTCoverView { let cover = BTCoverView() cover.frame = CGRect(x: 0, y: 64, width: BTscreenW, height: BTscreenH - 64 - 49) cover.backgroundColor = UIColor.blackColor() cover.alpha = 0.4 UIApplication.sharedApplication().keyWindow?.addSubview(cover) return cover } //点击屏幕调用闭包,类似代理 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.click() } }
apache-2.0
eb2a47c394ec8e6f19b1860d7b93c858
23.666667
88
0.600386
4.07874
false
false
false
false
ktmswzw/FeelingClientBySwift
FeelingClient/Library/UpLoader/PhotoUpLoader.swift
1
5289
import UIKit import Alamofire import SwiftyJSON import Toucan class PhotoUpLoader:BaseApi { let jwt = JWTTools() private var uploadMgr: TXYUploadManager!; private var sign = ""; private var bucket = "habit"; private var appId = "10005997"; private var semaphore: dispatch_semaphore_t?; private var queue: dispatch_queue_t = dispatch_get_global_queue(0, 0); static let sharedInstance = PhotoUpLoader() override init() { super.init() sign = initSign() } func initSign() -> String { if sign.length == 0 { let headers = jwt.getHeader(jwt.token, myDictionary: Dictionary<String,String>()) NetApi().makeCall(Alamofire.Method.GET, section: "user/imageSign", headers: headers, params: [:], completionHandler: { (result:BaseApi.Result) -> Void in switch (result) { case .Success(let r): if let temp = r { let myJosn = JSON(temp) self.jwt.sign = myJosn.dictionary!["message"]!.stringValue } break; case .Failure(let error): print("\(error)") break; } }) } return self.jwt.sign } func getPath(image: UIImage) -> NSData{ //压缩 let resizedAndMaskedImage = Toucan(image: image).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.Scale).image guard let data = UIImagePNGRepresentation(resizedAndMaskedImage) else {//png return UIImageJPEGRepresentation(resizedAndMaskedImage,1.0)! //jpg } return data } func completionAll(imageData:[UIImage], finishDo: CompletionHandlerType){ var path:String = "" var count = 0; for element in imageData { self.uploadToTXY(element, name: "000", completionHandler: { (result:Result) -> Void in switch (result) { case .Success(let pathIn): if let temp = pathIn { if count == 0 { path = temp as! String }else{ path = path + "," + (temp as! String) } } if count == imageData.count { finishDo(Result.Success(path)) } break; case .Failure(let error): print("\(error)") break; } }) count++ } } /// 上传至万象优图 func uploadToTXY(image: UIImage,name: String,completionHandler: CompletionHandlerType ) { let data = getPath(image) if data.length == 0 { NSLog("没有data"); completionHandler(Result.Failure("")) return; } if self.sign.length == 0 { NSLog("没有sign"); completionHandler(Result.Failure("")) return; } uploadMgr = TXYUploadManager(cloudType: TXYCloudType.ForImage, persistenceId: "", appId: self.appId); if uploadMgr == nil { semaphore = dispatch_semaphore_create(0); } dispatch_async(queue) {[weak self] () -> Void in if self?.semaphore != nil { NSLog("开始等待获取到签名信号"); let timer = dispatch_time(DISPATCH_TIME_NOW, Int64(15) * Int64(NSEC_PER_SEC)); dispatch_semaphore_wait((self?.semaphore)!, timer); self?.semaphore = nil NSLog("结束等待获取到签名信号"); } if self?.uploadMgr == nil { NSLog("不能开始上传, 万象优图上传管理器没有创建..."); completionHandler(Result.Failure("")); return; } //let uploadNode = TXYPhotoUploadTask(imageData: path, sign: self!.sign, bucket: self!.bucket, expiredDate: 0, msgContext: "msg", fileId: nil); let uploadNode = TXYPhotoUploadTask(imageData: data, fileName: name, sign: self!.sign, bucket: self!.bucket, expiredDate: 0, msgContext: "", fileId: nil); self?.uploadMgr.upload(uploadNode, complete: { (rsp: TXYTaskRsp!, context: [NSObject : AnyObject]!) -> Void in if let photoResp = rsp as? TXYPhotoUploadTaskRsp { NSLog(photoResp.photoFileId); NSLog(photoResp.photoURL); completionHandler(Result.Success(photoResp.photoURL)) } }, progress: {(total: Int64, complete: Int64, context: [NSObject : AnyObject]!) -> Void in NSLog("progress total:\(total) complete:\(complete)"); }, stateChange: {(state: TXYUploadTaskState, context: [NSObject : AnyObject]!) -> Void in NSLog("stateChange:\(state)"); }) }; } }
mit
fd9c0f02c0d8736c445fa5ae839a99d6
35.230769
166
0.497008
4.948424
false
false
false
false
RikkiGibson/Corvallis-Bus-iOS
CorvallisBusMac/BusMapViewController.swift
1
5823
// // BusMapViewController.swift // CorvallisBus // // Created by Rikki Gibson on 6/12/16. // Copyright © 2016 Rikki Gibson. All rights reserved. // import Cocoa import MapKit protocol BusMapViewControllerDataSource : class { func busStopAnnotations() -> Promise<[Int : BusStopAnnotation], BusError> } let CORVALLIS_LOCATION = CLLocation(latitude: 44.56802, longitude: -123.27926) let DEFAULT_SPAN = MKCoordinateSpanMake(0.01, 0.01) class BusMapViewController: NSViewController, MKMapViewDelegate, StopSelectionDelegate { @IBOutlet weak var mapView: MKMapView! weak var dataSource: BusMapViewControllerDataSource? let locationManagerDelegate = PromiseLocationManagerDelegate() var viewModel = BusMapViewModel(stops: [:], selectedRoute: nil, selectedStopID: nil) override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.showsUserLocation = true mapView.setRegion(MKCoordinateRegion(center: CORVALLIS_LOCATION.coordinate, span: DEFAULT_SPAN), animated: false) locationManagerDelegate.userLocation { maybeLocation in // Don't muck with the location if an annotation is selected right now guard self.mapView.selectedAnnotations.isEmpty else { return } // Only go to the user's location if they're within about 20 miles of Corvallis if case .success(let location) = maybeLocation, location.distance(from: CORVALLIS_LOCATION) < 32000 { let region = MKCoordinateRegion(center: location.coordinate, span: DEFAULT_SPAN) self.mapView.setRegion(region, animated: false) } } dataSource?.busStopAnnotations().startOnMainThread(onStopsLoaded) } // MARK: StopSelectionDelegate func onStopSelected(stopID: Int) { if let annotation = viewModel.stops[stopID] { mapView.setCenter(annotation.stop.location.coordinate, animated: true) mapView.selectAnnotation(annotation, animated: true) } } func onStopsLoaded(result: Failable<[Int: BusStopAnnotation], BusError>) { switch result { case .success(let stops): viewModel.stops = stops mapView.addAnnotations(Array(stops.values)) if let externalStopID = AppDelegate.dequeueSelectedStopID() { onStopSelected(stopID: externalStopID) } AppDelegate.stopSelectionDelegate = self case .error(let error): // TODO: show something print(error) } } @objc func onButtonClick(_ button: NSButton) { guard let selectedStop = selectedStop else { return } let defaults = UserDefaults.groupUserDefaults() var favorites = defaults.favoriteStopIds if let index = favorites.index(of: selectedStop.stop.id) { selectedStop.isFavorite = false favorites.remove(at: index) } else { favorites.append(selectedStop.stop.id) selectedStop.isFavorite = true } button.isHighlighted = selectedStop.isFavorite if let view = mapView.view(for: selectedStop) { view.update(with: selectedStop, isSelected: true) } defaults.favoriteStopIds = favorites } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? BusStopAnnotation { let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: String(describing: BusStopAnnotation.self)) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: String(describing: BusStopAnnotation.self)) annotationView.update(with: annotation, isSelected: false) let button = NSButton() button.image = NSImage(named: NSImage.Name(rawValue: "favorite")) button.alternateImage = NSImage(named: NSImage.Name(rawValue: "favorite")) button.bezelStyle = .regularSquare button.target = self button.action = #selector(BusMapViewController.onButtonClick) annotationView.rightCalloutAccessoryView = button annotationView.canShowCallout = true return annotationView } if annotation is MKUserLocation { return nil } return mapView.dequeueReusableAnnotationView(withIdentifier: String(describing: MKAnnotationView.self)) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: String(describing: MKAnnotationView.self)) } // can this variable be avoided? var selectedStop: BusStopAnnotation? func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { if let annotation = view.annotation as? BusStopAnnotation { view.update(with: annotation, isSelected: true) selectedStop = annotation // NSAnimationContext.beginGrouping() // NSAnimationContext.currentContext().duration = 0.1 // view!.setAffineTransform(CGAffineTransformMakeScale(1.3, 1.3)) // NSAnimationContext.endGrouping() } } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { if let annotation = view.annotation as? BusStopAnnotation { view.update(with: annotation, isSelected: false) selectedStop = nil // NSAnimationContext.beginGrouping() // NSAnimationContext.currentContext().duration = 0.1 // view.layer!.setAffineTransform(CGAffineTransformMakeScale(1.0, 1.0)) // NSAnimationContext.endGrouping() } } }
mit
edb3ebe6989ff6a99629aa0cde2afe30
41.188406
134
0.651838
5.193577
false
false
false
false
Ellusioists/TimingRemind
TenClock/AvoidingSubviewScrollViewDelegate.swift
2
2093
// // Created by joe on 12/2/16. // Copyright (c) 2016 Joseph Daniels. All rights reserved. // import Foundation import UIKit public class ConditionallyScrollingTableView: UITableView { public var avoidingView: UIView? = nil public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let avoidingView = avoidingView, touches.count == 1, let touch = touches.first else { return super.touchesBegan(touches, with: event) } let location = touch.location(in: avoidingView) self.isScrollEnabled = true if avoidingView.bounds.contains(location) { self.isScrollEnabled = false return } return super.touchesBegan(touches, with: event) } // } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.isScrollEnabled = true } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { // guard let avoidingView = avoidingView, touches.count == 1, let touch = touches.first else { // return super.touchesCancelled(touches, with: event) // } // let location = touch.location(in: avoidingView) self.isScrollEnabled = true // if avoidingView.bounds.contains(location) { // self.isScrollEnabled = false //// return false // } return super.touchesCancelled(touches, with: event) } override public func touchesShouldBegin (_ touches: Set<UITouch>, with event: UIEvent?, `in` view: UIView) -> Bool { guard let avoidingView = avoidingView, touches.count == 1, let touch = touches.first else { return super.touchesShouldBegin(touches, with: event, in: view) } let location = touch.location(in: avoidingView) self.isScrollEnabled = true if avoidingView.bounds.contains(location) { self.isScrollEnabled = false return false } return super.touchesShouldBegin(touches, with: event, in: view) } }
mit
e56c1958aed9bf65eca16e05a11cc0b8
37.054545
120
0.639274
4.559913
false
false
false
false
hirohisa/RxSwift
RxSwift/RxSwift/Disposables/ScheduledDisposable.swift
12
1191
// // ScheduledDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 6/13/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public class ScheduledDisposable : Cancelable { public let scheduler: ImmediateScheduler var _disposable: Disposable? var lock = SpinLock() public var disposable: Disposable { get { return lock.calculateLocked { _disposable ?? NopDisposable.instance } } } public var disposed: Bool { get { return lock.calculateLocked { return _disposable == nil } } } init(scheduler: ImmediateScheduler, disposable: Disposable) { self.scheduler = scheduler self._disposable = disposable } public func dispose() { scheduler.schedule(()) { self.disposeInner() return NopDisposableResult } } public func disposeInner() { lock.performLocked { if let disposable = _disposable { disposable.dispose() _disposable = nil } } } }
mit
1b216f363ad19641e6e1daab02d4c80d
21.923077
65
0.552477
5.293333
false
false
false
false
YoungGary/Sina
Sina/Sina/Classes/compose发布/emotionKeyboard/EmotionViewController.swift
1
6506
// // EmotionViewController.swift // Sina // // Created by YOUNG on 16/9/21. // Copyright © 2016年 Young. All rights reserved. // import UIKit class EmotionViewController: UIViewController { private lazy var emoCollectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonCollectionViewLayout()) private lazy var toolBar : UIToolbar = UIToolbar() private lazy var manager : EmoticonManager = EmoticonManager() //定义个闭包 保存选择的表情 var emotionCallBack : (emotion : Emotion) -> () //override init init(emotionCallBack : (emotion : Emotion) -> ()){ self.emotionCallBack = emotionCallBack super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupUI() } } //MARK: UI extension EmotionViewController{ private func setupUI(){ view.addSubview(emoCollectionView) view.addSubview(toolBar) emoCollectionView.backgroundColor = UIColor.whiteColor() toolBar.backgroundColor = UIColor.darkGrayColor() //frame VFL emoCollectionView.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false let views = ["tBar" : toolBar, "cView" : emoCollectionView] var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cView]-0-[tBar]-0-|", options: [.AlignAllLeft, .AlignAllRight], metrics: nil, views: views) view.addConstraints(cons) //setupCollectionView setupCollectionView() //setupToolBar setupToolBar() } } //MARK: collectionView and toolbar extension EmotionViewController{ private func setupCollectionView(){ emoCollectionView.dataSource = self emoCollectionView.delegate = self emoCollectionView.registerClass(EmotionCollectionViewCell.self, forCellWithReuseIdentifier: "collectionViewCell") } private func setupToolBar(){ // 1.定义toolBar中titles let titles = ["最近", "默认", "emoji", "浪小花"] // 2.遍历标题,创建item var index = 0 var tempItems = [UIBarButtonItem]() for title in titles { let item = UIBarButtonItem(title: title, style: .Plain, target: self, action: #selector(EmotionViewController.itemClick(_:))) item.tag = index index += 1 tempItems.append(item) tempItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)) } // 3.设置toolBar的items数组 tempItems.removeLast() toolBar.items = tempItems toolBar.tintColor = UIColor.orangeColor() } @objc private func itemClick(item : UIBarButtonItem) { // 1.获取点击的item的tag let tag = item.tag // 2.根据tag获取到当前组 let indexPath = NSIndexPath(forItem: 0, inSection: tag) // 3.滚动到对应的位置 emoCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true) } } //MARK: collectionView dataSource delegate extension EmotionViewController : UICollectionViewDataSource,UICollectionViewDelegate{ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return manager.packages.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let package = manager.packages[section] return package.emotions.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionViewCell", forIndexPath: indexPath) as! EmotionCollectionViewCell let package = manager.packages[indexPath.section] cell.emoticon = package.emotions[indexPath.item] return cell } //delegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 1.取出点击的表情 let package = manager.packages[indexPath.section] let emoticon = package.emotions[indexPath.item] // 2.将点击的表情插入最近分组中 insertRecentlyEmoticon(emoticon) //将选择的表情回调给vc emotionCallBack(emotion: emoticon) } private func insertRecentlyEmoticon(emoticon : Emotion) { // 1.如果是空白表情或者删除按钮,不需要插入 if emoticon.isRemove || emoticon.isEmpty { return } // 2.删除一个表情 if manager.packages.first!.emotions.contains(emoticon) { // 原来有该表情 let index = (manager.packages.first?.emotions.indexOf(emoticon))! manager.packages.first?.emotions.removeAtIndex(index) } else { // 原来没有这个表情 manager.packages.first?.emotions.removeAtIndex(19) } // 3.将emoticon插入最近分组中 manager.packages.first?.emotions.insert(emoticon, atIndex: 0) } } //MARK: 设置collectionViewFlowlayout class EmoticonCollectionViewLayout : UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() // 1.计算itemWH let itemWH = UIScreen.mainScreen().bounds.width / 7 // 2.设置layout的属性 itemSize = CGSize(width: itemWH, height: itemWH) minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = .Horizontal // 3.设置collectionView的属性 collectionView?.pagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false let insetMargin = (collectionView!.bounds.height - 3 * itemWH) / 2 collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0) } }
apache-2.0
7c229d73a243bfc60f4578c7640b99f4
32.235294
162
0.65535
5.144868
false
false
false
false
robocopklaus/sportskanone
Sportskanone/Views/NotificationPermissionViewController.swift
1
3759
// // NotificationPermissionViewController.swift // Sportskanone // // Created by Fabian Pahl on 28.03.17. // Copyright © 2017 21st digital GmbH. All rights reserved. // import UIKit import ReactiveCocoa import ReactiveSwift final class NotificationPermissionViewController<Store: StoreType>: UIViewController { private let verticalStackView = UIStackView() private let logoImageView = UIImageView() private let titleLabel = HeadlineLabel() private let textLabel = TextLabel() private let continueButton = BorderButton(type: .system) private let (lifetime, token) = Lifetime.make() private let viewModel: NotificationPermissionViewModel<Store> // MARK: - Object Life Cycle init(viewModel: NotificationPermissionViewModel<Store>) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle override func loadView() { let view = UIView() view.addSubview(verticalStackView) verticalStackView.addArrangedSubview(logoImageView) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(titleLabel) verticalStackView.addArrangedSubview(textLabel) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(UIView()) verticalStackView.addArrangedSubview(continueButton) self.view = view setupConstraints() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white verticalStackView.axis = .vertical verticalStackView.alignment = .center verticalStackView.spacing = 10 logoImageView.contentMode = .scaleAspectFit logoImageView.image = UIImage(named: viewModel.logoName) titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping textLabel.lineBreakMode = .byWordWrapping textLabel.numberOfLines = 0 viewModel.notificationRegistrationAction.errors .take(during: lifetime) .observe(on: UIScheduler()) .observeValues { [weak self] error in self?.presentError(error: error, title: "Error.Default.Title".localized) } viewModel.notificationRegistrationAction.completed .take(during: lifetime) .observe(on: UIScheduler()) .observeValues { UIApplication.shared.registerForRemoteNotifications() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBindings() } // MARK: - Styling func setupConstraints() { verticalStackView.translatesAutoresizingMaskIntoConstraints = false verticalStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true verticalStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true logoImageView.heightAnchor.constraint(equalTo: logoImageView.widthAnchor).isActive = true logoImageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true titleLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7).isActive = true textLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true } // MARK: - Reactive Bindings func setupBindings() { titleLabel.reactive.text <~ viewModel.title textLabel.reactive.text <~ viewModel.text continueButton.reactive.pressed = CocoaAction(viewModel.notificationRegistrationAction) continueButton.reactive.title(for: .normal) <~ viewModel.continueButtonTitle } }
mit
ca05ec25016e4d7983bcb91451144bcc
30.579832
100
0.735764
5.190608
false
false
false
false
apple/swift-docc-symbolkit
Sources/SymbolKit/SymbolGraph/Relationship/SourceOrigin.swift
1
1516
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation extension SymbolGraph.Relationship { /// A mixin defining a source symbol's origin. public struct SourceOrigin: Mixin, Codable, Hashable { public static var mixinKey = "sourceOrigin" /// Precise Identifier public var identifier: String /// Display Name public var displayName: String public init(identifier: String, displayName: String) { self.identifier = identifier self.displayName = displayName } enum CodingKeys: String, CodingKey { case identifier, displayName } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifier = try container.decode(String.self, forKey: .identifier) displayName = try container.decode(String.self, forKey: .displayName) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(identifier, forKey: .identifier) try container.encode(displayName, forKey: .displayName) } } }
apache-2.0
efed49f02194a0dbef932ad95c920228
32.688889
81
0.668206
5.0033
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/Link.swift
1
1963
import CoreData import EurofurenceWebAPI @objc(Link) public class Link: NSManagedObject { @nonobjc class func fetchRequest() -> NSFetchRequest<Link> { return NSFetchRequest<Link>(entityName: "Link") } @NSManaged public var fragmentType: String @NSManaged public var name: String? @NSManaged public var target: String } // MARK: - Content Resolution extension Link { enum Destination { case dealer(Dealer) init?(dealer: String, managedObjectContext: NSManagedObjectContext) { let fetchRequest: NSFetchRequest<Dealer> = Dealer.fetchRequest() fetchRequest.fetchLimit = 1 fetchRequest.predicate = NSPredicate(format: "identifier == %@", dealer) do { let fetchedResults = try managedObjectContext.fetch(fetchRequest) if let dealer = fetchedResults.first { self = .dealer(dealer) } else { return nil } } catch { return nil } } } var destination: Destination? { guard let managedObjectContext = managedObjectContext else { return nil } switch fragmentType.lowercased() { case "dealerdetail": return Destination(dealer: target, managedObjectContext: managedObjectContext) default: return nil } } } // MARK: - Link + Identifiable extension Link: Identifiable { public var id: some Hashable { var hasher = Hasher() hasher.combine(fragmentType) hasher.combine(target) return hasher.finalize() } } // MARK: - Updating extension Link { func update(from link: EurofurenceWebAPI.Link) { fragmentType = link.fragmentType name = link.name target = link.target } }
mit
442ef20a69ed5c43979bd11050e766a8
22.939024
90
0.570555
5.467967
false
false
false
false
antlr/antlr4
runtime/Swift/Sources/Antlr4/CommonTokenStream.swift
6
4238
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// This class extends _org.antlr.v4.runtime.BufferedTokenStream_ with functionality to filter /// token streams to tokens on a particular channel (tokens where /// _org.antlr.v4.runtime.Token#getChannel_ returns a particular value). /// /// /// This token stream provides access to all tokens by index or when calling /// methods like _#getText_. The channel filtering is only used for code /// accessing tokens via the lookahead methods _#LA_, _#LT_, and /// _#LB_. /// /// /// By default, tokens are placed on the default channel /// (_org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_), but may be reassigned by using the /// `->channel(HIDDEN)` lexer command, or by using an embedded action to /// call _org.antlr.v4.runtime.Lexer#setChannel_. /// /// /// /// Note: lexer rules which use the `->skip` lexer command or call /// _org.antlr.v4.runtime.Lexer#skip_ do not produce tokens at all, so input text matched by /// such a rule will not be available as part of the token stream, regardless of /// channel. /// public class CommonTokenStream: BufferedTokenStream { /// /// Specifies the channel to use for filtering tokens. /// /// /// The default value is _org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_, which matches the /// default channel assigned to tokens created by the lexer. /// internal var channel = CommonToken.DEFAULT_CHANNEL /// /// Constructs a new _org.antlr.v4.runtime.CommonTokenStream_ using the specified token /// source and the default token channel (_org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_). /// /// - parameter tokenSource: The token source. /// public override init(_ tokenSource: TokenSource) { super.init(tokenSource) } /// /// Constructs a new _org.antlr.v4.runtime.CommonTokenStream_ using the specified token /// source and filtering tokens to the specified channel. Only tokens whose /// _org.antlr.v4.runtime.Token#getChannel_ matches `channel` or have the /// _org.antlr.v4.runtime.Token#getType_ equal to _org.antlr.v4.runtime.Token#EOF_ will be returned by the /// token stream lookahead methods. /// /// - parameter tokenSource: The token source. /// - parameter channel: The channel to use for filtering tokens. /// public convenience init(_ tokenSource: TokenSource, _ channel: Int) { self.init(tokenSource) self.channel = channel } override internal func adjustSeekIndex(_ i: Int) throws -> Int { return try nextTokenOnChannel(i, channel) } override internal func LB(_ k: Int) throws -> Token? { if k == 0 || (p - k) < 0 { return nil } var i = p var n = 1 // find k good tokens looking backwards while n <= k { // skip off-channel tokens try i = previousTokenOnChannel(i - 1, channel) n += 1 } if i < 0 { return nil } return tokens[i] } override public func LT(_ k: Int) throws -> Token? { //System.out.println("enter LT("+k+")"); try lazyInit() if k == 0 { return nil } if k < 0 { return try LB(-k) } var i = p var n = 1 // we know tokens[p] is a good one // find k good tokens while n < k { // skip off-channel tokens, but make sure to not look past EOF if try sync(i + 1) { i = try nextTokenOnChannel(i + 1, channel) } n += 1 } // if ( i>range ) range = i; return tokens[i] } /// /// Count EOF just once. /// public func getNumberOfOnChannelTokens() throws -> Int { var n = 0 try fill() for t in tokens { if t.getChannel() == channel { n += 1 } if t.getType() == CommonToken.EOF { break } } return n } }
bsd-3-clause
b5d439fe5277f82a8e952c528cca38b7
30.626866
110
0.587777
4.090734
false
false
false
false
thoughtbot/poppins
UnitTests/Fakes/FakeDropboxService.swift
3
1286
import Result class FakeDropboxService: LinkableService { var lastCall: String = "" var controller: UIViewController? var url: NSURL? let type: Service = .Dropbox let client: SyncClient = FakeDropboxSyncClient() func setup() { lastCall = "setup" } func initiateAuthentication<A>(controller: A) { lastCall = "connect" self.controller = controller as? UIViewController } func finalizeAuthentication(url: NSURL) -> Bool { lastCall = "handleURL" self.url = url return true } func isLinked() -> Bool { lastCall = "isLinked" return false } func unLink() { lastCall = "unlink" } } class FakeDropboxSyncClient: SyncClient { var lastCall: String = "" func getFiles() -> Signal<[FileInfo]> { lastCall = "getFiles" return Signal() } func getFile(path: String, destinationPath: String) -> Signal<String> { lastCall = "getFile" return Signal() } func getShareURL(path: String) -> Signal<String> { lastCall = "getShareURL" return Signal() } func uploadFile(filename: String, localPath: String) -> Signal<Void> { lastCall = "uploadFile" return Signal() } }
mit
288dbbfb3c4ed3cc98b971fe81867531
21.172414
75
0.595645
4.258278
false
false
false
false
CalebeEmerick/Checkout
Source/Checkout/CreditCardTransactionResult.swift
1
1313
// // CreditCardTransactionResult.swift // Checkout // // Created by Calebe Emerick on 09/12/16. // Copyright © 2016 CalebeEmerick. All rights reserved. // import Foundation struct CreditCardTransactionResult { let message: String let amount: Int64 let brand: String let maskedNumber: String init() { self.message = "" self.amount = 0 self.brand = "" self.maskedNumber = "" } init(message: String, amount: Int64, brand: String, maskedNumber: String) { self.message = message self.amount = amount self.brand = brand self.maskedNumber = maskedNumber } } extension CreditCardTransactionResult : JSONDecodable { init?(json: JSON) { guard let message = json["AcquirerMessage"] as? String, let amount = json["AmountInCents"] as? Int64, let creditCardInformation = json["CreditCard"] as? JSON, let brand = creditCardInformation["CreditCardBrand"] as? String, let maskedCard = creditCardInformation["MaskedCreditCardNumber"] as? String else { return nil } self.message = message self.amount = amount self.brand = brand self.maskedNumber = maskedCard } }
mit
78a6f2544352aceeb3b10b4ae55d6d4d
24.72549
87
0.605183
4.571429
false
false
false
false
5calls/ios
FiveCalls/FiveCalls/IssuesContainerViewController.swift
1
9414
// // IssuesContainerViewController.swift // FiveCalls // // Created by Ben Scheirman on 2/1/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit import CoreLocation class IssuesContainerViewController : UIViewController, EditLocationViewControllerDelegate { @IBOutlet weak var headerView: UIView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var locationButton: UIButton! @IBOutlet weak var footerView: UIView! @IBOutlet weak var headerContainer: UIView! @IBOutlet weak var headerContainerConstraint: NSLayoutConstraint! @IBOutlet weak var iPadShareButton: UIButton! @IBOutlet weak var editRemindersButton: UIButton! @IBOutlet weak var fiveCallsButton: UIButton! let splitController = UISplitViewController() static let headerHeight: CGFloat = 90 var issuesViewController: IssuesViewController! var issuesManager = IssuesManager() var contactsManager = ContactsManager() lazy var effectView: UIVisualEffectView = { let effectView = UIVisualEffectView(frame: self.headerContainer.bounds) effectView.translatesAutoresizingMaskIntoConstraints = false effectView.effect = UIBlurEffect(style: .light) return effectView }() private func configureChildViewController() { let isRegularWidth = traitCollection.horizontalSizeClass == .regular let issuesVC = R.storyboard.main.issuesViewController()! issuesVC.issuesManager = issuesManager issuesVC.contactsManager = contactsManager issuesVC.issuesDelegate = self let childController: UIViewController if isRegularWidth { let issuesNavigation = UINavigationController(rootViewController: issuesVC) splitController.viewControllers = [issuesNavigation, UIViewController()] splitController.preferredDisplayMode = .allVisible childController = splitController issuesVC.iPadShareButton = self.iPadShareButton self.navigationController?.setNavigationBarHidden(true, animated: false) // layout the split controller before we get the width, otherwise it's the whole screen splitController.view.layoutIfNeeded() headerContainerConstraint.constant = self.splitController.primaryColumnWidth } else { childController = issuesVC } addChild(childController) view.insertSubview(childController.view, belowSubview: headerContainer) childController.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ childController.view.topAnchor.constraint(equalTo: view.topAnchor), childController.view.leftAnchor.constraint(equalTo: view.leftAnchor), childController.view.rightAnchor.constraint(equalTo: view.rightAnchor), childController.view.bottomAnchor.constraint(equalTo: footerView.topAnchor) ]) childController.didMove(toParent: self) issuesViewController = issuesVC } override func viewDidLoad() { super.viewDidLoad() setTitleLabel(location: UserLocation.current) configureChildViewController() setupHeaderWithBlurEffect() editRemindersButton.tintColor = R.color.darkBlue() locationButton.tintColor = R.color.darkBlue() let image = UIImage(named: "gear")?.withRenderingMode(.alwaysTemplate) editRemindersButton.setImage(image, for: .normal) } private func setupHeaderWithBlurEffect() { headerView.translatesAutoresizingMaskIntoConstraints = false effectView.contentView.addSubview(headerView) headerContainer.addSubview(effectView) NSLayoutConstraint.activate([ effectView.contentView.topAnchor.constraint(equalTo: headerView.topAnchor), effectView.contentView.bottomAnchor.constraint(equalTo: headerView.bottomAnchor), effectView.contentView.leftAnchor.constraint(equalTo: headerView.leftAnchor), effectView.contentView.rightAnchor.constraint(equalTo: headerView.rightAnchor), headerContainer.topAnchor.constraint(equalTo: effectView.topAnchor), headerContainer.bottomAnchor.constraint(equalTo: effectView.bottomAnchor), headerContainer.leftAnchor.constraint(equalTo: effectView.leftAnchor), headerContainer.rightAnchor.constraint(equalTo: effectView.rightAnchor) ]) } private func setContentInset() { // Fix for odd force unwrapping in crash noted in bug #75 guard issuesViewController != nil && headerContainer != nil else { return } // headercontainer is attached to the top of the screen not the safe area so we get the behind effect all the way to the top // however this means it's height grows from the expected 40 to safe area height + 40 let headerHeightSansSafeArea = headerContainer.frame.size.height - (UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0) issuesViewController.tableView.contentInset.top = headerHeightSansSafeArea issuesViewController.tableView.scrollIndicatorInsets.top = headerHeightSansSafeArea } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection != nil && previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { issuesViewController.willMove(toParent: nil) issuesViewController.view.constraints.forEach { constraint in issuesViewController.view.removeConstraint(constraint) } issuesViewController.view.removeFromSuperview() issuesViewController.removeFromParent() configureChildViewController() } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { guard splitController.viewControllers.count > 0 else { return } coordinator.animate(alongsideTransition: { [unowned self] _ in let showingSideBar = self.splitController.isCollapsed self.headerContainerConstraint.constant = !showingSideBar ? self.splitController.primaryColumnWidth : 0 }) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // no content inset for iPads if traitCollection.horizontalSizeClass != .regular { setContentInset() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) // don't need to listen anymore because any change comes from this VC (otherwise we'll end up fetching twice) NotificationCenter.default.removeObserver(self, name: .locationChanged, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // we need to know if location changes by any other VC so we can update our UI NotificationCenter.default.addObserver(self, selector: #selector(IssuesContainerViewController.locationDidChange(_:)), name: .locationChanged, object: nil) } @IBAction func setLocationTapped(_ sender: Any) { } @IBAction func addReminderTapped(_ sender: UIButton) { if let reminderViewController = R.storyboard.about.enableReminderVC(), let navController = R.storyboard.about.aboutNavController() { navController.setViewControllers([reminderViewController], animated: false) present(navController, animated: true, completion: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let nc = segue.destination as? UINavigationController, let vc = nc.topViewController as? EditLocationViewController { vc.delegate = self } } @objc func locationDidChange(_ notification: Notification) { let location = notification.object as! UserLocation setTitleLabel(location: location) } // MARK: - EditLocationViewControllerDelegate func editLocationViewControllerDidCancel(_ vc: EditLocationViewController) { dismiss(animated: true, completion: nil) } func editLocationViewController(_ vc: EditLocationViewController, didUpdateLocation location: UserLocation) { DispatchQueue.main.async { [weak self] in self?.dismiss(animated: true) { self?.issuesViewController.loadData(needsIssues: true) self?.setTitleLabel(location: location) } } } // MARK: - Private functions private func setTitleLabel(location: UserLocation?) { locationButton.setTitle(UserLocation.current.locationDisplay ?? "Set Location", for: .normal) } } extension IssuesContainerViewController : IssuesViewControllerDelegate { func didStartLoadingIssues() { activityIndicator.startAnimating() } func didFinishLoadingIssues() { activityIndicator.stopAnimating() } }
mit
d1dbf04dea18843f3842e1802bef6990
42.578704
163
0.698821
5.89787
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Gallery/Photos/PhotoViewController.swift
9
2363
import UIKit final class PhotoViewController: UIViewController { let scalingView = PhotoScalingView() let photo: GalleryItemModel private(set) lazy var doubleTapGestureRecognizer: UITapGestureRecognizer = { let gesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapWithGestureRecognizer(_:))) gesture.numberOfTapsRequired = 2 return gesture }() init(photo: GalleryItemModel) { self.photo = photo super.init(nibName: nil, bundle: nil) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() scalingView.delegate = self scalingView.frame = view.bounds scalingView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(scalingView) view.addGestureRecognizer(doubleTapGestureRecognizer) scalingView.photo = photo } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() scalingView.frame = view.bounds } @objc private func handleDoubleTapWithGestureRecognizer(_ recognizer: UITapGestureRecognizer) { let pointInView = recognizer.location(in: scalingView.imageView) var newZoomScale = scalingView.maximumZoomScale if scalingView.zoomScale >= scalingView.maximumZoomScale || abs(scalingView.zoomScale - scalingView.maximumZoomScale) <= 0.01 { newZoomScale = scalingView.minimumZoomScale } let scrollViewSize = scalingView.bounds.size let width = scrollViewSize.width / newZoomScale let height = scrollViewSize.height / newZoomScale let originX = pointInView.x - (width / 2.0) let originY = pointInView.y - (height / 2.0) let rectToZoom = CGRect(x: originX, y: originY, width: width, height: height) scalingView.zoom(to: rectToZoom, animated: true) } } extension PhotoViewController: UIScrollViewDelegate { func viewForZooming(in _: UIScrollView) -> UIView? { return scalingView.imageView } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with _: UIView?) { scrollView.panGestureRecognizer.isEnabled = true } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with _: UIView?, atScale _: CGFloat) { if scrollView.zoomScale == scrollView.minimumZoomScale { scrollView.panGestureRecognizer.isEnabled = false } } }
apache-2.0
592090f0fe827db81e62647111e46364
30.092105
115
0.735506
4.974737
false
false
false
false
googleprojectzero/fuzzilli
Sources/Fuzzilli/Util/WeightedList.swift
1
3030
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// A list where each element also has a weight, which determines how frequently it is selected by randomElement(). /// For example, an element with weight 10 is 2x more likely to be selected by randomElement() than an element with weight 5. public struct WeightedList<Element>: Sequence { private var elements = [(elem: Element, weight: Int, cumulativeWeight: Int)]() private var totalWeight = 0 public init() {} public init(_ values: [(Element, Int)]) { for (e, w) in values { append(e, withWeight: w) } } public var count: Int { return elements.count } public var isEmpty: Bool { return count == 0 } public mutating func append(_ elem: Element, withWeight weight: Int) { assert(weight > 0) elements.append((elem, weight, totalWeight)) totalWeight += weight } public func filter(_ isIncluded: (Element) -> Bool) -> WeightedList<Element> { var r = WeightedList() for (e, w, _) in elements where isIncluded(e) { r.append(e, withWeight: w) } return r } public func randomElement() -> Element { // Binary search: pick a random value between 0 and the sum of all weights, then find the // first element whose cumulative weight is less-than or equal to the selected one. let v = Int.random(in: 0..<totalWeight) var low = 0 var high = elements.count - 1 while low != high { let mid = low + (high - low + 1) / 2 // Verify the invariants of this binary search implementation. assert(0 <= low && low <= mid && mid <= high && high < elements.count) assert(elements[low].cumulativeWeight <= v) assert(high == elements.count - 1 || elements[high + 1].cumulativeWeight > v) if elements[mid].cumulativeWeight > v { high = mid - 1 } else { low = mid } } // Also verify the results of this binary search implementation. assert(elements[low].cumulativeWeight <= v) assert(low == 0 || elements[low - 1].cumulativeWeight < v) assert(low == elements.count - 1 || elements[low + 1].cumulativeWeight > v) return elements[low].elem } public func makeIterator() -> Array<Element>.Iterator { return elements.map({ $0.elem }).makeIterator() } }
apache-2.0
7174c39e64050a9f66524038413ee14a
35.071429
125
0.619142
4.40407
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureDebug/Sources/FeatureDebugUI/DebugView.swift
1
15973
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Algorithms import BlockchainComponentLibrary import BlockchainNamespace import Collections import Combine import DIKit import Examples import SwiftUI import ToolKit // swiftlint:disable force_try public protocol NetworkDebugScreenProvider { @ViewBuilder func buildDebugView() -> AnyView } struct DebugView: View { var window: UIWindow? @LazyInject var app: AppProtocol @State var pulse: Bool = false @State var layoutDirection: LayoutDirection = .leftToRight var body: some View { PrimaryNavigationView { ScrollView { VStack { PrimaryDivider() PrimaryNavigationLink( destination: FeatureFlags() .primaryNavigation(title: "⛳️ Feature Flags") ) { PrimaryRow(title: "⛳️ Feature Flags") } PrimaryDivider() PrimaryNavigationLink( destination: Examples.RootView.content .environment(\.layoutDirection, layoutDirection) .primaryNavigation(title: "📚 Component Library") { Button(layoutDirection == .leftToRight ? "➡️" : "⬅️") { layoutDirection = layoutDirection == .leftToRight ? .rightToLeft : .leftToRight } } ) { PrimaryRow(title: "📚 Component Library") } PrimaryDivider() PrimaryRow(title: "🤖 Pulse") { pulse = true } } .background(Color.semantic.background) } .sheet(isPresented: $pulse) { Pulse() .ignoresSafeArea() .onDisappear { pulse = false } } .primaryNavigation(title: "Debug") { Button(window?.overrideUserInterfaceStyle == .dark ? "☀️" : "🌑") { if let window = window { switch window.overrideUserInterfaceStyle { case .dark: window.overrideUserInterfaceStyle = .light default: window.overrideUserInterfaceStyle = .dark } } } } } .app(app) } } extension DebugView { struct NamespaceState: View { @BlockchainApp var app @Binding var filter: String init(_ filter: Binding<String>) { _filter = filter } let pasteboard = UIPasteboard.general @StateObject var observer: StateObserver = .init() func description(for key: Tag.Reference) -> String { observer.data[key]?.pretty ?? JSON.null.pretty } var keys: [Tag.Reference] { if filter.isEmpty { return Array(observer.data.keys) } return observer.data.keys.filter { key in key.string.replacingOccurrences(of: ".", with: " ") .distance( between: filter, using: FuzzyAlgorithm(caseInsensitive: true) ) < 0.3 } } var body: some View { if observer.data.isEmpty { ProgressView().onAppear { observer.observe(on: app) } } ForEach(keys, id: \.self) { key in VStack(alignment: .leading) { Text(key.string) .typography(.micro.bold()) HStack(alignment: .top) { switch key.tag { case blockchain.db.type.boolean: Text(description(for: key)) .typography(.micro) Spacer() PrimarySwitch( accessibilityLabel: key.string, isOn: app.binding(key).isYes ) case blockchain.db.type.integer: Spacer() Stepper( label: { Text(description(for: key)) .typography(.body1.bold()) }, onIncrement: { app.state.set(key, to: (try? app.state.get(key, as: Int.self) + 1).or(0).clamped(to: 0...)) }, onDecrement: { app.state.set(key, to: (try? app.state.get(key, as: Int.self) - 1).or(0).clamped(to: 0...)) } ) default: Text(description(for: key)) .typography(.micro) } } } .frame( maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading ) .padding() .background( RoundedRectangle(cornerRadius: 8, style: .continuous) .fill(Color.semantic.background) .shadow(color: .gray, radius: 2, x: 0, y: 2) ) .foregroundColor(.semantic.title) .multilineTextAlignment(.leading) .padding([.leading, .trailing]) .contextMenu { Button( action: { pasteboard.string = key.string }, label: { Label("Copy Name", systemImage: "doc.on.doc.fill") } ) Button( action: { pasteboard.string = observer.data[key]?.pretty }, label: { Label("Copy", systemImage: "doc.on.doc.fill") } ) if key.tag.is(blockchain.session.state.value) { Button( action: { app.state.clear(key) }, label: { Label("Clear", systemImage: "trash.fill") } ) } } } } } class StateObserver: ObservableObject { @Published var data: OrderedDictionary<Tag.Reference, JSON> = [:] private var isFetching = false private var subscription: AnyCancellable? init() {} func observe(on app: AppProtocol) { guard subscription.isNil else { return } subscription = app.publisher(for: blockchain.app.configuration.debug.observers, as: [Tag.Reference?].self) .compactMap(\.value) .flatMap { events in events.compacted().map(app.publisher(for:)).combineLatest() } .map { results in results.reduce(into: [:]) { sum, result in sum[result.metadata.ref] = try? result.value.decode(JSON.self) } } .receive(on: DispatchQueue.main) .sink { [weak self] results in self?.data = results } } } struct FeatureFlags: View { @BlockchainApp var app @State var data: [AppFeature: JSON] = [:] @State var filter: String = "" var body: some View { ScrollView { VStack { namespace Section(header: Text("Remote").typography(.title2)) { remote } } PrimaryButton(title: "Reset to default") { app.remoteConfiguration.clear() } .padding() } .listRowInsets( EdgeInsets( top: 0, leading: 0, bottom: 0, trailing: 0 ) ) .background(Color.semantic.background) .apply { view in if #available(iOS 15.0, *) { view.searchable(text: $filter) } } } let pasteboard = UIPasteboard.general @ViewBuilder var namespace: some View { NamespaceState($filter) } var keys: [AppFeature] { if filter.isEmpty { return AppFeature.allCases } return AppFeature.allCases.filter { key in key.remoteEnabledKey .distance( between: filter, using: FuzzyAlgorithm(caseInsensitive: true) ) < 0.3 } } @ViewBuilder var remote: some View { ForEach(keys, id: \.self) { feature in let name = feature.remoteEnabledKey Group { if let value = data[feature] { PrimaryRow( title: name, subtitle: value.description, trailing: { if value.isBoolean { PrimarySwitch( accessibilityLabel: name, isOn: Binding<Bool>( get: { try! app.remoteConfiguration.get(name) as! Bool }, set: { newValue in app.remoteConfiguration.override(name, with: newValue) } ) ) } } ) .typography(.caption1) .contextMenu { Button( action: { pasteboard.string = name }, label: { Label("Copy Name", systemImage: "doc.on.doc.fill") } ) Button( action: { pasteboard.string = value.description }, label: { Label("Copy JSON", systemImage: "doc.on.doc.fill") } ) } } else { PrimaryRow( title: name, trailing: { ProgressView() } ) .typography(.caption1) } } .onReceive( app.remoteConfiguration .publisher(for: name) .tryMap { output in try output.decode(JSON.self) } .replaceError(with: .null) ) { json in data[feature] = json } } } } struct Pulse: View { @Inject var networkDebugScreenProvider: NetworkDebugScreenProvider var body: some View { networkDebugScreenProvider.buildDebugView() } } } enum JSON: Codable, Equatable, CustomStringConvertible { case null case boolean(Bool) case string(String) case number(NSNumber) case array([JSON]) case object([String: JSON]) var isBoolean: Bool { if case .boolean = self { return true } return false } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .null } else if let boolean = try? container.decode(Bool.self) { self = .boolean(boolean) } else if let int = try? container.decode(Int.self) { self = .number(NSNumber(value: int)) } else if let double = try? container.decode(Double.self) { self = .number(NSNumber(value: double)) } else if let string = try? container.decode(String.self) { self = .string(string) } else if let array = try? container.decode([JSON].self) { self = .array(array) } else if let object = try? container.decode([String: JSON].self) { self = .object(object) } else { throw DecodingError.typeMismatch( JSON.self, .init( codingPath: decoder.codingPath, debugDescription: "Expected to decode JSON value" ) ) } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .null: try container.encodeNil() case .boolean(let bool): try container.encode(bool) case .number(let number): switch CFNumberGetType(number) { case .intType, .nsIntegerType, .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type: try container.encode(number.intValue) default: try container.encode(number.doubleValue) } case .string(let string): try container.encode(string) case .array(let array): try container.encode(array) case .object(let object): try container.encode(object) } } var pretty: String { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] do { return String(decoding: try encoder.encode(self), as: UTF8.self) } catch { return "<invalid json>" } } var description: String { pretty } } extension AppProtocol { func binding(_ event: Tag.Event) -> Binding<Any?> { let key = event.key() switch key.tag { case blockchain.session.state.value, blockchain.db.collection.id: return state.binding(event) case blockchain.session.configuration.value: return remoteConfiguration.binding(event) default: return .constant(nil) } } } extension Session.RemoteConfiguration { func binding(_ event: Tag.Event) -> Binding<Any?> { Binding( get: { [unowned self] in try? get(event) }, set: { [unowned self] newValue in override(event, with: newValue as Any) } ) } } extension Session.State { func binding(_ event: Tag.Event) -> Binding<Any?> { Binding( get: { [unowned self] in try? get(event) }, set: { [unowned self] newValue in set(event, to: newValue as Any) } ) } } extension Binding where Value == Any? { func decode<T: Decodable>( as type: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) -> Binding<T?> { Binding<T?>( get: { try? wrappedValue.decode(T.self, using: decoder) }, set: { newValue in wrappedValue = newValue } ) } var isYes: Binding<Bool> { Binding<Bool>( get: { (try? wrappedValue.decode(Bool.self)) == true }, set: { newValue in wrappedValue = newValue } ) } }
lgpl-3.0
e63fe8b50809a7bb2b400b6da3c913c6
33.87965
141
0.443225
5.534722
false
false
false
false
inacioferrarini/glasgow
Example/Tests/CoreData/Stack/CoreDataStackSpec.swift
1
4088
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData import Quick import Nimble @testable import Glasgow class CoreDataStackSpec: QuickSpec { // swiftlint:disable function_body_length override func spec() { describe("Core Data Stack") { let modelFileName = "GlasgowTests" let databaseFileName = "GlasgowTestsDB" let bundle = Bundle(for: type(of: self)) var stack: CoreDataStack? context("Initialization") { it("must create object") { // When stack = CoreDataStack(modelFileName: modelFileName, databaseFileName: databaseFileName, bundle: bundle) // Then expect(stack).toNot(beNil()) } it("Convenience init must create object") { // When stack = CoreDataStack(modelFileName: modelFileName, databaseFileName: databaseFileName) // Then expect(stack).toNot(beNil()) } } context("save method") { beforeEach { // Given stack = CoreDataStack(modelFileName: modelFileName, databaseFileName: databaseFileName, bundle: bundle) } it("must not crash") { // When var exceptionWasThrown = false var doCompleted = false do { if let context = stack?.managedObjectContext { _ = TestEntity.testEntity(with: "test value", group: "group", in: context) } try stack?.saveContext() doCompleted = true } catch { exceptionWasThrown = true } // Then expect(doCompleted).to(beTruthy()) expect(exceptionWasThrown).to(beFalsy()) } it("when exception happens, must throws exception") { // When var exceptionWasThrown = false var doCompleted = false do { if let context = stack?.managedObjectContext { _ = TestEntity.testEntity(with: nil, group: "group", in: context) } try stack?.saveContext() doCompleted = true } catch { exceptionWasThrown = true } // Then expect(doCompleted).to(beFalsy()) expect(exceptionWasThrown).to(beTruthy()) } } } } // swiftlint:enable body_length }
mit
fbfa0c55a5237f97dbaa1b74020e6a79
33.635593
123
0.532175
5.575716
false
true
false
false
jovito-royeca/Cineko
Cineko/NYTimesReviewManager.swift
1
2425
// // NYTimesReviewManager.swift // Cineko // // Created by Jovit Royeca on 01/05/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import CoreData enum NYTimesReviewError: ErrorType { case NoAPIKey } struct NYTimesReviewConstants { static let APIKey = "api-key" static let APIURL = "https://api.nytimes.com/svc/movies/v2" struct Reviews { struct Search { static let Path = "/reviews/search.json" } } } class NYTimesReviewManager: NSObject { // MARK: Variables private var apiKey:String? // MARK: Setup func setup(apiKey: String) { self.apiKey = apiKey } func movieReviews(movieID: NSNumber, completion: (error: NSError?) -> Void?) throws { guard (apiKey) != nil else { throw NYTimesReviewError.NoAPIKey } var movie:Movie? let fetchRequest = NSFetchRequest(entityName: "Movie") fetchRequest.predicate = NSPredicate(format: "movieID == %@", movieID) do { movie = try CoreDataManager.sharedInstance.privateContext.executeFetchRequest(fetchRequest).first as? Movie } catch {} let httpMethod:HTTPMethod = .Get let urlString = "\(NYTimesReviewConstants.APIURL)\(NYTimesReviewConstants.Reviews.Search.Path)" let parameters = [NYTimesReviewConstants.APIKey: apiKey!, "query": "'\(movie!.title!)'"] let success = { (results: AnyObject!) in if let dict = results as? [String: AnyObject] { if let json = dict["results"] as? [[String: AnyObject]] { for review in json { let m = ObjectManager.sharedInstance.findOrCreateReview(review) m.movie = movie } } } CoreDataManager.sharedInstance.savePrivateContext() completion(error: nil) } let failure = { (error: NSError?) -> Void in completion(error: error) } NetworkManager.sharedInstance.exec(httpMethod, urlString: urlString, headers: nil, parameters: parameters, values: nil, body: nil, dataOffset: 0, isJSON: true, success: success, failure: failure) } // MARK: Shared Instance static let sharedInstance = NYTimesReviewManager() }
apache-2.0
ecf26a631e6d210f5204ffaf371964c7
30.894737
203
0.585396
4.715953
false
false
false
false
xxxAIRINxxx/Cmg
Sources/Vector.swift
1
2249
// // Vector.swift // Cmg // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit import CoreImage public protocol Vectorable { var ciVector: CIVector { get } } public struct Vector2: Vectorable { public var x: CGFloat public var y: CGFloat public init(size: CGSize) { self.x = size.width self.y = size.height } public init(x: CGFloat, y: CGFloat) { self.x = x self.y = y } public init(values: [CGFloat]) { self.x = values.count >= 2 ? values[0] : 0.0 self.y = values.count >= 2 ? values[1] : 0.0 } public var ciVector: CIVector { return CIVector(x: x, y: y) } } public struct Vector4: Vectorable { public var x: CGFloat public var y: CGFloat public var z: CGFloat public var w: CGFloat public init(x: CGFloat, y: CGFloat, z: CGFloat, w: CGFloat) { self.x = x self.y = y self.z = z self.w = z } public init(size: CGSize) { self.x = 0.0 self.y = 0.0 self.z = size.width self.w = size.height } public init(rect: CGRect) { self.x = rect.origin.x self.y = rect.origin.y self.z = rect.size.width self.w = rect.size.height } public init(values: [CGFloat]) { self.x = values.count >= 4 ? values[0] : 0.0 self.y = values.count >= 4 ? values[1] : 0.0 self.z = values.count >= 4 ? values[2] : 0.0 self.w = values.count >= 4 ? values[3] : 0.0 } public var ciVector: CIVector { return CIVector(x: x, y: y, z: z, w: w) } } public struct VectorAny: Vectorable { public let count: Int public fileprivate(set) var values: [CGFloat] = [] public init(count: Int, values: [CGFloat]) { self.count = count for index in 0..<count { if values.count <= index { self.values.append(0.0) } else { self.values.append(values[index]) } } } public var ciVector: CIVector { return CIVector(values: self.values, count: self.count) } }
mit
75fc0a55ae92d0257d85524a1de53e83
22.416667
77
0.538701
3.529042
false
false
false
false
aranasaurus/flingInvaders
flingInvaders/Laser.swift
1
1250
// // Laser.swift // flingInvaders // // Created by Ryan Arana on 7/13/14. // Copyright (c) 2014 aranasaurus.com. All rights reserved. // import SpriteKit class Laser: SKSpriteNode { var velocity: CGPoint var active = false init(velocity:CGPoint, imageNamed:String) { self.velocity = velocity let texture = SKTexture(imageNamed: imageNamed) super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) self.xScale = 0.66 self.yScale = 0.66 self.configurePhysicsBody() } func configurePhysicsBody() { let pb = SKPhysicsBody(rectangleOfSize: self.frame.size) pb.dynamic = false pb.categoryBitMask = ColliderType.Laser.toRaw() pb.contactTestBitMask = ColliderType.Meteor.toRaw() | ColliderType.Wall.toRaw() pb.collisionBitMask = ColliderType.Meteor.toRaw() | ColliderType.Wall.toRaw() self.physicsBody = pb } func update(updateTime:NSTimeInterval) { //NSLog("update: \(updateTime)") //NSLog("update: \(velocity.x * updateTime), \(velocity.y * updateTime)") self.position = CGPoint(x: position.x + (velocity.x * updateTime), y: position.y + (velocity.y * updateTime)) } }
apache-2.0
2818174297be4abb1904668721e5372f
30.25
117
0.6504
4.098361
false
false
false
false
geowarsong/UG-Lemondo
Simple-Calculator/Simple Calculator/Simple Calculator/Controller/MainScreen.swift
1
2110
// // MainScreen.swift // Simple Calculator // // Created by C0mrade on 5/24/17. // Copyright © 2017 C0mrade. All rights reserved. // import UIKit class MainScreen: UIViewController { // MARK: - IBOutlets @IBOutlet weak var lblMain: UILabel! // MARK: - Properties var isFirstDigit = true var calculatedNumOne = 0.0 var arithmetic = 0 // MARK: - View LifeCycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // MARK: - IBActions @IBAction func equalButtonTapped(_ sender: UIButton) { if !lblMain.text!.isEmpty { let number = getCalculatedValue(num0: arithmetic, num1: calculatedNumOne, num2: Double(lblMain.text!)!) lblMain.text = "\(number)" } else { print("Could not make math operation because text is empty") } } @IBAction func clearAllTapped(_ sender: UIButton) { lblMain.text = "" // will clear label } @IBAction func arithmeticButtonTapped(_ sender: UIButton) { if !lblMain.text!.isEmpty { arithmetic = sender.tag // will store math operator calculatedNumOne = Double(lblMain.text!)! // cast string to double lblMain.text = "" } else { print("Could not select math operator because text is empty") } } @IBAction func calculatorNumberTapped(_ sender: UIButton) { // if user clicks on the button, first it will add number as main, // following numbers will be concatinated from right to left lblMain.text = isFirstDigit ? "\(sender.tag)" : lblMain.text! + "\(sender.tag)" } func getCalculatedValue (num0 op: Int, num1: Double, num2: Double) -> Double { switch op { case 0: return num1 + num2 case 1: return num1 - num2 case 2: return num1 / num2 case 3: return num1 * num2 default: break } return 0.0 } }
apache-2.0
99b34d26e59047ed6b58f03f4aae85d9
27.5
115
0.57468
4.348454
false
false
false
false
appsquickly/Typhoon-Swift-Example
PocketForecast/Model/Temperature.swift
1
3768
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public enum TemperatureUnits : Int { case Celsius case Fahrenheit } public class Temperature : NSObject, NSCoding { private var _temperatureInFahrenheit : NSDecimalNumber private var _shortFormatter : NumberFormatter private var _longFormatter : NumberFormatter public class func defaultUnits() -> TemperatureUnits { return TemperatureUnits(rawValue: UserDefaults.standard.integer(forKey: "pf.default.units"))! } public class func setDefaultUnits(units : TemperatureUnits) { UserDefaults.standard.set(units.rawValue, forKey: "pf.default.units") } public init(temperatureInFahrenheit : NSDecimalNumber) { _temperatureInFahrenheit = temperatureInFahrenheit; _shortFormatter = NumberFormatter() _shortFormatter.minimumFractionDigits = 0; _shortFormatter.maximumFractionDigits = 0; _longFormatter = NumberFormatter() _longFormatter.minimumFractionDigits = 0 _longFormatter.maximumFractionDigits = 1 } public convenience init(fahrenheitString : String) { self.init(temperatureInFahrenheit:NSDecimalNumber(string: fahrenheitString)) } public convenience init(celciusString : String) { let fahrenheit = NSDecimalNumber(string: celciusString) .multiplying(by: 9) .dividing(by: 5) .adding(32) self.init(temperatureInFahrenheit : fahrenheit) } public required convenience init?(coder : NSCoder) { let temp = coder.decodeObject(forKey: "temperatureInFahrenheit") as! NSDecimalNumber self.init(temperatureInFahrenheit: temp) } public func inFahrenheit() -> NSNumber { return _temperatureInFahrenheit; } public func inCelcius() -> NSNumber { return _temperatureInFahrenheit .subtracting(32) .multiplying(by: 5) .dividing(by: 9) } public func asShortStringInDefaultUnits() -> String { if Temperature.defaultUnits() == TemperatureUnits.Celsius { return self.asShortStringInCelsius() } return self.asShortStringInFahrenheit() } public func asLongStringInDefualtUnits() -> String { if Temperature.defaultUnits() == TemperatureUnits.Celsius { return self.asLongStringInCelsius() } return self.asLongStringInFahrenheit() } public func asShortStringInFahrenheit() -> String { return _shortFormatter.string(from: self.inFahrenheit())! + "°" } public func asLongStringInFahrenheit() -> String { return _longFormatter.string(from: self.inFahrenheit())! + "°" } public func asShortStringInCelsius() -> String { return _shortFormatter.string(from: self.inCelcius())! + "°" } public func asLongStringInCelsius() -> String { return _longFormatter.string(from: self.inCelcius())! + "°" } public override var description: String { return "Temperature: \(self.asShortStringInFahrenheit())f [\(self.asShortStringInCelsius()) celsius]" } public func encode(with coder: NSCoder) { coder.encode(_temperatureInFahrenheit, forKey:"temperatureInFahrenheit"); } }
apache-2.0
0f86191038d6afc413de029da951e1b4
30.898305
109
0.629118
5.11413
false
false
false
false
openbuild-sheffield/jolt
Sources/OpenbuildExtensionPerfect/model.ResponseModel422.swift
1
3377
import PerfectLib public class ResponseModel422: JSONConvertibleObject, DocumentationProtocol { static let registerName = "responseModel422" public var error: Bool = true public var message: String = "422 Unprocessable Entity. The request was well-formed but was unable to be followed due to semantic errors." public var validated: [String: Any?] = [:] public var messages: [String: Any] = [:] public var descriptions = [ "error": "An error has occurred, will always be true", "message": "Will always be '422 Unprocessable Entity. The request was well-formed but was unable to be followed due to semantic errors.'", "validated": "Key pair description of validated data.", "messages": "Key pair of description messages." ] public init(validation: RequestValidation, messages: [String : Any]) { self.validated = validation.validated self.messages = messages } public override func setJSONValues(_ values: [String : Any]) { self.error = getJSONValue(named: "error", from: values, defaultValue: true) self.message = getJSONValue(named: "message", from: values, defaultValue: "422 Unprocessable Entity. The request was well-formed but was unable to be followed due to semantic errors.") self.validated = getJSONValue(named: "validated", from: values, defaultValue: [:]) self.messages = getJSONValue(named: "messages", from: values, defaultValue: [:]) } public override func getJSONValues() -> [String : Any] { return [ JSONDecoding.objectIdentifierKey:ResponseModel422.registerName, "error": error, "message": message, "validated": validated, "messages":messages ] } public static func describeRAML() -> [String] { if let docs = ResponseDocumentation.getRAML(key: "ResponseModel422") { return docs } else { var v = RequestValidation() v.addValidated(key: "model_id", value: 1) v.addValidated(key: "model_attribute", value: "fubar") let m: [String: Any] = [ "updated": false, "errors": ["num_rows": "Failed to update correct number of rows 0"], "entities": [ "old": [ "model_id": 1, "model_attribute": "fubar" ], "attempted": [ "model_id": 1, "model_attribute": "fubar" ] ] ] let model = ResponseModel422(validation: v, messages: m) let aMirror = Mirror(reflecting: model) let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions) ResponseDocumentation.setRAML(key: "ResponseModel422", lines: docs) return docs } } } extension ResponseModel422: CustomReflectable { open var customMirror: Mirror { return Mirror( self, children: [ "error": self.error, "message": self.message, "validated": self.validated, "messages": self.messages ], displayStyle: Mirror.DisplayStyle.class ) } }
gpl-2.0
0079de22d7b8a4f14030783d45af8a45
33.824742
192
0.576547
4.796875
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/SectionEditorInputViewsController.swift
1
12895
protocol SectionEditorInputViewsSource: AnyObject { var inputViewController: UIInputViewController? { get } } protocol SectionEditorInputViewsControllerDelegate: AnyObject { func sectionEditorInputViewsControllerDidTapMediaInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) func sectionEditorInputViewsControllerDidTapLinkInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) } class SectionEditorInputViewsController: NSObject, SectionEditorInputViewsSource, Themeable { let webView: SectionEditorWebView let messagingController: SectionEditorWebViewMessagingController let textFormattingInputViewController = TextFormattingInputViewController.wmf_viewControllerFromStoryboardNamed("TextFormatting") let defaultEditToolbarView = DefaultEditToolbarView.wmf_viewFromClassNib() let contextualHighlightEditToolbarView = ContextualHighlightEditToolbarView.wmf_viewFromClassNib() let findAndReplaceView: FindAndReplaceKeyboardBar? = FindAndReplaceKeyboardBar.wmf_viewFromClassNib() private var isRangeSelected = false weak var delegate: SectionEditorInputViewsControllerDelegate? init(webView: SectionEditorWebView, messagingController: SectionEditorWebViewMessagingController, findAndReplaceDisplayDelegate: FindAndReplaceKeyboardBarDisplayDelegate) { self.webView = webView self.messagingController = messagingController super.init() textFormattingInputViewController.delegate = self defaultEditToolbarView?.delegate = self contextualHighlightEditToolbarView?.delegate = self findAndReplaceView?.delegate = self findAndReplaceView?.displayDelegate = findAndReplaceDisplayDelegate findAndReplaceView?.isShowingReplace = true messagingController.findInPageDelegate = self inputViewType = nil inputAccessoryViewType = .default } func textSelectionDidChange(isRangeSelected: Bool) { self.isRangeSelected = isRangeSelected if inputViewType == nil { if inputAccessoryViewType == .findInPage { messagingController.clearSearch() findAndReplaceView?.reset() findAndReplaceView?.hide() } inputAccessoryViewType = isRangeSelected ? .highlight : .default } defaultEditToolbarView?.enableAllButtons() contextualHighlightEditToolbarView?.enableAllButtons() defaultEditToolbarView?.deselectAllButtons() contextualHighlightEditToolbarView?.deselectAllButtons() textFormattingInputViewController.textSelectionDidChange(isRangeSelected: isRangeSelected) } func disableButton(button: SectionEditorButton) { defaultEditToolbarView?.disableButton(button) contextualHighlightEditToolbarView?.disableButton(button) textFormattingInputViewController.disableButton(button: button) } func buttonSelectionDidChange(button: SectionEditorButton) { defaultEditToolbarView?.selectButton(button) contextualHighlightEditToolbarView?.selectButton(button) textFormattingInputViewController.buttonSelectionDidChange(button: button) } func updateReplaceType(type: ReplaceType) { findAndReplaceView?.replaceType = type } var inputViewType: TextFormattingInputViewController.InputViewType? var suppressMenus: Bool = false { didSet { if suppressMenus { inputAccessoryViewType = nil } } } var inputViewController: UIInputViewController? { guard let inputViewType = inputViewType, !suppressMenus else { return nil } textFormattingInputViewController.inputViewType = inputViewType return textFormattingInputViewController } enum InputAccessoryViewType { case `default` case highlight case findInPage } private var previousInputAccessoryViewType: InputAccessoryViewType? private(set) var inputAccessoryViewType: InputAccessoryViewType? { didSet { previousInputAccessoryViewType = oldValue webView.setInputAccessoryView(inputAccessoryView) } } private var inputAccessoryView: UIView? { guard let inputAccessoryViewType = inputAccessoryViewType, !suppressMenus else { return nil } let maybeView: Any? switch inputAccessoryViewType { case .default: maybeView = defaultEditToolbarView case .highlight: maybeView = contextualHighlightEditToolbarView case .findInPage: maybeView = findAndReplaceView } guard let inputAccessoryView = maybeView as? UIView else { assertionFailure("Couldn't get preferredInputAccessoryView") return nil } return inputAccessoryView } func apply(theme: Theme) { textFormattingInputViewController.apply(theme: theme) defaultEditToolbarView?.apply(theme: theme) contextualHighlightEditToolbarView?.apply(theme: theme) findAndReplaceView?.apply(theme: theme) } private var findInPageFocusedMatchID: String? func didTransitionToNewCollection() { scrollToFindInPageMatchWithID(findInPageFocusedMatchID) } func resetFormattingAndStyleSubmenus() { guard inputViewType != nil else { return } inputViewType = nil inputAccessoryViewType = .default } func closeFindAndReplace() { guard let keyboardBar = findAndReplaceView else { return } messagingController.clearSearch() keyboardBar.reset() keyboardBar.hide() inputAccessoryViewType = previousInputAccessoryViewType if keyboardBar.isVisible { messagingController.selectLastFocusedMatch() messagingController.focusWithoutScroll() } } } // MARK: TextFormattingDelegate extension SectionEditorInputViewsController: TextFormattingDelegate { func textFormattingProvidingDidTapMediaInsert() { delegate?.sectionEditorInputViewsControllerDidTapMediaInsert(self) } func textFormattingProvidingDidTapTextSize(newSize: TextSizeType) { messagingController.setTextSize(newSize: newSize.rawValue) } func textFormattingProvidingDidTapFindInPage() { inputAccessoryViewType = .findInPage UIView.performWithoutAnimation { findAndReplaceView?.show() } } func textFormattingProvidingDidTapCursorUp() { messagingController.moveCursorUp() } func textFormattingProvidingDidTapCursorDown() { messagingController.moveCursorDown() } func textFormattingProvidingDidTapCursorRight() { messagingController.moveCursorRight() } func textFormattingProvidingDidTapCursorLeft() { messagingController.moveCursorLeft() } func textFormattingProvidingDidTapTextStyleFormatting() { inputViewType = .textStyle inputAccessoryViewType = nil } func textFormattingProvidingDidTapTextFormatting() { inputViewType = .textFormatting inputAccessoryViewType = nil } func textFormattingProvidingDidTapClose() { inputViewType = nil inputAccessoryViewType = isRangeSelected ? .highlight : .default } func textFormattingProvidingDidTapHeading(depth: Int) { messagingController.setHeadingSelection(depth: depth) } func textFormattingProvidingDidTapBold() { messagingController.toggleBoldSelection() } func textFormattingProvidingDidTapItalics() { messagingController.toggleItalicSelection() } func textFormattingProvidingDidTapUnderline() { messagingController.toggleUnderline() } func textFormattingProvidingDidTapStrikethrough() { messagingController.toggleStrikethrough() } func textFormattingProvidingDidTapReference() { messagingController.toggleReferenceSelection() } func textFormattingProvidingDidTapTemplate() { messagingController.toggleTemplateSelection() } func textFormattingProvidingDidTapComment() { messagingController.toggleComment() } func textFormattingProvidingDidTapLink() { delegate?.sectionEditorInputViewsControllerDidTapLinkInsert(self) } func textFormattingProvidingDidTapIncreaseIndent() { messagingController.increaseIndentDepth() } func textFormattingProvidingDidTapDecreaseIndent() { messagingController.decreaseIndentDepth() } func textFormattingProvidingDidTapOrderedList() { messagingController.toggleOrderedListSelection() } func textFormattingProvidingDidTapUnorderedList() { messagingController.toggleUnorderedListSelection() } func textFormattingProvidingDidTapSuperscript() { messagingController.toggleSuperscript() } func textFormattingProvidingDidTapSubscript() { messagingController.toggleSubscript() } func textFormattingProvidingDidTapClearFormatting() { messagingController.clearFormatting() } } extension SectionEditorInputViewsController: SectionEditorWebViewMessagingControllerFindInPageDelegate { func sectionEditorWebViewMessagingControllerDidReceiveFindInPagesMatchesMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, matchesCount: Int, matchIndex: Int, matchID: String?) { guard inputAccessoryViewType == .findInPage else { return } findAndReplaceView?.updateMatchCounts(index: matchIndex, total: UInt(matchesCount)) scrollToFindInPageMatchWithID(matchID) findInPageFocusedMatchID = matchID } private func scrollToFindInPageMatchWithID(_ matchID: String?) { guard let matchID = matchID else { return } webView.getScrollRectForHtmlElement(withId: matchID) { [weak self] (matchRect) in guard let findAndReplaceView = self?.findAndReplaceView, let webView = self?.webView, let findAndReplaceViewY = findAndReplaceView.window?.convert(.zero, from: findAndReplaceView).y else { return } let matchRectY = matchRect.minY let contentInsetTop = webView.scrollView.contentInset.top let newOffsetY = matchRectY + contentInsetTop - (0.5 * findAndReplaceViewY) + (0.5 * matchRect.height) let centeredOffset = CGPoint(x: webView.scrollView.contentOffset.x, y: newOffsetY) self?.scrollToOffset(centeredOffset, in: webView) } } private func scrollToOffset(_ newOffset: CGPoint, in webView: WKWebView) { guard !newOffset.x.isNaN && !newOffset.y.isNaN && newOffset.x.isFinite && newOffset.y.isFinite else { return } let safeOffset = CGPoint(x: newOffset.x, y: max(0 - webView.scrollView.contentInset.top, newOffset.y)) webView.scrollView.setContentOffset(safeOffset, animated: true) } } extension SectionEditorInputViewsController: FindAndReplaceKeyboardBarDelegate { func keyboardBarDidTapReturn(_ keyboardBar: FindAndReplaceKeyboardBar) { messagingController.findNext() } func keyboardBar(_ keyboardBar: FindAndReplaceKeyboardBar, didChangeSearchTerm searchTerm: String?) { guard let searchTerm = searchTerm else { return } messagingController.find(text: searchTerm) } func keyboardBarDidTapClose(_ keyboardBar: FindAndReplaceKeyboardBar) { // no-op, FindAndReplaceKeyboardBar not showing close button in Editor context } func keyboardBarDidTapClear(_ keyboardBar: FindAndReplaceKeyboardBar) { messagingController.clearSearch() keyboardBar.resetFind() } func keyboardBarDidTapPrevious(_ keyboardBar: FindAndReplaceKeyboardBar) { messagingController.findPrevious() } func keyboardBarDidTapNext(_ keyboardBar: FindAndReplaceKeyboardBar?) { messagingController.findNext() } func keyboardBarDidTapReplace(_ keyboardBar: FindAndReplaceKeyboardBar, replaceText: String, replaceType: ReplaceType) { switch replaceType { case .replaceSingle: messagingController.replaceSingle(text: replaceText) case .replaceAll: messagingController.replaceAll(text: replaceText) } } } #if (TEST) // MARK: Helpers for testing extension SectionEditorInputViewsController { var findAndReplaceViewForTesting: FindAndReplaceKeyboardBar? { return findAndReplaceView } } #endif
mit
c32d5740b2d36fef00d44c0687229ad3
33.386667
223
0.711283
6.020075
false
false
false
false
longitachi/ZLPhotoBrowser
Sources/General/ZLProgressHUD.swift
1
5476
// // ZLProgressHUD.swift // ZLPhotoBrowser // // Created by long on 2020/8/17. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class ZLProgressHUD: UIView { @objc public enum HUDStyle: Int { case light case lightBlur case dark case darkBlur var bgColor: UIColor { switch self { case .light: return .white case .dark: return .darkGray case .lightBlur: return UIColor.white.withAlphaComponent(0.8) case .darkBlur: return UIColor.darkGray.withAlphaComponent(0.8) } } var icon: UIImage? { switch self { case .light, .lightBlur: return .zl.getImage("zl_loading_dark") case .dark, .darkBlur: return .zl.getImage("zl_loading_light") } } var textColor: UIColor { switch self { case .light, .lightBlur: return .black case .dark, .darkBlur: return .white } } var blurEffectStyle: UIBlurEffect.Style? { switch self { case .light, .dark: return nil case .lightBlur: return .extraLight case .darkBlur: return .dark } } } private let style: ZLProgressHUD.HUDStyle private lazy var loadingView = UIImageView(image: style.icon) private var timer: Timer? var timeoutBlock: (() -> Void)? deinit { zl_debugPrint("ZLProgressHUD deinit") cleanTimer() } @objc public init(style: ZLProgressHUD.HUDStyle) { self.style = style super.init(frame: UIScreen.main.bounds) setupUI() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { let view = UIView(frame: CGRect(x: 0, y: 0, width: 135, height: 135)) view.layer.masksToBounds = true view.layer.cornerRadius = 12 view.backgroundColor = style.bgColor view.clipsToBounds = true view.center = center if let effectStyle = style.blurEffectStyle { let effect = UIBlurEffect(style: effectStyle) let effectView = UIVisualEffectView(effect: effect) effectView.frame = view.bounds view.addSubview(effectView) } loadingView.frame = CGRect(x: 135 / 2 - 20, y: 27, width: 40, height: 40) view.addSubview(loadingView) let label = UILabel(frame: CGRect(x: 0, y: 85, width: view.bounds.width, height: 30)) label.textAlignment = .center label.textColor = style.textColor label.font = .zl.font(ofSize: 16) label.text = localLanguageTextValue(.hudLoading) view.addSubview(label) addSubview(view) } private func startAnimation() { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = CGFloat.pi * 2 animation.duration = 0.8 animation.repeatCount = .infinity animation.fillMode = .forwards animation.isRemovedOnCompletion = false loadingView.layer.add(animation, forKey: nil) } @objc public func show(timeout: TimeInterval = 100) { ZLMainAsync { self.startAnimation() UIApplication.shared.keyWindow?.addSubview(self) } if timeout > 0 { cleanTimer() timer = Timer.scheduledTimer(timeInterval: timeout, target: ZLWeakProxy(target: self), selector: #selector(timeout(_:)), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: .default) } } @objc public func hide() { cleanTimer() ZLMainAsync { self.loadingView.layer.removeAllAnimations() self.removeFromSuperview() } } @objc func timeout(_ timer: Timer) { timeoutBlock?() hide() } func cleanTimer() { timer?.invalidate() timer = nil } }
mit
6be6d0e6dc696b1676e4874588f13236
31.023392
163
0.588203
4.724763
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/NotificationsV2/NotificationCell.swift
1
3775
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit import SnapKit struct NotificationCellInfo: CellContext { let identifier: String = NotificationCell.identifier let title: String let date: Date let isRead: Bool let isFirst: Bool let isLast: Bool init(title: String, date: Date, isRead: Bool = true, isFirst: Bool = false, isLast: Bool = false) { self.title = title self.date = date self.isRead = isRead self.isFirst = isFirst self.isLast = isLast } } class NotificationCell: ConfigurableTableViewCell { static let identifier: String = "NotificationCell" private let containerView: UIView = { let view = UIView() view.layer.cornerRadius = Style.Size.s8 view.layer.maskedCorners = [] view.layer.borderColor = Style.Colors.FoundationGrey.withAlphaComponent(0.1).cgColor view.layer.borderWidth = 1.0 return view }() private let titleLabel = UILabel(typography: .bodyRegular) private let dateLabel = UILabel(typography: .footnote, color: Style.Colors.FoundationGrey.withAlphaComponent(0.5)) override func commonInit() { super.commonInit() contentView.addSubview(containerView) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p24) $0.top.bottom.equalToSuperview() } containerView.addSubview(titleLabel) { $0.leading.trailing.top.equalToSuperview().inset(Style.Padding.p12) } containerView.addSubview(dateLabel) { $0.leading.trailing.bottom.equalToSuperview().inset(Style.Padding.p12) $0.top.equalTo(titleLabel.snp.bottom).offset(Style.Padding.p12) } } func configure(context: CellContext) { guard let context = context as? NotificationCellInfo else { return } if context.isRead { containerView.backgroundColor = Style.Colors.white } else { containerView.backgroundColor = Style.Colors.FoundationGreen.withAlphaComponent(0.1) } titleLabel.text = context.title dateLabel.text = "\(context.date.timeAgo() ?? "")" if context.isFirst { containerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] } else if context.isLast { containerView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner] } else { containerView.layer.maskedCorners = [] } } }
bsd-3-clause
87897dec50e73678d2bfd65ecbe60af3
36
116
0.725225
4.514354
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Parametric Equalizer.xcplaygroundpage/Contents.swift
1
2217
//: ## Parametric Equalizer //: #### A parametric equalizer can be used to raise or lower specific frequencies //: ### or frequency bands. Live sound engineers often use parametric equalizers //: ### during a concert in order to keep feedback from occuring, as they allow //: ### much more precise control over the frequency spectrum than other //: ### types of equalizers. Acoustic engineers will also use them to tune a room. //: ### This node may be useful if you're building an app to do audio analysis. import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var parametricEQ = AKParametricEQ(player) parametricEQ.centerFrequency = 4000 // Hz parametricEQ.q = 1.0 // Hz parametricEQ.gain = 10 // dB AudioKit.output = parametricEQ AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Parametric EQ") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: parametricEQ)) addSubview(AKPropertySlider( property: "Center Frequency", format: "%0.3f Hz", value: parametricEQ.centerFrequency, maximum: 22050, color: AKColor.greenColor() ) { sliderValue in parametricEQ.centerFrequency = sliderValue }) addSubview(AKPropertySlider( property: "Q", value: parametricEQ.q, maximum: 20, color: AKColor.redColor() ) { sliderValue in parametricEQ.q = sliderValue }) addSubview(AKPropertySlider( property: "Gain", format: "%0.1f dB", value: parametricEQ.gain, minimum: -20, maximum: 20, color: AKColor.cyanColor() ) { sliderValue in parametricEQ.gain = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
d82e1a82f8e7864cf7ab41197a72f629
31.602941
82
0.650429
4.982022
false
false
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Renderers/ChartXAxisRendererRadarChart.swift
15
2568
// // ChartXAxisRendererRadarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRendererRadarChart: ChartXAxisRenderer { private weak var _chart: RadarChartView! public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil) _chart = chart } public override func renderAxisLabels(context context: CGContext?) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return } let labelFont = _xAxis.labelFont let labelTextColor = _xAxis.labelTextColor let sliceangle = _chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = _chart.factor let center = _chart.centerOffsets let modulus = _xAxis.axisLabelModulus for var i = 0, count = _xAxis.values.count; i < count; i += modulus { let label = _xAxis.values[i] if (label == nil) { continue } let angle = (sliceangle * CGFloat(i) + _chart.rotationAngle) % 360.0 let p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor + _xAxis.labelWidth / 2.0, angle: angle) drawLabel(context: context, label: label!, xIndex: i, x: p.x, y: p.y - _xAxis.labelHeight / 2.0, align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } internal func drawLabel(context context: CGContext?, label: String, xIndex: Int, x: CGFloat, y: CGFloat, align: NSTextAlignment, attributes: [String: NSObject]) { let formattedLabel = _xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), align: align, attributes: attributes) } public override func renderLimitLines(context context: CGContext?) { /// XAxis LimitLines on RadarChart not yet supported. } }
apache-2.0
c1e150214cc10f7ea4c178cb6c0b026a
33.716216
218
0.63162
4.836158
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/NamedMetadata.swift
1
2143
#if SWIFT_PACKAGE import cllvm #endif /// A `NamedMetadata` object represents a module-level metadata value identified /// by a user-provided name. Named metadata is generated lazily when operands /// are attached. public class NamedMetadata { /// The module with which this named metadata is associated. public let module: Module /// The name associated with this named metadata. public let name: String private let llvm: LLVMNamedMDNodeRef init(module: Module, llvm: LLVMNamedMDNodeRef) { self.module = module self.llvm = llvm var nameLen = 0 guard let rawName = LLVMGetNamedMetadataName(llvm, &nameLen) else { fatalError("Could not retrieve name for named MD node?") } self.name = String(cString: rawName) } /// Retrieves the previous alias in the module, if there is one. public func previous() -> NamedMetadata? { guard let previous = LLVMGetPreviousNamedMetadata(llvm) else { return nil } return NamedMetadata(module: self.module, llvm: previous) } /// Retrieves the next alias in the module, if there is one. public func next() -> NamedMetadata? { guard let next = LLVMGetNextNamedMetadata(llvm) else { return nil } return NamedMetadata(module: self.module,llvm: next) } /// Computes the operands of a named metadata node. public var operands: [IRMetadata] { let count = Int(LLVMGetNamedMetadataNumOperands(self.module.llvm, name)) let operands = UnsafeMutablePointer<LLVMValueRef?>.allocate(capacity: count) LLVMGetNamedMetadataOperands(self.module.llvm, name, operands) var ops = [IRMetadata]() ops.reserveCapacity(count) for i in 0..<count { guard let rawOperand = operands[i] else { continue } guard let metadata = LLVMValueAsMetadata(rawOperand) else { continue } ops.append(AnyMetadata(llvm: metadata)) } return ops } /// Appends a metadata node as an operand. public func addOperand(_ op: IRMetadata) { let metaVal = LLVMMetadataAsValue(self.module.context.llvm, op.asMetadata()) LLVMAddNamedMetadataOperand(self.module.llvm, self.name, metaVal) } }
mit
06ac65a1eeee4c890ea3d03f1cd2265a
33.015873
80
0.708353
4.105364
false
false
false
false
latenitesoft/rounder
rounder/main.swift
1
3180
// // main.swift // rounder // // Created by Jorge on 16/07/14. // // The MIT License (MIT) // // Copyright (c) 2014 LateNiteSoft. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension String { subscript (i: Int) -> String { return String(Array(self)[i]) } } func showHeader() { println("Rounder 1.0") println("Copyright (c) LateNiteSoft 2014") println("Make image dimensions multiples of two.") println() } func showUsage() { println("Usage: rounder image-name-regex-pattern [-p]") println("Optional parameter -p makes rounder preserve the original file.") exit(1) } func main() { showHeader() let arguments = Process.arguments var preserveOriginal : Bool = false if arguments.count < 2 || arguments.count > 3 { showUsage() } if arguments.count == 3 { if arguments[2] != "-p" { showUsage() } else { preserveOriginal = true } } let currentPath = NSFileManager.defaultManager().currentDirectoryPath println("Base directory is \(currentPath)") var error : NSError? let regex = NSRegularExpression.regularExpressionWithPattern(arguments[1], options: NSRegularExpressionOptions.CaseInsensitive, error: &error) if error { println("Bad regex: \(error)") exit(2) } let contentsAtPath = NSFileManager.defaultManager().contentsOfDirectoryAtPath(currentPath, error: nil) as [String] for file in contentsAtPath { let filename = file.lastPathComponent if filename.isEmpty || filename[0] == "." { continue } let matches = regex.numberOfMatchesInString(filename, options: NSMatchingOptions(0), range: NSMakeRange(0, filename.utf16Count)) if (matches > 0) { println("\nProcessing file \(file)") let result = ImageProcessor.processImageAtPath("\(currentPath)/\(filename)", overwrite: !preserveOriginal) if (result) { println("Fixed \(filename)") } } } } main()
mit
a2785a41b6cd557666558f2ca6166293
30.485149
146
0.658176
4.472574
false
false
false
false
fancymax/12306ForMac
12306ForMac/Model/OrderDTO.swift
1
3817
// // OrderDTO.swift // 12306ForMac // // Created by fancymax on 16/2/16. // Copyright © 2016年 fancy. All rights reserved. // import Foundation import SwiftyJSON class OrderDTO:NSObject{ var sequence_no: String? var start_train_date_page: String? // var train_code_page: String? var ticket_total_price_page: String? var return_flag: String? var resign_flag: String? var arrive_time_page: String? //tickets[x] var coach_no: String? //车厢号 05 var seat_name: String? //席位号 01A号 var str_ticket_price_page: String? //票价 603.5 var ticket_type_name: String? //票种 成人票 var seat_type_name: String? //席别 一等座 var ticket_status_code: String? //状态 i var ticket_status_name: String? //状态 待支付 var pay_limit_time: String? //限定支付时间 2016-06-14 10:36:28 // stationTrainDTO var station_train_code: String? //G6012 var from_station_name: String? //深圳北 var to_station_name: String? //长沙南 //passengerDTO var passenger_name :String? //小明 //modified //05车厢 var coachName:String{ var name = "" if let no = coach_no { name = no + "车厢" } return name } var startTrainDate:Date? { if start_train_date_page == nil { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" if let date = dateFormatter.date(from: start_train_date_page!) { return date } else { logger.error("trainDateStr2Date dateStr = \(self.start_train_date_page)") return nil } } var startEndStation:String { return "\(from_station_name!)->\(to_station_name!)" } var whereToSeat:String { return "\(coachName) \(seat_name!)" } //¥603.5 var ticketPrice:String{ var name = "" if let price = str_ticket_price_page { name = "¥" + price } return name } var payStatus:String{ var name = "" if let limitTime = pay_limit_time, let status = ticket_status_name, let code = ticket_status_code { if code == "i" { name = "\(status)(请在 \(limitTime) 前支付)" } else { name = "\(status)" } } return name } init(json:JSON,ticketIdx:Int) { sequence_no = json["sequence_no"].string arrive_time_page = json["arrive_time_page"].string start_train_date_page = json["tickets"][ticketIdx]["start_train_date_page"].string coach_no = json["tickets"][ticketIdx]["coach_no"].string seat_name = json["tickets"][ticketIdx]["seat_name"].string str_ticket_price_page = json["tickets"][ticketIdx]["str_ticket_price_page"].string ticket_type_name = json["tickets"][ticketIdx]["ticket_type_name"].string seat_type_name = json["tickets"][ticketIdx]["seat_type_name"].string ticket_status_name = json["tickets"][ticketIdx]["ticket_status_name"].string ticket_status_code = json["tickets"][ticketIdx]["ticket_status_code"].string pay_limit_time = json["tickets"][ticketIdx]["pay_limit_time"].string station_train_code = json["tickets"][ticketIdx]["stationTrainDTO"]["station_train_code"].string from_station_name = json["tickets"][ticketIdx]["stationTrainDTO"]["from_station_name"].string to_station_name = json["tickets"][ticketIdx]["stationTrainDTO"]["to_station_name"].string passenger_name = json["tickets"][ticketIdx]["passengerDTO"]["passenger_name"].string } }
mit
a4c51aff966e32a3f13c188bbd6ab705
30.474576
107
0.580775
3.623415
false
false
false
false
Blackjacx/SHSearchBar
Tests/SHSearchBarTests/SHSearchBarTextFieldSpecs.swift
1
4037
// // SHSearchBarTextFieldSpecs.swift // SHSearchBar // // Created by Stefan Herold on 01/12/2016. // Copyright © 2020 Stefan Herold. All rights reserved. // import UIKit import Quick import Nimble @testable import SHSearchBar final class SHSearchBarTextFieldSpec: QuickSpec { // swiftlint:disable:next function_body_length override func spec() { var config: SHSearchBarConfig! let bounds: CGRect = CGRect(x: 0, y: 0, width: 353, height: 44) let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 38, height: 44)) let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 38, height: 44)) var textField: SHSearchBarTextField! var expectedRect: CGRect! describe("textField") { beforeEach { config = SHSearchBarConfig() textField = SHSearchBarTextField(config: config) textField.leftViewMode = .always textField.rightViewMode = .always } context("with no accessory views") { beforeEach { expectedRect = CGRect(x: config.rasterSize, y: 0, width: bounds.width - config.rasterSize * 2, height: bounds.height) } it("calculates the correct textRectForBounds") { expect(textField.textRect(forBounds: bounds)) == expectedRect } it("calculates the correct editingRectForBounds") { expect(textField.editingRect(forBounds: bounds)) == expectedRect } } context("with left accessory view") { beforeEach { textField.leftView = leftView expectedRect = CGRect(x: leftView.bounds.width, y: 0, width: bounds.width - leftView.bounds.width - config.rasterSize, height: bounds.height) } it("calculates the correct textRectForBounds") { expect(textField.textRect(forBounds: bounds)) == expectedRect } it("calculates the correct editingRectForBounds") { expect(textField.editingRect(forBounds: bounds)) == expectedRect } } context("with right accessory view") { beforeEach { textField.rightView = leftView expectedRect = CGRect(x: config.rasterSize, y: 0, width: bounds.width - rightView.bounds.width - config.rasterSize, height: bounds.height) } it("calculates the correct textRectForBounds") { expect(textField.textRect(forBounds: bounds)) == expectedRect } it("calculates the correct editingRectForBounds") { expect(textField.editingRect(forBounds: bounds)) == expectedRect } } context("with left and right accessory views") { beforeEach { textField.leftView = leftView textField.rightView = rightView expectedRect = CGRect(x: leftView.bounds.width, y: 0, width: bounds.width - leftView.bounds.width - leftView.bounds.width, height: bounds.height) } it("calculates the correct textRectForBounds") { expect(textField.textRect(forBounds: bounds)) == expectedRect } it("calculates the correct editingRectForBounds") { expect(textField.editingRect(forBounds: bounds)) == expectedRect } } } } }
mit
dff55909f1c5ec49518548e95eaae7d2
35.690909
137
0.507185
5.692525
false
true
false
false
zoeyzhong520/SlidingMenu
SlidingMenu/SlidingMenu/Common.swift
1
10716
// // Common.swift // ReadBook // // Created by JOE on 2017/7/12. // Copyright © 2017年 Hongyear Information Technology (Shanghai) Co.,Ltd. All rights reserved. // import UIKit import SnapKit import Kingfisher //MARK: - 设备信息 ///当前app信息 let GetAppInfo = Bundle.main.infoDictionary ///当前app版本号 let GetAppCurrentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ///获取设备系统号 let GetSystemVersion = UIDevice.current.systemVersion ///iPhone设备 let isIphone = (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone ? true : false) ///iPad设备 let isIpad = (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad ? true : false) ///iPhone4设备 let isIphone4s = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) < 568.0 ? true : false) ///iPhone5设备 let isIphone5 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 568.0 ? true : false) ///iPhone6设备 let isIphone6 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 667.0 ? true : false) ///iPhone6Plus设备 let isIphone6P = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 736.0 ? true : false) ///iPhoneSE设备 let isIphoneSE = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 568.0 ? true : false) ///iPhone7设备 let isIphone7 = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 667.0 ? true : false) ///iPhone7P设备 let isIphone7P = (max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) == 736.0 ? true : false) //MARK: - 尺寸信息 ///全屏宽度 let screenWidth = UIScreen.main.bounds.size.width ///全屏高度,不含状态栏高度 let screenHeight = UIScreen.main.bounds.size.height ///tabbar切换视图控制器高度 let tabbarHeight = 49.0 ///搜索视图高度 let searchBarHeight = 45.0 ///状态栏高度 let statusBarHeight = 20.0 ///导航栏高度 let navigationBarHeight = 44.0 ///通过方法获取屏幕的宽 func zzj_GetScreenWidth() -> CGFloat { return UIScreen.main.bounds.size.width } ///通过方法获取屏幕的高 func zzj_GetScreenHeight() -> CGFloat { return UIScreen.main.bounds.size.height } //MARK: - 时间格式 enum TimeFormat:String { case format_default = "yyyy-MM-dd HH:mm:ss" case format_yyMdHm = "yy-MM-dd HH:mm" case format_yyyyMdHm = "yyyy-MM-dd HH:mm" case format_yMd = "yyyy-MM-dd" case format_MdHms = "MM-dd HH:mm:ss" case format_MdHm = "MM-dd HH:mm" case format_Hms = "HH:mm:ss" case format_Hm = "HH:mm" case format_Md = "MM-dd" case format_yyMd = "yy-MM-dd" case format_YYMMdd = "yyyyMMdd" case format_yyyyMdHms = "yyyyMMddHHmmss" case format_yyyyMdHmsS = "yyyy-MM-dd HH:mm:ss.SSS" case format_yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS" case format_yMdWithSlash = "yyyy/MM/dd" case format_yM = "yyyy-MM" case format_yMdChangeSeparator = "yyyy.MM.dd" } //MARK: - 刷新格式 enum RefreshFormat { case tableView case collectionView } //MARK: - 常用字体 ///自适应字体大小 var fontSizeScale:(CGFloat) -> CGFloat = {size in let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.fontSizeScale(scale: size) } ///系统普通字体 var zzj_SystemFontWithSize:(CGFloat) -> UIFont = {size in return UIFont.systemFont(ofSize: fontSizeScale(size)) } ///系统加粗字体 var zzj_BoldFontWithSize:(CGFloat) -> UIFont = {size in return UIFont.boldSystemFont(ofSize: fontSizeScale(size)) } ///仅用于标题栏上,大标题字号 let navFont = zzj_SystemFontWithSize(18) ///标题字号 let titleFont = zzj_SystemFontWithSize(18) ///正文字号 let bodyFont = zzj_SystemFontWithSize(16) ///辅助字号 let assistFont = zzj_SystemFontWithSize(14) //MARK: - 常用颜色 ///根据RGBA生成颜色(格式为:22,22,22,0.5) var RGBAColor:(CGFloat, CGFloat, CGFloat, CGFloat) -> UIColor = {red, green, blue, alpha in return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: alpha) } ///根据RGB生成颜色(格式为:22,22,22) var RGB:(CGFloat, CGFloat, CGFloat) -> UIColor = {red, green, blue in return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1.0) } ///根据色值生成颜色(无透明度)(格式为0xffffff) var zzj_ColorWithHex:(NSInteger) -> UIColor = {hex in let red = ((CGFloat)((hex & 0xFF0000) >> 16)) / 255.0 let green = ((CGFloat)((hex & 0xFF00) >> 8)) / 255.0 let blue = ((CGFloat)((hex & 0xFF))) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } ///输入框提示语的颜色 let placeHolderTipColor = zzj_ColorWithHex(0xafafaf) ///三大色调 let essentialColor = zzj_ColorWithHex(0x46a0f0)//蓝色 let assistOrangeColor = zzj_ColorWithHex(0xff8c28)//橙色 let assistGreenColor = zzj_ColorWithHex(0x5abe00)//绿色 /// 导航栏背景色 let zzj_NavigationBarBackgroundColor = RGB(58, 139, 255) /// 书本详情导航栏背景色 let zzj_BookDetailNavigationBarBackgroundColor = RGB(22, 17, 66) /// shadowOpacity let zzj_ShadowOpacity:Float = 0.2 /// shadowColor let zzj_ShadowColor = UIColor.lightGray /// shadowOffset let zzj_ShadowOffset = CGSize(width: 3, height: 3 ) /// cornerRadius let zzj_CornerRadius = fontSizeScale(2) /// shadowRadius let zzj_ShadowRadius = fontSizeScale(4) //MARK: - 常用变量/方法定义 ///打印日志 - parameter message: 日志消息内容 func printLog<T>(message:T) { #if DEBUG print("\(message)") #endif } ///根据图片名称获取图片 let zzj_ImageWithName:(String) -> UIImage? = {imageName in return UIImage(named: imageName) } ///URL let zzj_URLWithString:(String) -> URL? = { urlString in return URL(string: urlString) } ///CGRectZero let zzj_CGRectZero = CGRect(x: 0, y: 0, width: 0, height: 0) //MARK: - 线程队列 ///主线程队列 let zzj_MainThread = DispatchQueue.main ///Global队列 let zzj_GlobalThread = DispatchQueue.global(qos: .default) ///DispatchTime.now() let zzj_DispatchTimeNow = DispatchTime.now() //MARK: - 闭包closure typealias JumpClosure = () -> () //JumpClosure Default typealias IndexPathJumpClosure = (_ indexPath: IndexPath) -> () //JumpClosure with IndexPath typealias IntJumpClosure = (_ subIndex: Int) -> () //JumpClosure with Int typealias NSNumberJumpClosure = (_ subIndex: NSNumber) -> () //JumpClosure with NSNumber typealias CGFloatJumpClosure = (_ height: CGFloat) -> () //JumpClosure with CGFloat typealias RequestSuccessJumpClosure = (_ model: NSObject) -> () typealias RequestFailureJumpClosure = (_ error: NSError) -> () typealias StringJumpClosure = (_ string: String) -> () //JumpClosure with String typealias BoolJumpClosure = (_ bool: Bool) -> () //JumpClosure with Bool typealias IntWithIndexPathJumpClosure = (_ subIndex: Int, _ indexPath: IndexPath) -> () //JumpClosure with Int,IndexPath typealias StringWithStringJumpClosure = (_ string1: String, _ string2: String) -> () //JumpClosure with String,String typealias FloatJumpClosure = (_ float: Float) -> () //JumpClosure with Float typealias IntWithStringWithStringJumpClosure = (_ int: Int, _ string1: String, _ string2: String) -> () //JumpClosure with Int,String,String //MARK: - KeyWindow let zzj_KeyWindow = UIApplication.shared.keyWindow //MARK: - 文件路径 /// tmp目录路径 let zzj_TmpPath = NSTemporaryDirectory() as NSString /// Documents目录路径 let zzj_DocumentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString /// Library/Caches目录路径 let zzj_CachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! as NSString /// Library/Application Support目录路径 let zzj_SupportPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first! as NSString /// 沙盒主目录路径 let zzj_HomePath = NSHomeDirectory() as NSString //MARK: - 网络请求 //Host //let Host = "wap.seedu.me" //let BaseURL = "http://s3.cn-north-1.amazonaws.com.cn/seedu" let Host = "phone.seedu.me" let BaseURL = "http://s3.cn-north-1.amazonaws.com.cn/seedutest" /// UserInfomation var UserIconImageUrl:String? = nil var UserName:String? = nil var UserSid:Int? = nil /// 班级登陆 POST let ClassLoginUrl = "http://\(Host)/class/login" /// 学生列表 GET let StudentsUrl:(String) -> String = { gradeId in return "http://\(Host)/students?gradeId=\(gradeId)" } /// 学生登录 POST let StudentsLoginUrl = "http://\(Host)/student/login" /*以下需要加入HTTPHeader验证信息*/ /// 书架标签 GET let BookshelfTagsUrl = "http://\(Host)/tags" /// 标签书本 GET let BooksUrl = "http://\(Host)/books" let AllBooksUrl = "http://\(Host)/books/all" /// 书本详情 GET let BookDetailUrl:(String) -> String = { bid in return "http://\(Host)/book?bid=\(bid)" } /// 个人详情 GET let PersonInfoUrl = "http://\(Host)/person/info" /// 客观题-获取客观题题目 GET let ObjectiveQuestionsUrl:(String) -> String = { bid in return "http://\(Host)/objects/\(bid)" } /// 主观题-获取主观题以及主观题答案 GET let SubjectiveQuestionsUrl:(String) -> String = { bid in return "http://\(Host)/subjects/\(bid)" } /// 任务-设置阅读,客观,主观完成 state的范围(reading,object,subject) POST let TaskEndingUrl:(String) -> String = { state in return "http://\(Host)/task/\(state)/ending" } /// 任务-主观题单题提交 POST let SubjectiveSubmitUrl = "http://\(Host)/subject" /// 任务列表 GET let MissionUrl = "http://\(Host)/tasks" /// 阅读记录 GET let ReadingRecordUrl = "http://\(Host)/history" /// 收藏列表 GET | POST:收藏,param: bid书本ID | delete:取消收藏,param: {id}:收藏Id int(>0) let MyCollectionUrl = "http://\(Host)/collection" /// 我的积分列表 GET let MyScoreUrl = "http://\(Host)/score" /// 意见反馈 POST let FeedBackUrl = "http://\(Host)/feedback" /// 下载epub let Epub_DownloadUrl = "http://54.223.77.112/epubs/3.epub" /// 任务情况 GET let MissionSituationUrl = "http://\(Host)/class/tasks" /// 阅读计时 POST let BookTimeUrl = "http://\(Host)/book/time" /// 广告链接 GET let BannerUrl = "http://\(Host)/getNews" /// 网络请求错误信息 let zzj_ErrorMessage = "网络请求失败,请重新访问"
mit
09421e3738657a2f25a43ef560511e5a
22.536058
140
0.686753
3.24098
false
false
false
false
wuleijun/SwiftPractice
SwiftPractice/SwiftPractice/UIViewPosition.swift
1
2344
// // UIViewPosition.swift // SwiftPractice // // Created by 吴蕾君 on 16/3/15. // Copyright © 2016年 rayjuneWu. All rights reserved. // import UIKit public extension UIView { var x: CGFloat { get { return self.frame.origin.x } set (newX) { var frame: CGRect = self.frame frame.origin.x = newX self.frame = frame } } var y: CGFloat { get { return self.frame.origin.y } set (newY) { var frame: CGRect = self.frame frame.origin.y = newY self.frame = frame } } var width: CGFloat { get { return self.frame.size.width } set (newWidth) { var frame: CGRect = self.frame frame.size.width = newWidth self.frame = frame } } var height: CGFloat { get { return self.frame.size.height } set (newHeight) { var frame: CGRect = self.frame frame.size.height = newHeight self.frame = frame } } var origin: CGPoint { get { return self.frame.origin } set (newOrigin) { var frame: CGRect = self.frame frame.origin = newOrigin self.frame = frame } } var size: CGSize { get { return self.frame.size } set (newSize) { var frame: CGRect = self.frame frame.size = newSize self.frame = frame } } var bottom: CGFloat { get { return self.y + self.height } set (newBottom) { self.y = newBottom - self.height } } var right: CGFloat { get { return self.x + self.width } set (newRight) { self.x = newRight - self.width } } var centerX: CGFloat { get { return self.center.x } set (newCenterX) { self.center = CGPointMake(newCenterX, self.center.y) } } var centerY: CGFloat { get { return self.center.y } set (newCenterY) { self.center = CGPointMake(self.center.x, newCenterY) } } }
mit
5085c97c4ccee521aa88ff04b08b3aed
21.247619
64
0.463383
4.292279
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/FeatureDetection.swift
1
7777
// // FeatureDetection.swift // Alfredo // // Created by Eric Kunz on 8/20/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation import AVFoundation open class FeatureDetection { /** Detects faces. - returns: An array of detected faces. */ open func detectFacesInImage(_ image: CIImage) -> [CIFaceFeature] { let features = detectFeaturesInImage(image) var faces = [CIFaceFeature]() for feature in features { if let face = feature as? CIFaceFeature { faces.append(face) } } return faces } /** Detects faces. - returns: An array of detected faces. */ open func detectFacesInImage(_ image: UIImage) -> [CIFaceFeature] { return detectFacesInImage(image.ciImage!) } /** Detects faces, rectangles, QR codes, and text. - returns: An array of detected features. */ open func detectFeaturesInImage(_ image: CIImage) -> [CIFeature] { let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyLow, CIDetectorTracking : true]) return detector!.features(in: image) } /** Detects faces, rectangles, QR codes, and text. - returns: An array of detected features. */ open func detectFeaturesInImage(_ image: UIImage) -> [CIFeature] { return detectFeaturesInImage(image.ciImage!) } /** Transforms the frames of CIFeature objects into another frame. Can be used to get feature frames for a camera preview as the device's camera image usually originates differently and is at a different scale than is previewed. If you are using face detection in a CMSampleBufferDelegate method like - captureOutput:didOutputSampleBuffer:fromConnection: , you can get the clean aperture as follows. let description: CMFormatDescriptionRef = CMSampleBufferGetFormatDescription(sampleBuffer) let cleanAperture = CMVideoFormatDescriptionGetCleanAperture(description, Boolean(0)) - parameter features: An Array of CIFeature. - parameter previewLayer: The layer that view frames will be translated to. - parameter cleanAperture: The clean aperture is a rectangle that defines the portion of the encoded pixel dimensions that represents image data valid for display. - parameter mirrored: Is the video from the camera horizontally flipped for the preview. */ open func rectsForFeatures(_ features: [CIFeature], previewLayer: AVCaptureVideoPreviewLayer, cleanAperture: CGRect, mirrored: Bool) -> [CGRect] { var featureRects = [CGRect]() for feature in features { featureRects.append(rectForFeature(feature, previewLayer: previewLayer, cleanAperture: cleanAperture, mirrored: mirrored)) } return featureRects } /** Transforms the frames of CIFeature objects into another frame. Can be used to get feature frames for a camera preview as the device's camera image usually originates differently and is at a different scale than is previewed. If you are using face detection in a CMSampleBufferDelegate method like - captureOutput:didOutputSampleBuffer:fromConnection: , you can get the clean aperture as follows. let description: CMFormatDescriptionRef = CMSampleBufferGetFormatDescription(sampleBuffer) let cleanAperture = CMVideoFormatDescriptionGetCleanAperture(description, Boolean(0)) - parameter feature: A CIFeature. - parameter previewLayer: The layer that view frames will be translated to. - parameter cleanAperture: The clean aperture is a rectangle that defines the portion of the encoded pixel dimensions that represents image data valid for display. - parameter mirrored: Is the video from the camera horizontally flipped for the preview. */ open func rectForFeature(_ feature: CIFeature, previewLayer: AVCaptureVideoPreviewLayer, cleanAperture: CGRect, mirrored: Bool) -> CGRect { return locationOfFaceInView(feature.bounds, gravity: previewLayer.videoGravity, previewFrame: previewLayer.frame, cleanAperture: cleanAperture, mirrored: mirrored) } fileprivate func locationOfFaceInView(_ featureBounds: CGRect, gravity: AVLayerVideoGravity, previewFrame: CGRect, cleanAperture: CGRect, mirrored: Bool) -> CGRect { let parentFrameSize = previewFrame.size let cleanApertureSize = cleanAperture.size // find where the video box is positioned within the preview layer based on the video size and gravity let previewBox = videoPreviewBox(gravity: gravity, frameSize: parentFrameSize, apertureSize: cleanApertureSize) // find the correct position for the square layer within the previewLayer // the feature box originates in the bottom left of the video frame. // (Bottom right if mirroring is turned on) var faceRect = featureBounds // flip preview width and height var temp = faceRect.size.width faceRect.size.width = faceRect.size.height faceRect.size.height = temp temp = faceRect.origin.x faceRect.origin.x = faceRect.origin.y faceRect.origin.y = temp // scale coordinates so they fit in the preview box, which may be scaled let widthScaleBy = previewBox.size.width / cleanApertureSize.height let heightScaleBy = previewBox.size.height / cleanApertureSize.width faceRect.size.width *= widthScaleBy faceRect.size.height *= heightScaleBy faceRect.origin.x *= widthScaleBy faceRect.origin.y *= heightScaleBy if mirrored { faceRect = faceRect.offsetBy(dx: previewBox.origin.x + previewBox.size.width - faceRect.size.width - (faceRect.origin.x * 2), dy: previewBox.origin.y) } else { faceRect = faceRect.offsetBy(dx: previewBox.origin.x, dy: previewBox.origin.y) } return faceRect } fileprivate func videoPreviewBox(gravity: AVLayerVideoGravity, frameSize: CGSize, apertureSize: CGSize) -> CGRect { let apertureRatio = apertureSize.height / apertureSize.width let viewRatio = frameSize.width / frameSize.height var size = CGSize.zero if gravity == AVLayerVideoGravity.resizeAspectFill { if viewRatio > apertureRatio { size.width = frameSize.width size.height = apertureSize.width * (frameSize.width / apertureSize.height) } else { size.width = apertureSize.height * (frameSize.height / apertureSize.width) size.height = frameSize.height } } else if gravity == AVLayerVideoGravity.resizeAspect { if viewRatio > apertureRatio { size.width = apertureSize.height * (frameSize.height / apertureSize.width) size.height = frameSize.height } else { size.width = frameSize.width size.height = apertureSize.width * (frameSize.width / apertureSize.height) } } else if gravity == AVLayerVideoGravity.resize { size.width = frameSize.width size.height = frameSize.height } var videoBox = CGRect.zero videoBox.size = size if size.width < frameSize.width { videoBox.origin.x = (frameSize.width - size.width) / 2 } else { videoBox.origin.x = (size.width - frameSize.width) / 2 } if size.height < frameSize.height { videoBox.origin.y = (frameSize.height - size.height) / 2 } else { videoBox.origin.y = (size.height - frameSize.height) / 2 } return videoBox } }
mit
ad03c07b0afaaa15617555ddba1812b8
40.588235
171
0.680211
4.7624
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/Cells/QuoteMessageCell.swift
1
4274
// // QuoteMessageCell.swift // Rocket.Chat // // Created by Filipe Alvarenga on 17/10/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import RocketChatViewController final class QuoteMessageCell: BaseQuoteMessageCell, SizingCell { static let identifier = String(describing: QuoteMessageCell.self) static let sizingCell: UICollectionViewCell & ChatCell = { guard let cell = QuoteMessageCell.instantiateFromNib() else { return QuoteMessageCell() } return cell }() @IBOutlet weak var avatarContainerView: UIView! { didSet { avatarContainerView.layer.cornerRadius = 4 avatarView.frame = avatarContainerView.bounds avatarContainerView.addSubview(avatarView) } } @IBOutlet weak var messageUsername: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var statusView: UIImageView! @IBOutlet weak var containerView: UIView! { didSet { containerView.layer.borderWidth = 1 } } @IBOutlet weak var purpose: UILabel! @IBOutlet weak var username: UILabel! @IBOutlet weak var text: UILabel! @IBOutlet weak var arrow: UIImageView! @IBOutlet weak var readReceiptButton: UIButton! @IBOutlet weak var avatarWidthConstraint: NSLayoutConstraint! @IBOutlet weak var avatarLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var containerLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var textLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var textTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var containerTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var readReceiptWidthConstraint: NSLayoutConstraint! @IBOutlet weak var readReceiptTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var purposeHeightConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() textHeightConstraint = NSLayoutConstraint( item: text, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 20 ) textHeightConstraint.isActive = true purposeHeightInitialConstant = purposeHeightConstraint.constant avatarLeadingInitialConstant = avatarLeadingConstraint.constant avatarWidthInitialConstant = avatarWidthConstraint.constant containerLeadingInitialConstant = containerLeadingConstraint.constant textLeadingInitialConstant = textLeadingConstraint.constant textTrailingInitialConstant = textTrailingConstraint.constant containerTrailingInitialConstant = containerTrailingConstraint.constant readReceiptWidthInitialConstant = readReceiptWidthConstraint.constant readReceiptTrailingInitialConstant = readReceiptTrailingConstraint.constant let gesture = UITapGestureRecognizer(target: self, action: #selector(didTapContainerView)) gesture.delegate = self containerView.addGestureRecognizer(gesture) insertGesturesIfNeeded(with: username) } override func configure(completeRendering: Bool) { configure(readReceipt: readReceiptButton) configure( with: avatarView, date: date, status: statusView, and: messageUsername, completeRendering: completeRendering ) configure( purpose: purpose, purposeHeightConstraint: purposeHeightConstraint, username: username, text: text, textHeightConstraint: textHeightConstraint, arrow: arrow ) } } extension QuoteMessageCell { override func applyTheme() { super.applyTheme() let theme = self.theme ?? .light containerView.backgroundColor = theme.chatComponentBackground messageUsername.textColor = theme.titleText date.textColor = theme.auxiliaryText purpose.textColor = theme.auxiliaryText username.textColor = theme.bodyText text.textColor = theme.bodyText containerView.layer.borderColor = theme.borderColor.cgColor } }
mit
2915dc1d696e101917d432b4ce57a34b
33.459677
98
0.697402
5.829468
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/API/Requests/Room/RoomFilesRequest.swift
1
1467
// // RoomFilesRequest.swift // Rocket.Chat // // Created by Filipe Alvarenga on 11/04/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import SwiftyJSON import Foundation import RealmSwift fileprivate extension SubscriptionType { var path: String { switch self { case .channel: return "/api/v1/channels.files" case .group: return "/api/v1/groups.files" case .directMessage: return "/api/v1/dm.files" } } } final class RoomFilesRequest: APIRequest { typealias APIResourceType = RoomFilesResource var path: String { return type.path } var query: String? let roomId: String? let type: SubscriptionType init(roomId: String, subscriptionType: SubscriptionType) { self.type = subscriptionType self.roomId = roomId self.query = "roomId=\(roomId)&sort={\"uploadedAt\":-1}" } } final class RoomFilesResource: APIResource { var files: [File]? { let realm = Realm.current return raw?["files"].arrayValue.map { let file = File() file.map($0, realm: realm) return file } } var count: Int? { return raw?["count"].int } var offset: Int? { return raw?["offset"].int } var total: Int? { return raw?["total"].int } var success: Bool { return raw?["success"].bool ?? false } }
mit
97eb7401a5698be53930dcc2781bb12f
20.246377
64
0.581173
4.164773
false
false
false
false
lazytype/FingerTree
FingerTree/TreeView.swift
1
4902
// TreeView.swift // // Copyright (c) 2015-Present, Michael Mitchell // // 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. extension FingerTree { var viewLeft: (Element, FingerTree)? { switch self { case .empty: return nil case let .single(a): return (a, FingerTree.empty) case let .deep(.one(a), deeper, suffix, _): let rest: FingerTree if let (element, deeperRest) = deeper.viewLeft { rest = FingerTree.deep( prefix: element.node!.makeAffix(), deeper: deeperRest, suffix: suffix, deeper.measure <> suffix.measure ) } else { rest = suffix.makeFingerTree() } return (a, rest) case let .deep(prefix, deeper, suffix, _): let (first, rest) = prefix.viewFirst let annotation = rest!.measure <> deeper.measure <> suffix.measure return (first, FingerTree.deep(prefix: rest!, deeper: deeper, suffix: suffix, annotation)) } } var viewRight: (FingerTree, Element)? { switch self { case .empty: return nil case let .single(a): return (FingerTree.empty, a) case let .deep(prefix, deeper, .one(a), _): let rest: FingerTree if let (deeperRest, element) = deeper.viewRight { rest = FingerTree.deep( prefix: prefix, deeper: deeperRest, suffix: element.node!.makeAffix(), prefix.measure <> deeper.measure ) } else { rest = prefix.makeFingerTree() } return (rest, a) case let .deep(prefix, deeper, suffix, _): let (rest, last) = suffix.viewLast let annotation = prefix.measure <> deeper.measure <> rest!.measure return (FingerTree.deep(prefix: prefix, deeper: deeper, suffix: rest!, annotation), last) } } } extension Affix { func makeFingerTree() -> FingerTree<TValue, TAnnotation> { switch self { case let .one(a): return FingerTree.single(a) case let .two(a, b): return FingerTree.deep( prefix: Affix.one(a), deeper: FingerTree.empty, suffix: Affix.one(b), a.measure <> b.measure ) case let .three(a, b, c): return FingerTree.deep( prefix: Affix.two(a, b), deeper: FingerTree.empty, suffix: Affix.one(c), a.measure <> b.measure <> c.measure ) case let .four(a, b, c, d): return FingerTree.deep( prefix: Affix.two(a, b), deeper: FingerTree.empty, suffix: Affix.two(c, d), a.measure <> b.measure <> c.measure <> d.measure ) } } } extension Node { func makeAffix() -> Affix<TValue, TAnnotation> { switch self { case let .branch2(a, b, _): return Affix.two(a, b) case let .branch3(a, b, c, _): return Affix.three(a, b, c) } } } extension FingerTree { static func createDeep( prefix: Affix<TValue, TAnnotation>?, deeper: FingerTree, suffix: Affix<TValue, TAnnotation>? ) -> FingerTree { if prefix == nil && suffix == nil { if let (element, rest) = deeper.viewLeft { return createDeep(prefix: element.node!.makeAffix(), deeper: rest, suffix: nil) } else { return FingerTree.empty } } else if prefix == nil { if let (rest, element) = deeper.viewRight { return createDeep(prefix: element.node!.makeAffix(), deeper: rest, suffix: suffix) } else { return suffix!.makeFingerTree() } } else if suffix == nil { if let (rest, element) = deeper.viewRight { return createDeep(prefix: prefix, deeper: rest, suffix: element.node!.makeAffix()) } else { return prefix!.makeFingerTree() } } else { let annotation = prefix!.measure <> deeper.measure <> suffix!.measure return FingerTree.deep(prefix: prefix!, deeper: deeper, suffix: suffix!, annotation) } } }
mit
a7ef26df4324dd835237b49995812985
31.68
97
0.628111
3.890476
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/Library/QSiriWaveView.swift
1
4002
// // QSiriWaveView.swift // Example // // Created by Ahmad Athaullah on 4/18/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit public class QSiriWaveView: UIView { static let kDefaultFrequency:CGFloat = 1.5 static let kDefaultAmplitude:CGFloat = 1.0 static let kDefaultIdleAmplitude:CGFloat = 0.01 static let kDefaultNumberOfWaves:UInt = 5 static let kDefaultPhaseShift:CGFloat = -0.15 static let kDefaultDensity:CGFloat = 5.0 static let kDefaultPrimaryLineWidth:CGFloat = 3.0 static let kDefaultSecondaryLineWidth:CGFloat = 1.0 public var numberOfWaves:UInt = 1 public var waveColor:UIColor = UIColor.white public var primaryWaveWidth:CGFloat = 1.0 public var secondaryWaveWidth:CGFloat = 1.0 public var idleAmplitude:CGFloat = 1.0 public var frequency:CGFloat = 1.0 public var amplitude:CGFloat = 1.0 public var density:CGFloat = 1.0 public var phaseShift:CGFloat = 1.0 private var phase : CGFloat = 0 override public func draw(_ rect: CGRect) { // Drawing code super.draw(rect) let context = UIGraphicsGetCurrentContext() context?.clear(self.bounds) self.backgroundColor?.set() context?.fill(rect) // draw multiple sinus waves, with equal phases but altered amplitudes, multiplied by a parable function. for i in 0...self.numberOfWaves{ let context = UIGraphicsGetCurrentContext() let strokeLineWidth = (i == 0) ? self.primaryWaveWidth : self.secondaryWaveWidth context?.setLineWidth(strokeLineWidth) let halfHeight = self.bounds.height / 2.0 let width = self.bounds.width let mid = width / 2 let maxAmplitude = halfHeight - (strokeLineWidth * 2) let progress = 1.0 - CGFloat(i / self.numberOfWaves) let normedAmplitude = ((1.5 * progress) - CGFloat(2.0 / CGFloat(self.numberOfWaves))) * self.amplitude let multiplier = min(1.0, (progress / 3.0 * 2.0) + (1.0 / 3.0)) self.waveColor.withAlphaComponent(multiplier * self.waveColor.cgColor.alpha).set() var x = CGFloat(0) while x < (width + self.density) { let scaling:CGFloat = -pow((1.0 / mid * (x - mid)), 2) + 1.0 let y:CGFloat = scaling * maxAmplitude * normedAmplitude * CGFloat(sinf(2.0 * Float(Double.pi) * Float(x / width) * Float(self.frequency) + Float(self.phase))) + halfHeight if x == 0 { context?.move(to: CGPoint(x: x, y: y)) }else{ context?.addLine(to: CGPoint(x: x, y: y)) } x += self.density } context?.strokePath() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } required public override init(frame: CGRect) { super.init(frame: frame) self.setup() } public func setup(){ self.waveColor = UIColor.white self.frequency = QSiriWaveView.kDefaultFrequency self.amplitude = QSiriWaveView.kDefaultAmplitude self.idleAmplitude = QSiriWaveView.kDefaultIdleAmplitude self.numberOfWaves = QSiriWaveView.kDefaultNumberOfWaves self.phaseShift = QSiriWaveView.kDefaultPhaseShift self.density = QSiriWaveView.kDefaultDensity self.primaryWaveWidth = QSiriWaveView.kDefaultPrimaryLineWidth self.secondaryWaveWidth = QSiriWaveView.kDefaultSecondaryLineWidth } public func update(withLevel level:CGFloat){ self.phase += self.phaseShift self.amplitude = fmax(level, self.idleAmplitude) self.setNeedsDisplay() } }
mit
2666a1ffc4ac0ddfc7d5d23ea1bd98ee
36.392523
188
0.602849
4.363141
false
false
false
false
brandons/Swifter
Swifter/Swifter.swift
1
8671
// // Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(iOS) || os(OSX) import Accounts #endif public class Swifter { // MARK: - Types public typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void internal struct CallbackNotification { static let notificationName = "SwifterCallbackNotificationName" static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey" } internal struct SwifterError { static let domain = "SwifterErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } internal struct DataParameters { static let dataKey = "SwifterDataParameterKey" static let fileNameKey = "SwifterDataParameterFilename" } // MARK: - Properties internal(set) var apiURL: NSURL internal(set) var uploadURL: NSURL internal(set) var streamURL: NSURL internal(set) var userStreamURL: NSURL internal(set) var siteStreamURL: NSURL public var client: SwifterClientProtocol // MARK: - Initializers public convenience init(consumerKey: String, consumerSecret: String) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, appOnly: false) } public init(consumerKey: String, consumerSecret: String, appOnly: Bool) { if appOnly { self.client = SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } else { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } #if os(iOS) || os(OSX) public init(account: ACAccount) { self.client = SwifterAccountsClient(account: account) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } #endif deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - JSON Requests internal func jsonRequestWithPath(path: String, baseURL: NSURL, method: String, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: SwifterHTTPRequest.FailureHandler? = nil) -> SwifterHTTPRequest { let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = { data, _, _, response in if downloadProgress == nil { return } var error: NSError? do { let jsonResult = try JSON.parseJSONData(data) downloadProgress?(json: jsonResult, response: response) } catch var error2 as NSError { error = error2 let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) let jsonChunks = jsonString!.componentsSeparatedByString("\r\n") for chunk in jsonChunks { if chunk.utf16.count == 0 { continue } let chunkData = chunk.dataUsingEncoding(NSUTF8StringEncoding) do { let jsonResult = try JSON.parseJSONData(data) if let downloadProgress = downloadProgress { downloadProgress(json: jsonResult, response: response) } } catch var error1 as NSError { error = error1 } catch { fatalError() } } } catch { fatalError() } } let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = { data, response in dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) { var error: NSError? do { let jsonResult = try JSON.parseJSONData(data) dispatch_async(dispatch_get_main_queue()) { if let success = success { success(json: jsonResult, response: response) } } } catch var error1 as NSError { error = error1 dispatch_async(dispatch_get_main_queue()) { if let failure = failure { failure(error: error!) } } } catch { fatalError() } } } if method == "GET" { return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } else { return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } } internal func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "GET", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } internal func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "POST", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } }
mit
56be56ad44eb81b46e1b72aa70229149
43.466667
341
0.643063
4.983333
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/SavedPageSpotlightManager.swift
1
3811
import UIKit import MobileCoreServices import CoreSpotlight import CocoaLumberjackSwift public extension NSURL { @available(iOS 9.0, *) @objc func searchableItemAttributes() -> CSSearchableItemAttributeSet? { guard self.wmf_isWikiResource else { return nil } guard let title = self.wmf_title else { return nil } let components = title.components(separatedBy: " ") let searchableItem = CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String) searchableItem.keywords = ["Wikipedia","Wikimedia","Wiki"] + components searchableItem.title = self.wmf_title searchableItem.displayName = self.wmf_title searchableItem.identifier = NSURL.wmf_desktopURL(for: self as URL)?.absoluteString searchableItem.relatedUniqueIdentifier = NSURL.wmf_desktopURL(for: self as URL)?.absoluteString return searchableItem } } public extension MWKArticle { @available(iOS 9.0, *) @objc func searchableItemAttributes() -> CSSearchableItemAttributeSet { let castURL = url as NSURL let searchableItem = castURL.searchableItemAttributes() ?? CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String) searchableItem.subject = entityDescription searchableItem.contentDescription = summary if let string = imageURL { searchableItem.thumbnailData = ImageController.shared.permanentlyCachedTypedDiskDataForImage(withURL: URL(string: string)).data } return searchableItem } } @available(iOS 9.0, *) public class WMFSavedPageSpotlightManager: NSObject { private let queue = DispatchQueue(label: "org.wikimedia.saved_page_spotlight_manager", qos: DispatchQoS.background, attributes: [], autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.workItem, target: nil) private let dataStore: MWKDataStore @objc var savedPageList: MWKSavedPageList { return dataStore.savedPageList } @objc public required init(dataStore: MWKDataStore) { self.dataStore = dataStore super.init() } @objc public func reindexSavedPages() { self.savedPageList.enumerateItems { (item, stop) in guard let URL = item.url else { return } self.addToIndex(url: URL as NSURL) } } @objc public func addToIndex(url: NSURL) { guard let article = dataStore.existingArticle(with: url as URL), let identifier = NSURL.wmf_desktopURL(for: url as URL)?.absoluteString else { return } queue.async { let searchableItemAttributes = article.searchableItemAttributes() searchableItemAttributes.keywords?.append("Saved") let item = CSSearchableItem(uniqueIdentifier: identifier, domainIdentifier: "org.wikimedia.wikipedia", attributeSet: searchableItemAttributes) item.expirationDate = NSDate.distantFuture CSSearchableIndex.default().indexSearchableItems([item]) { (error) -> Void in if let error = error { DDLogError("Indexing error: \(error.localizedDescription)") } } } } @objc public func removeFromIndex(url: NSURL) { guard let identifier = NSURL.wmf_desktopURL(for: url as URL)?.absoluteString else { return } queue.async { CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: [identifier]) { (error) in if let error = error { DDLogError("Deindexing error: \(error.localizedDescription)") } } } } }
mit
e68763d7dc2cdb3c3926db8fcccdeae1
36.362745
215
0.648911
5.199181
false
false
false
false
frootloops/swift
validation-test/compiler_crashers_2/0123-rdar31164540.swift
4
29695
// RUN: not --crash %target-swift-frontend -parse-stdlib -DBUILDING_OUTSIDE_STDLIB %s -emit-ir // REQUIRES: objc_interop //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if BUILDING_OUTSIDE_STDLIB import Swift internal func _conditionallyUnreachable() -> Never { _conditionallyUnreachable() } extension Array { func _getOwner_native() -> Builtin.NativeObject { fatalError() } } #endif @_transparent internal func _abstract( methodName: StaticString = #function, file: StaticString = #file, line: UInt = #line ) -> Never { #if INTERNAL_CHECKS_ENABLED _fatalErrorMessage("abstract method", methodName, file: file, line: line, flags: _fatalErrorFlags()) #else _conditionallyUnreachable() #endif } // MARK: Type-erased abstract base classes public class AnyKeyPath: Hashable { public func appending<Value, AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> AnyKeyPath? { _abstract() } public class var rootType: Any.Type { _abstract() } public class var valueType: Any.Type { _abstract() } final public var hashValue: Int { var hash = 0 withBuffer { var buffer = $0 while true { let (component, type) = buffer.next() hash ^= _mixInt(component.value.hashValue) if let type = type { hash ^= _mixInt(unsafeBitCast(type, to: Int.self)) } else { break } } } return hash } public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool { // Fast-path identical objects if a === b { return true } // Short-circuit differently-typed key paths if type(of: a) != type(of: b) { return false } return a.withBuffer { var aBuffer = $0 return b.withBuffer { var bBuffer = $0 // Two equivalent key paths should have the same reference prefix if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix { return false } while true { let (aComponent, aType) = aBuffer.next() let (bComponent, bType) = bBuffer.next() if aComponent.header.endOfReferencePrefix != bComponent.header.endOfReferencePrefix || aComponent.value != bComponent.value || aType != bType { return false } if aType == nil { return true } } } } } // MARK: Implementation details // Prevent normal initialization. We use tail allocation via // allocWithTailElems(). internal init() { _sanityCheckFailure("use _create(...)") } public // @testable static func _create( capacityInBytes bytes: Int, initializedBy body: (UnsafeMutableRawBufferPointer) -> Void ) -> Self { _sanityCheck(bytes > 0 && bytes % 4 == 0, "capacity must be multiple of 4 bytes") let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue, Int32.self) let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result, Int32.self)) body(UnsafeMutableRawBufferPointer(start: base, count: bytes)) return result } func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T { defer { _fixLifetime(self) } let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self)) return try f(KeyPathBuffer(base: base)) } } public class PartialKeyPath<Root>: AnyKeyPath { public override func appending<Value, AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> KeyPath<Root, AppendedValue>? { _abstract() } public func appending<Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue>? { _abstract() } // MARK: Override abstract interfaces @_inlineable public final override class var rootType: Any.Type { return Root.self } } // MARK: Concrete implementations // FIXME(ABI): This protocol is a hack to work around the inability to have // "new" non-overriding overloads in subclasses public protocol _KeyPath { associatedtype _Root associatedtype _Value } public class KeyPath<Root, Value>: PartialKeyPath<Root>, _KeyPath { public typealias _Root = Root public typealias _Value = Value public func appending<AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> KeyPath<Root, AppendedValue> { let resultTy = type(of: self).appendedType(with: type(of: path)) return withBuffer { var rootBuffer = $0 return path.withBuffer { var leafBuffer = $0 // Result buffer has room for both key paths' components, plus the // header, plus space for the middle key path component. let resultSize = rootBuffer.data.count + leafBuffer.data.count + MemoryLayout<KeyPathBuffer.Header>.size + MemoryLayout<Int>.size return resultTy._create(capacityInBytes: resultSize) { var destBuffer = $0 func pushRaw(_ count: Int) { _sanityCheck(destBuffer.count >= count) destBuffer = UnsafeMutableRawBufferPointer( start: destBuffer.baseAddress.unsafelyUnwrapped + count, count: destBuffer.count - count ) } func pushType(_ type: Any.Type) { let intSize = MemoryLayout<Int>.size _sanityCheck(destBuffer.count >= intSize) if intSize == 8 { let words = unsafeBitCast(type, to: (UInt32, UInt32).self) destBuffer.storeBytes(of: words.0, as: UInt32.self) destBuffer.storeBytes(of: words.1, toByteOffset: 4, as: UInt32.self) } else if intSize == 4 { destBuffer.storeBytes(of: type, as: Any.Type.self) } else { _sanityCheckFailure("unsupported architecture") } pushRaw(intSize) } // Save space for the header. let header = KeyPathBuffer.Header( size: resultSize - 4, trivial: rootBuffer.trivial && leafBuffer.trivial, hasReferencePrefix: rootBuffer.hasReferencePrefix || leafBuffer.hasReferencePrefix ) destBuffer.storeBytes(of: header, as: KeyPathBuffer.Header.self) pushRaw(MemoryLayout<KeyPathBuffer.Header>.size) let leafHasReferencePrefix = leafBuffer.hasReferencePrefix let leafIsReferenceWritable = type(of: path).kind == .reference // Clone the root components into the buffer. while true { let (component, type) = rootBuffer.next() let isLast = type == nil // If the leaf appended path has a reference prefix, then the // entire root is part of the reference prefix. let endOfReferencePrefix: Bool if leafHasReferencePrefix { endOfReferencePrefix = false } else if isLast && leafIsReferenceWritable { endOfReferencePrefix = true } else { endOfReferencePrefix = component.header.endOfReferencePrefix } component.clone( into: &destBuffer, endOfReferencePrefix: endOfReferencePrefix ) if let type = type { pushType(type) } else { // Insert our endpoint type between the root and leaf components. pushType(Value.self) break } } // Clone the leaf components into the buffer. while true { let (component, type) = rootBuffer.next() component.clone( into: &destBuffer, endOfReferencePrefix: component.header.endOfReferencePrefix ) if let type = type { pushType(type) } else { break } } _sanityCheck(destBuffer.count == 0, "did not fill entire result buffer") } } } } @_inlineable public final func appending<AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> { return unsafeDowncast( appending(path: path as KeyPath<Value, AppendedValue>), to: ReferenceWritableKeyPath<Root, AppendedValue>.self ) } // MARK: Override optional-returning abstract interfaces @_inlineable public final override func appending<Value2, AppendedValue>( path: KeyPath<Value2, AppendedValue> ) -> KeyPath<Root, AppendedValue>? { if Value2.self == Value.self { return .some(appending( path: unsafeDowncast(path, to: KeyPath<Value, AppendedValue>.self))) } return nil } @_inlineable public final override func appending<Value2, AppendedValue>( path: ReferenceWritableKeyPath<Value2, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue>? { if Value2.self == Value.self { return .some(appending( path: unsafeDowncast(path, to: ReferenceWritableKeyPath<Value, AppendedValue>.self))) } return nil } @_inlineable public final override class var valueType: Any.Type { return Value.self } // MARK: Implementation enum Kind { case readOnly, value, reference } class var kind: Kind { return .readOnly } static func appendedType<AppendedValue>( with t: KeyPath<Value, AppendedValue>.Type ) -> KeyPath<Root, AppendedValue>.Type { let resultKind: Kind switch (self.kind, t.kind) { case (_, .reference): resultKind = .reference case (let x, .value): resultKind = x default: resultKind = .readOnly } switch resultKind { case .readOnly: return KeyPath<Root, AppendedValue>.self case .value: return WritableKeyPath.self case .reference: return ReferenceWritableKeyPath.self } } final func projectReadOnly(from root: Root) -> Value { // TODO: For perf, we could use a local growable buffer instead of Any var curBase: Any = root return withBuffer { var buffer = $0 while true { let (rawComponent, optNextType) = buffer.next() let valueType = optNextType ?? Value.self let isLast = optNextType == nil func project<CurValue>(_ base: CurValue) -> Value? { func project2<NewValue>(_: NewValue.Type) -> Value? { let newBase: NewValue = rawComponent.projectReadOnly(base) if isLast { _sanityCheck(NewValue.self == Value.self, "key path does not terminate in correct type") return unsafeBitCast(newBase, to: Value.self) } else { curBase = newBase return nil } } return _openExistential(valueType, do: project2) } if let result = _openExistential(curBase, do: project) { return result } } } } deinit { withBuffer { $0.destroy() } } } public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> { public final func appending<AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> WritableKeyPath<Root, AppendedValue> { return unsafeDowncast( appending(path: path as KeyPath<Value, AppendedValue>), to: WritableKeyPath<Root, AppendedValue>.self ) } // MARK: Implementation detail override class var kind: Kind { return .value } // `base` is assumed to be undergoing a formal access for the duration of the // call, so must not be mutated by an alias func projectMutableAddress(from base: UnsafePointer<Root>) -> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) { var p = UnsafeRawPointer(base) var type: Any.Type = Root.self var keepAlive: [AnyObject] = [] return withBuffer { var buffer = $0 _sanityCheck(!buffer.hasReferencePrefix, "WritableKeyPath should not have a reference prefix") while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent.projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == UnsafeRawPointer(base), keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(type, do: project) if optNextType == nil { break } type = nextType } // TODO: With coroutines, it would be better to yield here, so that // we don't need the hack of the keepAlive array to manage closing // accesses. let typedPointer = p.assumingMemoryBound(to: Value.self) return (pointer: UnsafeMutablePointer(mutating: typedPointer), owner: keepAlive._getOwner_native()) } } } public class ReferenceWritableKeyPath<Root, Value>: WritableKeyPath<Root, Value> { /* TODO: need a "new" attribute public final func appending<AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> { return unsafeDowncast( appending(path: path as KeyPath<Value, AppendedValue>), to: ReferenceWritableKeyPath<Root, AppendedValue>.self ) }*/ // MARK: Implementation detail final override class var kind: Kind { return .reference } final override func projectMutableAddress(from base: UnsafePointer<Root>) -> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) { // Since we're a ReferenceWritableKeyPath, we know we don't mutate the base in // practice. return projectMutableAddress(from: base.pointee) } final func projectMutableAddress(from origBase: Root) -> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) { var keepAlive: [AnyObject] = [] var address: UnsafeMutablePointer<Value> = withBuffer { var buffer = $0 // Project out the reference prefix. var base: Any = origBase while buffer.hasReferencePrefix { let (rawComponent, optNextType) = buffer.next() _sanityCheck(optNextType != nil, "reference prefix should not go to end of buffer") let nextType = optNextType.unsafelyUnwrapped func project<NewValue>(_: NewValue.Type) -> Any { func project2<CurValue>(_ base: CurValue) -> Any { return rawComponent.projectReadOnly(base) as NewValue } return _openExistential(base, do: project2) } base = _openExistential(nextType, do: project) } // Start formal access to the mutable value, based on the final base // value. func formalMutation<MutationRoot>(_ base: MutationRoot) -> UnsafeMutablePointer<Value> { var base2 = base return withUnsafeBytes(of: &base2) { baseBytes in var p = baseBytes.baseAddress.unsafelyUnwrapped var curType: Any.Type = MutationRoot.self while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent.projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == baseBytes.baseAddress, keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(curType, do: project) if optNextType == nil { break } curType = nextType } let typedPointer = p.assumingMemoryBound(to: Value.self) return UnsafeMutablePointer(mutating: typedPointer) } } return _openExistential(base, do: formalMutation) } return (address, keepAlive._getOwner_native()) } } extension _KeyPath where Self: ReferenceWritableKeyPath<_Root, _Value> { @_inlineable public final func appending<AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> { return unsafeDowncast( appending(path: path as KeyPath<Value, AppendedValue>), to: ReferenceWritableKeyPath<Root, AppendedValue>.self ) } } // MARK: Implementation details enum KeyPathComponentKind { /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct` /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class` /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap } enum KeyPathComponent: Hashable { struct RawAccessor { var rawCode: Builtin.RawPointer var rawContext: Builtin.NativeObject? } /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct`(offset: Int) /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class`(offset: Int) /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool { switch (a, b) { case (.struct(offset: let a), .struct(offset: let b)), (.class (offset: let a), .class (offset: let b)): return a == b case (.optionalChain, .optionalChain), (.optionalForce, .optionalForce), (.optionalWrap, .optionalWrap): return true case (.struct, _), (.class, _), (.optionalChain, _), (.optionalForce, _), (.optionalWrap, _): return false } } var hashValue: Int { var hash: Int = 0 switch self { case .struct(offset: let a): hash ^= _mixInt(0) hash ^= _mixInt(a) case .class(offset: let b): hash ^= _mixInt(1) hash ^= _mixInt(b) case .optionalChain: hash ^= _mixInt(2) case .optionalForce: hash ^= _mixInt(3) case .optionalWrap: hash ^= _mixInt(4) } return hash } } struct RawKeyPathComponent { var header: Header var body: UnsafeRawBufferPointer struct Header { static var payloadBits: Int { return 29 } static var payloadMask: Int { return 0xFFFF_FFFF >> (32 - payloadBits) } var _value: UInt32 var discriminator: Int { return Int(_value) >> Header.payloadBits & 0x3 } var payload: Int { get { return Int(_value) & Header.payloadMask } set { _sanityCheck(newValue & Header.payloadMask == newValue, "payload too big") let shortMask = UInt32(Header.payloadMask) _value = _value & ~shortMask | UInt32(newValue) } } var endOfReferencePrefix: Bool { get { return Int(_value) >> Header.payloadBits & 0x4 != 0 } set { let bit = 0x4 << UInt32(Header.payloadBits) if newValue { _value = _value | bit } else { _value = _value & ~bit } } } var kind: KeyPathComponentKind { switch (discriminator, payload) { case (0, _): return .struct case (2, _): return .class case (3, 0): return .optionalChain case (3, 1): return .optionalWrap case (3, 2): return .optionalForce default: _sanityCheckFailure("invalid header") } } var bodySize: Int { switch kind { case .struct, .class: if payload == Header.payloadMask { return 4 } // overflowed return 0 case .optionalChain, .optionalForce, .optionalWrap: return 0 } } var isTrivial: Bool { switch kind { case .struct, .class, .optionalChain, .optionalForce, .optionalWrap: return true } } } var _structOrClassOffset: Int { _sanityCheck(header.kind == .struct || header.kind == .class, "no offset for this kind") // An offset too large to fit inline is represented by a signal and stored // in the body. if header.payload == Header.payloadMask { // Offset overflowed into body _sanityCheck(body.count >= MemoryLayout<UInt32>.size, "component not big enough") return Int(body.load(as: UInt32.self)) } return header.payload } var value: KeyPathComponent { switch header.kind { case .struct: return .struct(offset: _structOrClassOffset) case .class: return .class(offset: _structOrClassOffset) case .optionalChain: return .optionalChain case .optionalForce: return .optionalForce case .optionalWrap: return .optionalWrap } } func destroy() { switch header.kind { case .struct, .class, .optionalChain, .optionalForce, .optionalWrap: // trivial return } } func clone(into buffer: inout UnsafeMutableRawBufferPointer, endOfReferencePrefix: Bool) { var newHeader = header newHeader.endOfReferencePrefix = endOfReferencePrefix var componentSize = MemoryLayout<Header>.size buffer.storeBytes(of: newHeader, as: Header.self) switch header.kind { case .struct, .class: if header.payload == Header.payloadMask { let overflowOffset = body.load(as: UInt32.self) buffer.storeBytes(of: overflowOffset, toByteOffset: 4, as: UInt32.self) componentSize += 4 } case .optionalChain, .optionalForce, .optionalWrap: break } _sanityCheck(buffer.count >= componentSize) buffer = UnsafeMutableRawBufferPointer( start: buffer.baseAddress.unsafelyUnwrapped + componentSize, count: buffer.count - componentSize ) } func projectReadOnly<CurValue, NewValue>(_ base: CurValue) -> NewValue { switch value { case .struct(let offset): var base2 = base return withUnsafeBytes(of: &base2) { let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset) // The contents of the struct should be well-typed, so we can assume // typed memory here. return p.assumingMemoryBound(to: NewValue.self).pointee } case .class(let offset): _sanityCheck(CurValue.self is AnyObject.Type, "base is not a class") let baseObj = unsafeBitCast(base, to: AnyObject.self) let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj)) defer { _fixLifetime(baseObj) } return basePtr.advanced(by: offset) .assumingMemoryBound(to: NewValue.self) .pointee case .optionalChain: fatalError("TODO") case .optionalForce: fatalError("TODO") case .optionalWrap: fatalError("TODO") } } func projectMutableAddress<CurValue, NewValue>( _ base: UnsafeRawPointer, from _: CurValue.Type, to _: NewValue.Type, isRoot: Bool, keepAlive: inout [AnyObject] ) -> UnsafeRawPointer { switch value { case .struct(let offset): return base.advanced(by: offset) case .class(let offset): // A class dereference should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _sanityCheck(isRoot, "class component should not appear in the middle of mutation") // AnyObject memory can alias any class reference memory, so we can // assume type here let object = base.assumingMemoryBound(to: AnyObject.self).pointee // The base ought to be kept alive for the duration of the derived access keepAlive.append(object) return UnsafeRawPointer(Builtin.bridgeToRawPointer(object)) .advanced(by: offset) case .optionalForce: fatalError("TODO") case .optionalChain, .optionalWrap: _sanityCheckFailure("not a mutable key path component") } } } internal struct KeyPathBuffer { var data: UnsafeRawBufferPointer var trivial: Bool var hasReferencePrefix: Bool struct Header { var _value: UInt32 init(size: Int, trivial: Bool, hasReferencePrefix: Bool) { _sanityCheck(size <= 0x3FFF_FFFF, "key path too big") _value = UInt32(size) | (trivial ? 0x8000_0000 : 0) | (hasReferencePrefix ? 0x4000_0000 : 0) } var size: Int { return Int(_value & 0x3FFF_FFFF) } var trivial: Bool { return _value & 0x8000_0000 != 0 } var hasReferencePrefix: Bool { return _value & 0x4000_0000 != 0 } } init(base: UnsafeRawPointer) { let header = base.load(as: Header.self) data = UnsafeRawBufferPointer( start: base + MemoryLayout<Header>.size, count: header.size ) trivial = header.trivial hasReferencePrefix = header.hasReferencePrefix } func destroy() { if trivial { return } fatalError("TODO") } mutating func next() -> (RawKeyPathComponent, Any.Type?) { let header = pop(RawKeyPathComponent.Header.self) // Track if this is the last component of the reference prefix. if header.endOfReferencePrefix { _sanityCheck(self.hasReferencePrefix, "beginMutation marker in non-reference-writable key path?") self.hasReferencePrefix = false } let body: UnsafeRawBufferPointer let size = header.bodySize if size != 0 { body = popRaw(size) } else { body = UnsafeRawBufferPointer(start: nil, count: 0) } let component = RawKeyPathComponent(header: header, body: body) // fetch type, which is in the buffer unless it's the final component let nextType: Any.Type? if data.count == 0 { nextType = nil } else { if MemoryLayout<Any.Type>.size == 8 { // Words in the key path buffer are 32-bit aligned nextType = unsafeBitCast(pop((Int32, Int32).self), to: Any.Type.self) } else if MemoryLayout<Any.Type>.size == 4 { nextType = pop(Any.Type.self) } else { _sanityCheckFailure("unexpected word size") } } return (component, nextType) } mutating func pop<T>(_ type: T.Type) -> T { let raw = popRaw(MemoryLayout<T>.size) return raw.load(as: type) } mutating func popRaw(_ size: Int) -> UnsafeRawBufferPointer { _sanityCheck(data.count >= size, "not enough space for next component?") let result = UnsafeRawBufferPointer(start: data.baseAddress, count: size) data = UnsafeRawBufferPointer( start: data.baseAddress.unsafelyUnwrapped + size, count: data.count - size ) return result } } public struct _KeyPathBase<T> { public var base: T public init(base: T) { self.base = base } // TODO: These subscripts ought to sit on `Any` public subscript<U>(keyPath: KeyPath<T, U>) -> U { return keyPath.projectReadOnly(from: base) } public subscript<U>(keyPath: WritableKeyPath<T, U>) -> U { get { return keyPath.projectReadOnly(from: base) } mutableAddressWithNativeOwner { // The soundness of this `addressof` operation relies on the returned // address from an address only being used during a single formal access // of `self` (IOW, there's no end of the formal access between // `materializeForSet` and its continuation). let basePtr = UnsafeMutablePointer<T>(Builtin.addressof(&base)) return keyPath.projectMutableAddress(from: basePtr) } } public subscript<U>(keyPath: ReferenceWritableKeyPath<T, U>) -> U { get { return keyPath.projectReadOnly(from: base) } nonmutating mutableAddressWithNativeOwner { return keyPath.projectMutableAddress(from: base) } } }
apache-2.0
95fe4c43c18904d082160d653bc38e30
30.930108
94
0.610507
4.745126
false
false
false
false
artsy/eigen
ios/ArtsyWidget/FeaturedArtworks/FeaturedArtworks+SmallView.swift
1
1701
import SwiftUI import WidgetKit extension FeaturedArtworks { struct SmallView: SwiftUI.View { static let supportedFamilies: [WidgetFamily] = [.systemSmall] let entry: Entry var artwork: Artwork { return entry.artworks.first! } var body: some SwiftUI.View { let artsyLogo = UIImage(named: "BlackArtsyLogo")! let artworkImage = artwork.image! let artistName = artwork.artist.name let artworkUrl = artwork.url VStack() { HStack(alignment: .top) { Image(uiImage: artworkImage) .resizable() .scaledToFit() Spacer() Image(uiImage: artsyLogo) .resizable() .frame(width: 20, height: 20) } Spacer() PrimaryText(name: artistName) .lineLimit(1) .frame(maxWidth: .infinity, alignment: .leading) } .padding(16) .widgetURL(artworkUrl) .background(Color.white) } } } struct FeaturedArtworks_SmallView_Previews: PreviewProvider { static var previews: some SwiftUI.View { let entry = FeaturedArtworks.Entry.fallback() let families = FeaturedArtworks.SmallView.supportedFamilies Group { ForEach(families, id: \.self) { family in FeaturedArtworks.SmallView(entry: entry) .previewContext(WidgetPreviewContext(family: family)) } } } }
mit
f05c05c8e540a53a3fab1b8f311909c7
30.5
73
0.507349
5.217791
false
false
false
false
springware/cloudsight-swift
Example-swift/Pods/CloudSight/CloudSight/CloudSightImageResponse.swift
2
5820
// // CloudSightImageResponse.swift // CloudSight // // Created by OCR Labs on 3/7/17. // Copyright © 2017 OCR Labs. All rights reserved. // import UIKit public class CloudSightImageResponse: NSObject { let kTPImageResponseTroubleError = 9020 let kTPImageResponseTimeoutError = 9021 let kTPImageResponseURL = "https://api.cloudsightapi.com/image_responses/%@" var query: CloudSightQuery var currentTimer = NSTimer() var session = NSURLSession() var cancelled: Bool var delegate: CloudSightQueryDelegate var token: String = "" var loadPartialResponse: Bool = false init(token: String, withDelegate delegate: CloudSightQueryDelegate, forQuery _query: CloudSightQuery) { cancelled = false; self.token = token; self.delegate = delegate; query = _query; } deinit { self.cancel() } func handleErrorForCode(code: Int, withMessage message: String) { let error = NSError(domain: NSBundle(forClass: self.dynamicType).bundleIdentifier!, code: code, userInfo: [NSLocalizedDescriptionKey : message]) self.delegate.cloudSightQueryDidFail(query, withError: error) } func pollForResponse() { if cancelled { return } // Start next request to poll for image let responseUrl = String(format: kTPImageResponseURL, self.token) let params: NSDictionary = [:]; let authHeader = CloudSightConnection.sharedInstance().authorizationHeaderWithUrl(responseUrl, withParameters: params) // Setup connection session let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() sessionConfiguration.timeoutIntervalForRequest = 30 sessionConfiguration.HTTPAdditionalHeaders = ["Accept": "application/json", "Authorization": authHeader] session = NSURLSession.init(configuration: sessionConfiguration, delegate: nil, delegateQueue: nil) let responseUrlWithParameters = NSURL (string:responseUrl); //responseUrlWithParameters = responseUrlWithParameters. // [responseUrlWithParameters URLWithQuery:[NSString URLQueryWithParameters:params]]; let request = NSMutableURLRequest(URL: responseUrlWithParameters!) let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in if self.cancelled { return } if error != nil || data == nil { self.handleErrorForCode(self.kTPImageResponseTroubleError, withMessage: error!.localizedDescription) return } do { // Sanity check - sometimes server fails in the response (500 error, etc) let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let statusCode = (response as? NSHTTPURLResponse)?.statusCode if statusCode != 200 || dict.allKeys.count == 0 { self.handleErrorForCode(self.kTPImageResponseTroubleError, withMessage: String(data:data!, encoding: NSUTF8StringEncoding)!) return } // Handle the CloudSight image response let taggedImageStatus = String(dict.objectForKey("status")!) if taggedImageStatus == "not completed" { self.restart() } else if taggedImageStatus == "skipped" { var taggedImageString = dict.objectForKey("reason")! if taggedImageString is NSNull { taggedImageString = "" } self.query.skipReason = String(taggedImageString) self.delegate.cloudSightQueryDidFinishIdentifying(self.query) } else if taggedImageStatus == "in progress" || taggedImageStatus == "completed" { var taggedImageString = dict.objectForKey("name")! if taggedImageString is NSNull { taggedImageString = "" } self.query.title = String(taggedImageString) if taggedImageStatus == "in progress" { self.restart() self.delegate.cloudSightQueryDidUpdateTag(self.query) } else { self.delegate.cloudSightQueryDidFinishIdentifying(self.query) } } else if taggedImageStatus == "timeout" { self.handleErrorForCode(self.kTPImageResponseTimeoutError, withMessage: "Timeout, please try again") } } catch { print("error: \(error)") } }) task.resume() session.finishTasksAndInvalidate() } func cancel() { currentTimer.invalidate(); cancelled = true; session.invalidateAndCancel(); } func restart() { if cancelled { return } // Callback happens from another queue during response dispatch_async(dispatch_get_main_queue(), { // Restart the request loop after a 1s delay self.currentTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "pollForResponse", userInfo: nil, repeats: false)}) } }
mit
a54ddc6e29cedde16e02a99735b96686
38.317568
152
0.575528
5.795817
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift
4
1107
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// public class EmptyPredictionContext: SingletonPredictionContext { /// /// Represents `$` in local context prediction, which means wildcard. /// `+x = *`. /// public static let Instance = EmptyPredictionContext() public init() { super.init(nil, PredictionContext.EMPTY_RETURN_STATE) } override public func isEmpty() -> Bool { return true } override public func size() -> Int { return 1 } override public func getParent(_ index: Int) -> PredictionContext? { return nil } override public func getReturnState(_ index: Int) -> Int { return returnState } override public var description: String { return "$" } } public func ==(lhs: EmptyPredictionContext, rhs: EmptyPredictionContext) -> Bool { if lhs === rhs { return true } return false }
bsd-3-clause
9ce83664b45b5d2488ebe19b2d995d31
19.886792
82
0.615176
4.651261
false
false
false
false
dongishan/SayIt-iOS-Machine-Learning-App
Carthage/Checkouts/ios-sdk/Source/SpeechToTextV1/SpeechToText.swift
1
14601
/** * Copyright IBM Corporation 2016 * * 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 RestKit import AVFoundation /** The IBM Watson Speech to Text service enables you to add speech transcription capabilities to your application. It uses machine intelligence to combine information about grammar and language structure to generate an accurate transcription. Transcriptions are supported for various audio formats and languages. This class makes it easy to recognize audio with the Speech to Text service. Internally, many of the functions make use of the `SpeechToTextSession` class, but this class provides a simpler interface by minimizing customizability. If you find that you require more control of the session or microphone, consider using the `SpeechToTextSession` class instead. */ public class SpeechToText { /// The base URL to use when contacting the service. public var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" /// The URL that shall be used to obtain a token. public var tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" /// The URL that shall be used to stream audio for transcription. public var websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() private let username: String private let password: String private let credentials: Credentials private var microphoneSession: SpeechToTextSession? private let audioSession = AVAudioSession.sharedInstance() private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1" /** Create a `SpeechToText` object. - parameter username: The username used to authenticate with the service. - parameter password: The password used to authenticate with the service. */ public init(username: String, password: String) { self.username = username self.password = password self.credentials = Credentials.basicAuthentication(username: username, password: password) } /** If the given data represents an error returned by the Speech to Text service, then return an NSError object with information about the error that occured. Otherwise, return nil. - parameter data: Raw data returned from the service that may represent an error. */ private func dataToError(data: Data) -> NSError? { do { let json = try JSON(data: data) let error = try json.getString(at: "error") let code = try json.getInt(at: "code") let description = try json.getString(at: "code_description") let userInfo = [ NSLocalizedFailureReasonErrorKey: error, NSLocalizedRecoverySuggestionErrorKey: description ] return NSError(domain: domain, code: code, userInfo: userInfo) } catch { return nil } } /** Retrieve a list of models available for use with the service. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the list of models. */ public func getModels(failure: ((Error) -> Void)? = nil, success: @escaping ([Model]) -> Void) { // construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v1/models", credentials: credentials, headerParameters: defaultHeaders, acceptType: "application/json" ) // execute REST request request.responseArray(dataToError: dataToError, path: ["models"]) { (response: RestResponse<[Model]>) in switch response.result { case .success(let models): success(models) case .failure(let error): failure?(error) } } } /** Retrieve information about a particular model that is available for use with the service. - parameter withID: The alphanumeric ID of the model. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with information about the model. */ public func getModel( withID modelID: String, failure: ((Error) -> Void)? = nil, success: @escaping (Model) -> Void) { //construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v1/models/" + modelID, credentials: credentials, headerParameters: defaultHeaders, acceptType: "application/json" ) // execute REST request request.responseObject(dataToError: dataToError) { (response: RestResponse<Model>) in switch response.result { case .success(let model): success(model) case .failure(let error): failure?(error) } } } /** Perform speech recognition for an audio file. - parameter audio: The audio file to transcribe. - parameter settings: The configuration to use for this recognition request. - parameter model: The language and sample rate of the audio. For supported models, visit https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml#models. - parameter customizationID: The GUID of a custom language model that is to be used with the request. The base language model of the specified custom language model must match the model specified with the `model` parameter. By default, no custom model is used. - parameter learningOptOut: If `true`, then this request will not be logged for training. - parameter failure: A function executed whenever an error occurs. - parameter success: A function executed with all transcription results whenever a final or interim transcription is received. */ public func recognize( audio: URL, settings: RecognitionSettings, model: String? = nil, customizationID: String? = nil, learningOptOut: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (SpeechRecognitionResults) -> Void) { do { let data = try Data(contentsOf: audio) recognize( audio: data, settings: settings, model: model, customizationID: customizationID, learningOptOut: learningOptOut, failure: failure, success: success ) } catch { let failureReason = "Could not load audio data from \(audio)." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) failure?(error) return } } /** Perform speech recognition for audio data. - parameter audio: The audio data to transcribe. - parameter settings: The configuration to use for this recognition request. - parameter model: The language and sample rate of the audio. For supported models, visit https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml#models. - parameter customizationID: The GUID of a custom language model that is to be used with the request. The base language model of the specified custom language model must match the model specified with the `model` parameter. By default, no custom model is used. - parameter learningOptOut: If `true`, then this request will not be logged for training. - parameter failure: A function executed whenever an error occurs. - parameter success: A function executed with all transcription results whenever a final or interim transcription is received. */ public func recognize( audio: Data, settings: RecognitionSettings, model: String? = nil, customizationID: String? = nil, learningOptOut: Bool? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (SpeechRecognitionResults) -> Void) { // create session let session = SpeechToTextSession( username: username, password: password, model: model, customizationID: customizationID, learningOptOut: learningOptOut ) // set urls session.serviceURL = serviceURL session.tokenURL = tokenURL session.websocketsURL = websocketsURL // set headers session.defaultHeaders = defaultHeaders // set callbacks session.onResults = success session.onError = failure // execute recognition request session.connect() session.startRequest(settings: settings) session.recognize(audio: audio) session.stopRequest() session.disconnect() } /** Perform speech recognition for microphone audio. To stop the microphone, invoke `stopRecognizeMicrophone()`. Knowing when to stop the microphone depends upon the recognition request's continuous setting: - If `false`, then the service ends the recognition request at the first end-of-speech incident (denoted by a half-second of non-speech or when the stream terminates). This will coincide with a `final` transcription result. So the `success` callback should be configured to stop the microphone when a final transcription result is received. - If `true`, then you will typically stop the microphone based on user-feedback. For example, your application may have a button to start/stop the request, or you may stream the microphone for the duration of a long press on a UI element. Microphone audio is compressed to Opus format unless otherwise specified by the `compress` parameter. With compression enabled, the `settings` should specify a `contentType` of `AudioMediaType.Opus`. With compression disabled, the `settings` should specify `contentType` of `AudioMediaType.L16(rate: 16000, channels: 1)`. This function may cause the system to automatically prompt the user for permission to access the microphone. Use `AVAudioSession.requestRecordPermission(_:)` if you would prefer to ask for the user's permission in advance. - parameter settings: The configuration for this transcription request. - parameter model: The language and sample rate of the audio. For supported models, visit https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml#models. - parameter customizationID: The GUID of a custom language model that is to be used with the request. The base language model of the specified custom language model must match the model specified with the `model` parameter. By default, no custom model is used. - parameter learningOptOut: If `true`, then this request will not be logged for training. - parameter compress: Should microphone audio be compressed to Opus format? (Opus compression reduces latency and bandwidth.) - parameter failure: A function executed whenever an error occurs. - parameter success: A function executed with all transcription results whenever a final or interim transcription is received. */ public func recognizeMicrophone( settings: RecognitionSettings, model: String? = nil, customizationID: String? = nil, learningOptOut: Bool? = nil, compress: Bool = true, failure: ((Error) -> Void)? = nil, success: @escaping (SpeechRecognitionResults) -> Void) { // make sure the AVAudioSession shared instance is properly configured do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker, .mixWithOthers]) try audioSession.setActive(true) } catch { let failureReason = "Failed to setup the AVAudioSession sharedInstance properly." let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: self.domain, code: 0, userInfo: userInfo) failure?(error) return } // validate settings var settings = settings settings.contentType = compress ? .opus : .l16(rate: 16000, channels: 1) // create session let session = SpeechToTextSession( username: username, password: password, model: model, customizationID: customizationID, learningOptOut: learningOptOut ) // set urls session.serviceURL = serviceURL session.tokenURL = tokenURL session.websocketsURL = websocketsURL // set headers session.defaultHeaders = defaultHeaders // set callbacks session.onResults = success session.onError = failure // start recognition request session.connect() session.startRequest(settings: settings) session.startMicrophone(compress: compress) // store session microphoneSession = session } /** Stop performing speech recognition for microphone audio. When invoked, this function will 1. Stop recording audio from the microphone. 2. Send a stop message to stop the current recognition request. 3. Wait to receive all recognition results then disconnect from the service. */ public func stopRecognizeMicrophone() { microphoneSession?.stopMicrophone() microphoneSession?.stopRequest() microphoneSession?.disconnect() } }
gpl-3.0
0eb8c1e62d877a39867cd7316dc48271
41.199422
120
0.656941
5.223971
false
false
false
false
listen-li/DYZB
DYZB/DYZB/Classes/Home/ViewModel/RecommendVeiwModel.swift
1
4769
// // RecommendVeiwModel.swift // DYZB // // Created by admin on 17/7/21. // Copyright © 2017年 smartFlash. All rights reserved. // import UIKit class RecommendVeiwModel { //Mark:- 懒加载属性 //0 1 2-12 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var bigDataGroup : AnchorGroup = AnchorGroup() lazy var prettyGroup : AnchorGroup = AnchorGroup() lazy var cycleModels : [CycleModel] = [CycleModel]() } //Mark:- 发送网络请求 extension RecommendVeiwModel{ //请求推荐数据 func requestData(finishCallback : @escaping () -> ()) { //0.定义参数 let parameters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrentTime() as NSString] //创建Group let disgroup = DispatchGroup() //1.请求第一部分推荐数据 disgroup.enter() NetworkTools.requestData(tape: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrentTime() as NSString]) { (result) in //1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } //2.根据data该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } //3.遍历字典,并将字典转成模型对象 //3.1设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" //3.2获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } //3.3离开组 disgroup.leave() } //2.请求第二部分颜值数据 disgroup.enter() NetworkTools.requestData(tape: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in //1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } //2.根据data该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } //3.遍历字典,并将字典转成模型对象 //3.1设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" //3.2获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } //3.3离开组 disgroup.leave() } //3.请求2-12部分游戏数据 disgroup.enter() NetworkTools.requestData(tape: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in //1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } //2.根据data该key,获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } //3.遍历数组,获取字典,并将字典转成模型对象 for dict in dataArray { let group = AnchorGroup(dict: dict) self.anchorGroups.append(group) } //3.4离开组 disgroup.leave() } //4.所有的数据都请求到,之后进行排序 disgroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } //请求无限轮播的数据 func requestCycleData(finishCallback : @escaping () -> ()) { NetworkTools.requestData(tape: .GET, URLString: "http://capi.douyucdn.cn/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in //1.获取整体字典数据 guard let resultDic = result as? [NSString : NSObject] else { return } //2.根据data的key获取数据 guard let dataArray = resultDic["data"] as? [[NSString : NSObject]] else { return } //3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } finishCallback() } } }
mit
fc9bff8fa987bd7a12e24019b4892dfc
32.640625
178
0.530887
4.527865
false
false
false
false
kevinli194/CancerCenterPrototype
CancerInstituteDemo/CancerInstituteDemo/Resources/SpecialTableViewController.swift
1
3855
// // SpecialTableViewController.swift // CancerInstituteDemo // // Created by Anna Benson on 11/9/15. // Copyright © 2015 KAG. All rights reserved. // import UIKit class SpecialTableViewController: UITableViewController { //data arrays var specialTitles = ["CRUSH colorectal Cancer 5K & Fun Walk", "Spring For Support 5K", "Spa Day", "Strike Out Sarcoma 5K & Fun Walk", "Komen Race For The Cure", "Pink Ribbon Yoga Retreat", "Gail Parkins Memorial Ovarian Cancer Walk & 5K", "Boyette Family Farm Corn Maze", "Making Strides Against Breast Cancer", "Light The Night", "Tree of Hope Lighting Ceremony"] var specialDescriptions = [ "Held March 14 at the American Tobacco Trail in Durham, NC. For more information, visit sites.duke.edu", "Held March 28 at Southpoint Mall in Durham, NC. For more information, visit Springforsupport5k.org", "Spa Day is an annual event hosted by the Duke Cancer Patient Support Program. Spa Day focuses on Duke Cancer Center patients and their caregivers. Vendors volunteer to provide services including makeovers, wig styling, massage therapy, hand massage, gentle yoga, and poetry. Spa Day will be held on Wednesday, June 1, from 10 a.m. to 3 p.m. for more information, call 919.684.4497.", "Held Jun 13 at the Durham Athletic Park. For more information, visit sites.duke.edu/dukecancerinstitute", "Held June 14 at RTP in Morrisville, NC. For more information, visit Komennctc.org", "Held August 7 through August 10 at the Trinity Center. For more information, visit Yogaretreat.com", "Held September 12 at Sanderson High School in Raleigh, NC. For more information, visit ovarianawareness.org", "Held October 1 through Oct. 31 in Clayton, NC.", "Held October 2 in the Noth Hills Mall in Raleigh, NC. For more information, visit Makingstrides.acsevents.org", "Held October 10 in Durham, NC. For more information, visit lightthenight.org", "Held in December in the Duke Cancer Center. For more information, visit sites.duke.edu/dukecancerinstitute"] var specialImages = ["crushColorectal.jpg", "springSupport.png","spaDay.jpg","strikeoutSarcoma.png", "default.jpg", "default.jpg", "default.jpg", "default.jpg", "default.jpg", "default.jpg", "treeHope.jpg"] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return specialTitles.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //set up table view let cell = self.tableView.dequeueReusableCellWithIdentifier("SpecialTableViewCell", forIndexPath: indexPath) as! SpecialTableViewCell let row = indexPath.row cell.specialLabel.text = specialTitles[row] return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //navigate to new pages via segues if segue.identifier == "ShowSpecialDetails" { let detailViewController = segue.destinationViewController as! SpecialDetailViewController let myIndexPath = self.tableView.indexPathForSelectedRow! let row = myIndexPath.row detailViewController.myTitle = specialTitles[row] detailViewController.myDescription = specialDescriptions[row] detailViewController.myImage = specialImages[row] } } }
mit
4def17793baee42f4daeef0ff6cae815
55.632353
392
0.709166
4.213348
false
false
false
false
modocache/FutureKit
FutureKit/FutureBatch.swift
3
14597
// // Future-Sequences.swift // FutureKit // // Created by Michael Gray on 4/13/15. // 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 // --------------------------------------------------------------------------------------------------- // // CONVERT an Array of Futures into a single Future // // --------------------------------------------------------------------------------------------------- public typealias FutureBatch = FutureBatchOf<Any> public class FutureBatchOf<T> { /** */ internal(set) var subFutures = [Future<T>]() private var tokens = [CancellationToken]() /** `completionsFuture` returns an array of individual Completion<T> values - returns: a `Future<[Completion<T>]>` always returns with a Success. Returns an array of the individual Future.Completion values for each subFuture. */ public internal(set) var completionsFuture : Future<[Completion<T>]> /** batchFuture succeeds iff all subFutures succeed. The result is an array `[T]`. it does not complete until all futures have been completed within the batch (even if some fail or are cancelled). */ public internal(set) lazy var batchFuture : Future<[T]> = FutureBatchOf.futureFromCompletionsFuture(self.completionsFuture) /** `future` succeeds iff all subfutures succeed. Will complete with a Fail or Cancel as soon as the first sub future is failed or cancelled. `future` may complete, while some subfutures are still running, if one completes with a Fail or Canycel. If it's important to know that all Futures have completed, you can alertnatively use `batchFuture` and `cancelRemainingFuturesOnFirstFail()` or `cancelRemainingFuturesOnFirstFailOrCancel()`. batchFuture will always wait for all subFutures to complete before finishing, but will wait for the cancellations to be processed before exiting. this wi */ public internal(set) lazy var future : Future<[T]> = self._onFirstFailOrCancel() /** takes a type-safe list of Futures. */ public init(f : [Future<T>]) { self.subFutures = f for s in self.subFutures { if let t = s.getCancelToken() { self.tokens.append(t) } } self.completionsFuture = FutureBatchOf.completionsFuture(f) } /** takes a list of Futures. Each future will be converted into a Future that returns T. */ public convenience init(futures : [AnyObject]) { let f : [Future<T>] = FutureBatch.convertArray(futures) self.init(f:f) } /** takes a type-safe list of Futures. */ public convenience init(array : NSArray) { let f : [Future<T>] = FutureBatch.convertArray(array as [AnyObject]) self.init(f:f) } /** will forward a cancel request to each subFuture Doesn't guarantee that a particular future gets canceled */ func cancel(forced:Bool = false) { for t in self.tokens { t.cancel(forced:forced) } } /** will cause any other Futures to automatically be cancelled, if one of the subfutures future fails or is cancelled */ func cancelRemainingFuturesOnFirstFailOrCancel() { self.future.onComplete { (completion) -> Void in if (!completion.isSuccess) { self.cancel() } } } /** will cause any other subfutures to automatically be cancelled, if one of the subfutures future fails. Cancellations are ignored. */ func cancelRemainingFuturesOnFirstFail() { self.future.onComplete { (completion) -> Void in if (completion.isFail) { self.cancel() } } } /** Allows you to define a Block that will execute as soon as each Future completes. The biggest difference between using onEachComplete() or just using the `future` var, is that this block will execute as soon as each future completes. The block will be executed repeately, until all sub futures have been completed. This can also be used to compose a new Future[__Type]. All the values returned from the block will be assembled and returned in a new Future<[__Type]. If needed. - parameter executor: executor to use to run the block :block: block block to execute as soon as each Future completes. */ public final func onEachComplete<__Type>(executor : Executor,block:(completion:Completion<T>, future:Future<T>, index:Int)-> __Type) -> Future<[__Type]> { var futures = [Future<__Type>]() for (index, future) in enumerate(self.subFutures) { let f = future.onComplete({ (completion) -> __Type in return block(completion: completion, future:future,index: index) }) futures.append(f) } return FutureBatchOf<__Type>.futureFromArrayOfFutures(futures) } public final func onEachComplete<__Type>(block:(completion:Completion<T>, future:Future<T>,index:Int)-> __Type) -> Future<[__Type]> { return self.onEachComplete(.Primary, block: block) } /** */ private final func _onFirstFailOrCancel(executor : Executor = .Immediate,block:((error:ErrorType, future:Future<T>, index:Int)-> Void)? = nil) -> Future<[T]> { let promise = Promise<[T]>() // we are gonna make a Future that typealias blockT = () -> Void let failOrCancelPromise = Promise<blockT?>() for (index, future) in enumerate(self.subFutures) { future.onComplete({ (completion) -> Void in if (completion.state != .Success) { let cb = executor.callbackBlockFor { block?(error: completion.error, future: future, index: index) } failOrCancelPromise.completeWithSuccess(cb) promise.complete(completion.As()) } }) } self.batchFuture.onComplete { (completion) -> Void in if (completion.state == .Success) { failOrCancelPromise.completeWithCancel() } } failOrCancelPromise.future.onSuccess { (result) -> Void in result?() } self.batchFuture.onComplete (.Immediate) { (completion) -> Void in promise.complete(completion) } return promise.future } /* adds a handler that executes on the first Future that fails. :params: block a block that will execute **/ public final func onFirstFail(executor : Executor,block:(error:NSError, future:Future<T>, index:Int)-> Void) -> Future<[T]> { return _onFirstFailOrCancel(executor: executor, block: block) } public final func onFirstFail(block:(error:NSError, future:Future<T>, index:Int)-> Void) -> Future<[T]> { return _onFirstFailOrCancel(executor: .Primary, block: block) } /** takes an array of futures returns a new array of futures converted to the desired Type `<__Type>` `Any` is the only type that is guaranteed to always work. Useful if you have a bunch of mixed type Futures, and convert them into a list of Future types. WARNING: if `T as! __Type` isn't legal, than your code may generate an exception. works iff the following code works: let t : T let s = t as! __Type example: - parameter array: array of Futures - returns: an array of Futures converted to return type <S> */ public class func convertArray<__Type>(array:[Future<T>]) -> [Future<__Type>] { var futures = [Future<__Type>]() for a in array { futures.append(a.As()) } return futures } /** takes an array of futures returns a new array of futures converted to the desired Type <S> 'Any' is the only type that is guaranteed to always work. Useful if you have a bunch of mixed type Futures, and convert them into a list of Future types. - parameter array: array of Futures - returns: an array of Futures converted to return type <S> */ public class func convertArray<__Type>(array:[AnyObject]) -> [Future<__Type>] { var futures = [Future<__Type>]() for a in array { let f = a as! FutureProtocol futures.append(f.As()) } return futures } /** takes an array of futures of type `[Future<T>]` and returns a single future of type Future<[Completion<T>] So you can now just add a single onSuccess/onFail/onCancel handler that will be executed once all of the sub-futures in the array have completed. This future always returns .Success, with a result individual completions. This future will never complete, if one of it's sub futures doesn't complete. you have to check the result of the array individually if you care about the specific outcome of a subfuture - parameter array: an array of Futures of type `[T]`. - returns: a single future that returns an array of `Completion<T>` values. */ public class func completionsFuture(array : [Future<T>]) -> Future<[Completion<T>]> { if (array.count == 0) { let result = [Completion<T>]() return Future<[Completion<T>]>(success: result) } else if (array.count == 1) { let f = array.first! return f.onComplete({ (c: Completion<T>) -> [Completion<T>] in return [c] }) } else { let promise = Promise<[Completion<T>]>() var total = array.count var result = [Completion<T>](count:array.count,repeatedValue:.Cancelled) for (index, future) in enumerate(array) { future.onComplete(.Immediate) { (completion: Completion<T>) -> Void in promise.synchObject.modifyAsync({ () -> Int in result[index] = completion total-- return total }, done: { (currentTotal) -> Void in if (currentTotal == 0) { promise.completeWithSuccess(result) } }) } } return promise.future } } /** takes a future of type `Future<[Completion<T>]` (usually returned from `completionFutures()`) and returns a single future of type `Future<[T]>`. It checks all the completion values and will return .Fail if one of the Futures Failed. will return .Cancelled if there were no .Fail completions, but at least one subfuture was cancelled. returns .Success iff all the subfutures completed. - parameter a: completions future of type `Future<[Completion<T>]>` - returns: a single future that returns an array an array of `[T]`. */ public class func futureFromCompletionsFuture<T>(f : Future<[Completion<T>]>) -> Future<[T]> { return f.onSuccess { (completions:[Completion<T>]) -> Completion<[T]> in var results = [T]() var errors = [ErrorType]() var cancellations = 0 for completion in completions { switch completion.state { case .Success: let r = completion.result results.append(r) case .Fail: errors.append(completion.error) case .Cancelled: cancellations++ } } if (errors.count > 0) { if (errors.count == 1) { return FAIL(errors.first!) } else { return FAIL(FutureNSError(error: .ErrorForMultipleErrors, userInfo:["errors" : "\(errors)"])) } } if (cancellations > 0) { return CANCELLED() } return SUCCESS(results) } } /** takes an array of futures of type `[Future<T>]` and returns a single future of type Future<[T]> So you can now just add a single onSuccess/onFail/onCancel handler that will be executed once all of the sub-futures in the array have completed. It checks all the completion values and will return .Fail if one of the Futures Failed. will return .Cancelled if there were no .Fail completions, but at least one subfuture was cancelled. returns .Success iff all the subfutures completed. this Future will not complete until ALL subfutures have finished. If you need a Future that completes as soon as single Fail or Cancel is seen, use a `FutureBatch` object and use the var `future` or the method `onFirstFail()` - parameter array: an array of Futures of type `[T]`. - returns: a single future that returns an array of `[T]`, or a .Fail or .Cancel if a single sub-future fails or is canceled. */ public final class func futureFromArrayOfFutures(array : [Future<T>]) -> Future<[T]> { return futureFromCompletionsFuture(completionsFuture(array)) } }
mit
72ae9fec6d2b279b17a3cac6ada76076
39.434903
346
0.597657
4.742365
false
false
false
false
squaremeals/squaremeals-ios-app
SquareMeals/Supporting Files/Extensions/UICollectionView+Extensions.swift
1
2696
// // UICollectionView+Extensions.swift // Command // // Created by Zachary Shakked on 12/15/16. // Copyright © 2016 Shakd, LLC. All rights reserved. // import UIKit import UIKit extension UICollectionView { // MARK: Deque public func dequeueCell<T: ReusableView>(for indexPath: IndexPath) -> T { return dequeueCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) } public func dequeueCell<T>(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? T else { fatalError("Type not registered with identifier: \(identifier)") } return cell } public func dequeueHeaderFooter<T: ReusableView>(ofKind kind: String, for indexPath: IndexPath) -> T { return dequeueHeaderFooter(ofKind: kind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) } public func dequeueHeaderFooter<T>(ofKind kind: String, withReuseIdentifier identifier: String, for indexPath: IndexPath) -> T { guard let view = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath) as? T else { fatalError("Type not registered with identifier: \(identifier)") } return view } // MARK: Registration public func registerCell(type: ReusableView.Type) { if let nib = UINib(potentialName: String(describing: type)) { register(nib, forCellWithReuseIdentifier: type.reuseIdentifier) return } register(type.self, forCellWithReuseIdentifier: type.reuseIdentifier) } public func registerCells(types: ReusableView.Type...) { types.forEach { registerCell(type: $0) } } public func registerHeader(type: ReusableView.Type) { if let nib = UINib(potentialName: String(describing: type)) { register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: type.reuseIdentifier) return } register(type.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: type.reuseIdentifier) } public func registerFooter(type: ReusableView.Type) { if let nib = UINib(potentialName: String(describing: type)) { register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: type.reuseIdentifier) return } register(type.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: type.reuseIdentifier) } }
mit
1b1df429a587e75990dd79a66b271f16
38.057971
200
0.696104
5.39
false
false
false
false
vasi05/MovingHelper
MovingHelper/ModelControllers/TaskLoader.swift
1
1285
// // TaskLoader.swift // MovingHelper // // Created by Ellen Shapiro on 6/7/15. // Copyright (c) 2015 Razeware. All rights reserved. // import UIKit /* Struct to load tasks from JSON. */ public struct TaskLoader { static func loadSavedTasksFromJSONFile(fileName: FileName) -> [Task]? { let path = fileName.jsonFileName().pathInDocumentsDirectory() if let data = NSData(contentsOfFile: path) { return tasksFromData(data) } else { return nil } } /** - returns: The stock moving tasks included with the app. */ public static func loadStockTasks() -> [Task] { if let path = NSBundle.mainBundle() .pathForResource(FileName.StockTasks.rawValue, ofType: "json"), data = NSData(contentsOfFile: path), tasks = tasksFromData(data) { return tasks } //Fall through case NSLog("Tasks did not load!") return [Task]() } private static func tasksFromData(data: NSData) -> [Task]? { do { let arrayOfTaskDictionaries = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [NSDictionary] // use jsonData return Task.tasksFromArrayOfJSONDictionaries(arrayOfTaskDictionaries!) } catch { // report error return nil } } }
mit
5b80972ca8daaea3e5561570b0bdf37e
22.814815
118
0.64358
4.312081
false
false
false
false
openHPI/xikolo-ios
Common/Helpers/Markdown/NSLayoutManager+setNeedLayout.swift
1
1710
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // extension NSLayoutManager { /// Determine the character ranges for an attachment private func rangesForAttachment(attachment: NSTextAttachment) -> [NSRange] { guard let textStorage = self.textStorage else { return [] } // find character range for this attachment let range = NSRange(location: 0, length: textStorage.length) var refreshRanges: [NSRange] = [] textStorage.enumerateAttribute(NSAttributedString.Key.attachment, in: range, options: []) { value, effectiveRange, _ in guard let foundAttachment = value as? NSTextAttachment, foundAttachment == attachment else { return } // add this range to the refresh ranges refreshRanges.append(effectiveRange) } return refreshRanges } /// Trigger a relayout for an attachment func setNeedsLayout(forAttachment attachment: NSTextAttachment) { // invalidate the display for the corresponding ranges for range in self.rangesForAttachment(attachment: attachment).reversed() { self.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil) self.invalidateDisplay(forCharacterRange: range) } } /// Trigger a re-display for an attachment func setNeedsDisplay(forAttachment attachment: NSTextAttachment) { // invalidate the display for the corresponding ranges for range in self.rangesForAttachment(attachment: attachment).reversed() { self.invalidateDisplay(forCharacterRange: range) } } }
gpl-3.0
dc492ce2d43310580b81648fc27f7d15
35.361702
127
0.668227
5.357367
false
false
false
false
DigitalRogues/DisneyWatch
DisneyWatchApp Extension/MagicIndexObject.swift
1
1053
// // MagicIndexRealmObject.swift // Digital Rogues // // Created by punk on 8/30/15. // Copyright © 2015 Digital Rogues. All rights reserved. // import Foundation class MagicIndexObject: NSObject { // {"parks":{"date":"Saturday September 05 2015","disneyland":{"crowdIndex":"20","forecast":"yup, it’s packed","times":"9:00AM to 11:00PM"},"california_adventure":{"crowdIndex":"20","forecast":"yup, it’s packed","times":"):9:00AM to 9:00PM"}},"lastUpdated":1441470610} // dynamic var dlrIndex:String = "" dynamic var dlrOpen:String = "" dynamic var dlrForecast:String = "" dynamic var dcaIndex:String = "" dynamic var dcaOpen:String = "" dynamic var dcaForecast:String = "" dynamic var lastUpdated:String = "" dynamic var lastUpdated_unix:String = "" dynamic var date:String = "" dynamic var closed:String = "" // Specify properties to ignore (Realm won't persist these) // override static func ignoredProperties() -> [String] { // return [] // } }
mit
7b93b7e85bf6f2bdb39ae9350c2be51a
26.578947
271
0.638359
3.651568
false
false
false
false
jakecraige/SwiftLint
Source/SwiftLintFramework/Location.swift
1
1535
// // Location.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public struct Location: CustomStringConvertible, Equatable { public let file: String? public let line: Int? public let character: Int? public var description: String { // Xcode likes warnings and errors in the following format: // {full_path_to_file}{:line}{:character}: {error,warning}: {content} return (file ?? "<nopath>") + (line.map({ ":\($0)" }) ?? "") + (character.map({ ":\($0)" }) ?? "") } public init(file: String?, line: Int? = nil, character: Int? = nil) { self.file = file self.line = line self.character = character } public init(file: File, offset: Int) { self.file = file.path if let lineAndCharacter = file.contents.lineAndCharacterForByteOffset(offset) { line = lineAndCharacter.line character = lineAndCharacter.character } else { line = nil character = nil } } } // MARK: Equatable /** Returns true if `lhs` Location is equal to `rhs` Location. :param: lhs Location to compare to `rhs`. :param: rhs Location to compare to `lhs`. :returns: True if `lhs` Location is equal to `rhs` Location. */ public func == (lhs: Location, rhs: Location) -> Bool { return lhs.file == rhs.file && lhs.line == rhs.line && lhs.character == rhs.character }
mit
e7cdc8e27ebed2d588412d78bd6297e1
26.909091
87
0.59544
3.956186
false
false
false
false
robertherdzik/RHSideButtons
RHSideButtons/RHSideButtons/RHButtonView.swift
1
4077
// // RHButtonView.swift // RHSideButtons // // Created by Robert Herdzik on 22/05/16. // Copyright © 2016 Robert Herdzik. All rights reserved. // import UIKit public protocol RHButtonViewDelegate: class { func didSelectButton(_ buttonView: RHButtonView) } public class RHButtonView: UIView, RHButtonViewConfigProtocol { public typealias BuildCellBlock = (RHButtonViewConfigProtocol) -> Void public weak var delegate: RHButtonViewDelegate? public var bgColor: UIColor = UIColor.white { didSet { backgroundColor = bgColor } } public var image: UIImage? { didSet { setupImageViewIfNeeded() updateImageView() layoutIfNeeded() } } public var hasShadow: Bool = true { didSet { hasShadow ? addShadow() : removeShadow() layoutIfNeeded() } } public var imgView: UIImageView? fileprivate let overlayView = UIView() override init(frame: CGRect) { super.init(frame: frame) setup() } convenience public init(builder: BuildCellBlock) { self.init(frame: CGRect.zero) builder(self) } convenience public init(builder: RHButtonViewConfigProtocol) { self.init(frame: CGRect.zero) bgColor = builder.bgColor image = builder.image hasShadow = builder.hasShadow } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() // View Appearance layer.cornerRadius = bounds.width/2 //Overlay Layer overlayView.frame = bounds overlayView.layer.cornerRadius = layer.cornerRadius // Image View imgView?.frame = bounds imgView?.layer.cornerRadius = layer.cornerRadius // Shadow setShadowOffset(false) } fileprivate func setup() { setupOverlayLayer() } fileprivate func setupOverlayLayer() { overlayView.backgroundColor = UIColor.clear overlayView.isUserInteractionEnabled = false addSubview(overlayView) } fileprivate func setupImageViewIfNeeded() { if imgView != nil { return } imgView = UIImageView(image: image) insertSubview(imgView!, belowSubview: overlayView) } fileprivate func updateImageView() { imgView?.image = image imgView?.contentMode = .scaleAspectFit imgView?.clipsToBounds = true } fileprivate func addShadow() { layer.shadowOpacity = 0.8 layer.shadowColor = UIColor.darkGray.cgColor } fileprivate func removeShadow() { layer.shadowOpacity = 0 } fileprivate func setShadowOffset(_ isSelected: Bool) { let shadowOffsetX = isSelected ? CGFloat(1) : CGFloat(5) let shadowOffsetY = isSelected ? CGFloat(0) : CGFloat(3) layer.shadowOffset = CGSize(width: bounds.origin.x + shadowOffsetX, height: bounds.origin.y + shadowOffsetY) } fileprivate func adjustAppearanceForStateSelected(_ selected: Bool) { setShadowOffset(selected) setOverlayColorForState(selected) } fileprivate func setOverlayColorForState(_ selected: Bool) { overlayView.backgroundColor = selected ? UIColor.black.withAlphaComponent(0.2) : UIColor.clear } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { adjustAppearanceForStateSelected(true) } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { adjustAppearanceForStateSelected(false) } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { delegate?.didSelectButton(self) adjustAppearanceForStateSelected(false) } }
mit
993ed1e1495445d80942695302cfd612
26.917808
116
0.623651
5.252577
false
false
false
false
material-motion/material-motion-swift
src/reactivetypes/Reactive+CALayer.swift
2
12111
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit extension Reactive where O: CALayer { public var anchorPoint: ReactiveProperty<CGPoint> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.anchorPoint, externalWrite: { layer.anchorPoint = $0 }, keyPath: "anchorPoint") } } public var anchorPointAdjustment: ReactiveProperty<AnchorPointAdjustment> { let anchorPoint = self.anchorPoint let position = self.position return _properties.named(#function) { return .init(initialValue: .init(anchorPoint: anchorPoint.value, position: position.value)) { anchorPoint.value = $0.anchorPoint; position.value = $0.position } } } public var backgroundColor: ReactiveProperty<CGColor> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.backgroundColor!, externalWrite: { layer.backgroundColor = $0 }, keyPath: "backgroundColor") } } public var cornerRadius: ReactiveProperty<CGFloat> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.cornerRadius, externalWrite: { layer.cornerRadius = $0 }, keyPath: "cornerRadius") } } public var height: ReactiveProperty<CGFloat> { let size = self.size return _properties.named(#function) { return createCoreAnimationProperty(initialValue: size.value.height, externalWrite: { var dimensions = size.value; dimensions.height = $0; size.value = dimensions }, keyPath: "bounds.size.height") } } public var opacity: ReactiveProperty<CGFloat> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: CGFloat(layer.opacity), externalWrite: { layer.opacity = Float($0) }, keyPath: "opacity") } } public var position: ReactiveProperty<CGPoint> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.position, externalWrite: { layer.position = $0 }, keyPath: "position") } } public var positionX: ReactiveProperty<CGFloat> { let position = self.position return _properties.named(#function) { return createCoreAnimationProperty(initialValue: position.value.x, externalWrite: { var point = position.value; point.x = $0; position.value = point }, keyPath: "position.x") } } public var positionY: ReactiveProperty<CGFloat> { let position = self.position return _properties.named(#function) { return createCoreAnimationProperty(initialValue: position.value.y, externalWrite: { var point = position.value; point.y = $0; position.value = point }, keyPath: "position.y") } } public var rotation: ReactiveProperty<CGFloat> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.value(forKeyPath: "transform.rotation.z") as! CGFloat, externalWrite: { layer.setValue($0, forKeyPath: "transform.rotation.z") }, keyPath: "transform.rotation.z") } } public var scale: ReactiveProperty<CGFloat> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.value(forKeyPath: "transform.scale") as! CGFloat, externalWrite: { layer.setValue($0, forKeyPath: "transform.scale") }, keyPath: "transform.scale.xy") } } public var size: ReactiveProperty<CGSize> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.bounds.size, externalWrite: { layer.bounds.size = $0 }, keyPath: "bounds.size") } } public var shadowPath: ReactiveProperty<CGPath> { let layer = _object return _properties.named(#function) { return createCoreAnimationProperty(initialValue: layer.shadowPath!, externalWrite: { layer.shadowPath = $0 }, keyPath: "shadowPath") } } public var width: ReactiveProperty<CGFloat> { let size = self.size return _properties.named(#function) { return createCoreAnimationProperty(initialValue: size.value.width, externalWrite: { var dimensions = size.value; dimensions.width = $0; size.value = dimensions }, keyPath: "bounds.size.width") } } func createCoreAnimationProperty<T>(initialValue: T, externalWrite: @escaping NextChannel<T>, keyPath: String) -> ReactiveProperty<T> { let layer = _object var decomposedKeys = Set<String>() let property = ReactiveProperty(initialValue: initialValue, externalWrite: { value in let actionsWereDisabled = CATransaction.disableActions() CATransaction.setDisableActions(true) externalWrite(value) CATransaction.setDisableActions(actionsWereDisabled) }, coreAnimation: { event in switch event { case .add(let info): if let timeline = info.timeline { layer.timeline = timeline } let animation = info.animation.copy() as! CAPropertyAnimation if !(animation is CASpringAnimation) { animation.duration *= TimeInterval(simulatorDragCoefficient()) animation.beginTime *= TimeInterval(simulatorDragCoefficient()) } if layer.speed == 0, let lastTimelineState = layer.lastTimelineState { animation.beginTime = TimeInterval(lastTimelineState.beginTime) + animation.beginTime } else { animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) + animation.beginTime } animation.keyPath = keyPath if let unsafeMakeAdditive = info.makeAdditive { let makeAdditive: ((Any, Any) -> Any) = { from, to in // When mapping properties to properties it's possible for the values to get implicitly // wrapped in an NSNumber instance. This may cause the generic makeAdditive // implementation to fail to cast to T, so we unbox the type here instead. if let from = from as? NSNumber, let to = to as? NSNumber { return from.doubleValue - to.doubleValue } return unsafeMakeAdditive(from, to) } if let basicAnimation = animation as? CABasicAnimation { basicAnimation.fromValue = makeAdditive(basicAnimation.fromValue!, basicAnimation.toValue!) basicAnimation.toValue = makeAdditive(basicAnimation.toValue!, basicAnimation.toValue!) basicAnimation.isAdditive = true } else if let keyframeAnimation = animation as? CAKeyframeAnimation { let lastValue = keyframeAnimation.values!.last! keyframeAnimation.values = keyframeAnimation.values!.map { makeAdditive($0, lastValue) } keyframeAnimation.isAdditive = true } } // Core Animation springs do not support multi-dimensional velocity, so we bear the burden // of decomposing multi-dimensional springs here. if let springAnimation = animation as? CASpringAnimation , springAnimation.isAdditive , let initialVelocity = info.initialVelocity as? CGPoint , let delta = springAnimation.fromValue as? CGPoint { let decomposed = decompose(springAnimation: springAnimation, delta: delta, initialVelocity: initialVelocity) CATransaction.begin() CATransaction.setCompletionBlock(info.onCompletion) layer.add(decomposed.0, forKey: info.key + ".x") layer.add(decomposed.1, forKey: info.key + ".y") CATransaction.commit() decomposedKeys.insert(info.key) return } if let initialVelocity = info.initialVelocity { applyInitialVelocity(initialVelocity, to: animation) } CATransaction.begin() CATransaction.setCompletionBlock(info.onCompletion) layer.add(animation, forKey: info.key + "." + keyPath) CATransaction.commit() case .remove(let key): if let presentationLayer = layer.presentation() { layer.setValue(presentationLayer.value(forKeyPath: keyPath), forKeyPath: keyPath) } if decomposedKeys.contains(key) { layer.removeAnimation(forKey: key + ".x") layer.removeAnimation(forKey: key + ".y") decomposedKeys.remove(key) } else { layer.removeAnimation(forKey: key + "." + keyPath) } } }) var lastView: UIView? property.shouldVisualizeMotion = { view, containerView in if lastView != view, let lastView = lastView { lastView.removeFromSuperview() } view.isUserInteractionEnabled = false if let superlayer = layer.superlayer { view.frame = superlayer.convert(superlayer.bounds, to: containerView.layer) } else { view.frame = containerView.bounds } containerView.addSubview(view) lastView = view } return property } } private func decompose(springAnimation: CASpringAnimation, delta: CGPoint, initialVelocity: CGPoint) -> (CASpringAnimation, CASpringAnimation) { let xAnimation = springAnimation.copy() as! CASpringAnimation let yAnimation = springAnimation.copy() as! CASpringAnimation xAnimation.fromValue = delta.x yAnimation.fromValue = delta.y xAnimation.toValue = 0 yAnimation.toValue = 0 if delta.x != 0 { xAnimation.initialVelocity = initialVelocity.x / -delta.x } if delta.y != 0 { yAnimation.initialVelocity = initialVelocity.y / -delta.y } xAnimation.keyPath = springAnimation.keyPath! + ".x" yAnimation.keyPath = springAnimation.keyPath! + ".y" return (xAnimation, yAnimation) } private func applyInitialVelocity(_ initialVelocity: Any, to animation: CAPropertyAnimation) { if let springAnimation = animation as? CASpringAnimation, springAnimation.isAdditive { // Additive animations have a toValue of 0 and a fromValue of negative delta (where the model // value came from). guard let initialVelocity = initialVelocity as? CGFloat, let delta = springAnimation.fromValue as? CGFloat else { // Unsupported velocity type. return } if delta != 0 { // CASpringAnimation's initialVelocity is proportional to the distance to travel, i.e. our // delta. springAnimation.initialVelocity = initialVelocity / -delta } } }
apache-2.0
0b68b4d2a013963f81f5359b4639aeaa
39.64094
144
0.628767
5.101516
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/TripKitUIBundle.swift
1
2248
// // TripKitUIBundle.swift // TripKit // // Created by Adrian Schoenig on 23/06/2016. // // import Foundation import UIKit extension UIImage { public static let iconAlert = named("icon-alert") public static let iconCross = named("icon-cross") public static let iconCompass = UIImage.named("icon-compass") // Occupancy static let iconCheckMini = named("icon-check-mini") static let iconExclamationmarkMini = named("icon-exclamation-mark-mini") static let iconCrossMini = named("icon-cross-mini") static let iconWheelchairMini = named("icon-wheelchair-mini") // Badges public static let badgeCheck = named("check-mark") public static let badgeHeart = named("heart-circle") public static let badgeLeaf = named("leaf-circle") public static let badgeLightning = named("lightning-circle") public static let badgeLike = named("like-circle") public static let badgeMoney = named("money-circle") // Actions public static let iconAlternative = named("alternative") public static let iconArrow = named("icon-arrow") public static let iconArrowUp = named("arrow-up") public static let iconShowPassword = named("icon-show") public static let iconHidePassword = named("icon-hide") public static let iconShare = named("share") public static let iconChevronDown = named("chevron-down") public static let iconChevronTimetable = named("timetable-chevron-down") // TripBoy static let iconTripBoyWorker = named("worker") static let iconTripBoyHappy = named("tripboy-smile") static let iconTripBoySad = named("tripboy-sad") } extension UIImage { private static func named(_ name: String) -> UIImage { return UIImage(named: name, in: .tripKitUI, compatibleWith: nil)! } } class TripKitUIBundle: NSObject { static func optionalImageNamed(_ name: String) -> UIImage? { return UIImage(named: name, in: .tripKitUI, compatibleWith: nil) } static func imageNamed(_ name: String) -> UIImage { guard let image = optionalImageNamed(name) else { preconditionFailure() } return image } fileprivate static func bundle() -> Bundle { return Bundle(for: self) } } extension Bundle { static let tripKitUI: Bundle = TripKitUIBundle.bundle() }
apache-2.0
d78af4f47bbec85f132bcb92f8e88b2e
26.084337
74
0.715302
4.028674
false
false
false
false
rharri/swift-ios
CityDetail/CityDetail/City.swift
1
668
// // City.swift // CityDetail // // Created by Ryan Harri on 2016-05-03. // Copyright © 2016 Ryan Harri. All rights reserved. // import Foundation import UIKit class City { let name: String let country: String let population: Double let grossDomesticProduct: Double let url: String let image: UIImage? init(name: String, country: String, population: Double, grossDomesticProduct: Double, url: String, image: UIImage?) { self.name = name self.country = country self.population = population self.grossDomesticProduct = grossDomesticProduct self.url = url self.image = image } }
mit
3e8d13c7a31a96898364ef1d4b2b554c
22.857143
121
0.656672
3.768362
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Throttle.swift
14
3380
// // Throttle.swift // Rx // // Created by Krunoslav Zaher on 3/22/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ThrottleSink<O: ObserverType, Scheduler: SchedulerType> : Sink<O>, ObserverType { typealias Element = O.E typealias ParentType = Throttle<Element, Scheduler> let parent: ParentType let lock = NSRecursiveLock() // state var id = 0 as UInt64 var value: Element? = nil let cancellable = SerialDisposable() init(parent: ParentType, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = parent.source.subscribeSafe(self) return CompositeDisposable(subscription, cancellable) } func on(event: Event<Element>) { switch event { case .Next: break case .Error: fallthrough case .Completed: cancellable.dispose() break } let latestId = self.lock.calculateLocked { () -> UInt64 in let observer = self.observer let oldValue = self.value self.id = self.id &+ 1 switch event { case .Next(let element): self.value = element case .Error: self.value = nil observer?.on(event) self.dispose() case .Completed: self.value = nil if let value = oldValue { observer?.on(.Next(value)) } observer?.on(.Completed) self.dispose() } return id } switch event { case .Next(_): let d = SingleAssignmentDisposable() self.cancellable.disposable = d let scheduler = self.parent.scheduler let dueTime = self.parent.dueTime let disposeTimer = scheduler.scheduleRelative(latestId, dueTime: dueTime) { (id) in self.propagate() return NopDisposable.instance } d.disposable = disposeTimer default: break } } func propagate() { let originalValue: Element? = self.lock.calculateLocked { let originalValue = self.value self.value = nil return originalValue } if let value = originalValue { observer?.on(.Next(value)) } } } class Throttle<Element, Scheduler: SchedulerType> : Producer<Element> { let source: Observable<Element> let dueTime: Scheduler.TimeInterval let scheduler: Scheduler init(source: Observable<Element>, dueTime: Scheduler.TimeInterval, scheduler: Scheduler) { self.source = source self.dueTime = dueTime self.scheduler = scheduler } override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
gpl-3.0
60cf329040aa0f3121d8d2d4edaa5ed7
26.487805
139
0.53787
5.184049
false
false
false
false
Srinija/SwiftCamScanner
Example/SwiftCamScanner/CameraView.swift
1
5226
// // CameraView.swift // CamScanner // // Created by Srinija on 15/05/17. // Copyright © 2017 Srinija Ammapalli. All rights reserved. // import UIKit import AVFoundation import Photos class CameraView: UIView { let captureSession = AVCaptureSession() let imageOutput = AVCaptureStillImageOutput() var previewLayer: AVCaptureVideoPreviewLayer! var activeInput: AVCaptureDeviceInput! var focusMarker: UIImageView! func setupCamera(){ captureSession.sessionPreset = AVCaptureSession.Preset.high let camera = AVCaptureDevice.default(for: AVMediaType.video) do { let input = try AVCaptureDeviceInput(device: camera!) if captureSession.canAddInput(input) { captureSession.addInput(input) activeInput = input } } catch { print("Error setting device input: \(error)") } imageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(imageOutput) { captureSession.addOutput(imageOutput) } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = self.bounds previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill self.layer.addSublayer(previewLayer) let tapForFocus = UITapGestureRecognizer(target: self, action: #selector(tapToFocus(_:))) tapForFocus.numberOfTapsRequired = 1 self.addGestureRecognizer(tapForFocus) focusMarker = UIImageView(image: #imageLiteral(resourceName: "focus")) focusMarker.frame.size = CGSize(width: 100, height: 100) focusMarker.isHidden = true self.addSubview(focusMarker) if !captureSession.isRunning { videoQueue().async { self.captureSession.startRunning() } } } func videoQueue() -> DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.default) } // MARK: Focus Methods @objc func tapToFocus(_ recognizer: UIGestureRecognizer) { if activeInput.device.isFocusPointOfInterestSupported { let point = recognizer.location(in: self) let pointOfInterest = previewLayer.captureDevicePointConverted(fromLayerPoint: point) showMarkerAtPoint(point, marker: focusMarker) focusAtPoint(pointOfInterest) } } func focusAtPoint(_ point: CGPoint) { let device = activeInput.device if (device.isFocusPointOfInterestSupported) && (device.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus)) { do { try device.lockForConfiguration() device.focusPointOfInterest = point device.focusMode = AVCaptureDevice.FocusMode.autoFocus device.unlockForConfiguration() } catch { print("Error focusing on POI: \(error)") } } } func showMarkerAtPoint(_ point: CGPoint, marker: UIImageView) { marker.center = point marker.isHidden = false UIView.animate(withDuration: 0.15, delay: 0.0, options: UIViewAnimationOptions(), animations: { () -> Void in marker.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1.0) }) { (Bool) -> Void in let delay = 0.5 let popTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime, execute: { () -> Void in marker.isHidden = true marker.transform = CGAffineTransform.identity }) } } func capturePhoto(completionHandler:@escaping(_ image: UIImage?)->Void){ let connection = imageOutput.connection(with: AVMediaType.video) if (connection?.isVideoOrientationSupported)! { connection?.videoOrientation = getOrientation() } imageOutput.captureStillImageAsynchronously(from: connection!) { (sampleBuffer: CMSampleBuffer?, error: Error?) -> Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer!) let image = UIImage(data: imageData!) completionHandler(image) } else { print("Error capturing photo: \(String(describing: error?.localizedDescription))") } } } func getOrientation() -> AVCaptureVideoOrientation { var orientation: AVCaptureVideoOrientation switch UIDevice.current.orientation { case .portrait: orientation = .portrait case .landscapeRight: orientation = .landscapeLeft case .portraitUpsideDown: orientation = .portraitUpsideDown default: orientation = .landscapeRight } return orientation } }
mit
1933dd070cf8dcf2eaef3421c3720894
34.067114
113
0.606699
5.697928
false
false
false
false
lzbgithubcode/LZBPageView
LZBPageView/LZBPageView/LZBPageView/LZBTitleView.swift
1
10975
// // LZBTitleView.swift // LZBPageView // // Created by zibin on 2017/5/12. // Copyright © 2017年 项目共享githud地址:https://github.com/lzbgithubcode/LZBPageView 简书详解地址:http://www.jianshu.com/p/3170d0d886a2 作者喜欢分享技术与开发资料,如果你也是喜欢分享的人可以加入我们iOS资料demo共享群:490658347. All rights reserved. // import UIKit //用class表示只有类可以继承协议,本来不需要声明什么的 protocol LZBTitleViewDelegate : class { func titleView(_ titleView : LZBTitleView, targetIndex : NSInteger) } class LZBTitleView: UIView { weak var delegate : LZBTitleViewDelegate? fileprivate var titles : [String] fileprivate var style : LZBPageStyleModel fileprivate var currentIndex : NSInteger = 0 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var normalColor : (CGFloat, CGFloat, CGFloat) = self.style.titleViewTitleNormalColor.getRGBValue() fileprivate lazy var selectColor : (CGFloat, CGFloat, CGFloat) = self.style.titleViewTitleSelectColor.getRGBValue() //懒加载 fileprivate lazy var deltaColor : (CGFloat, CGFloat, CGFloat) = { let rdelta = self.selectColor.0 - self.normalColor.0 let gdelta = self.selectColor.1 - self.normalColor.1 let bdelta = self.selectColor.2 - self.normalColor.2 return (rdelta , gdelta , bdelta) }() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var lableMaskView : UIView = { let lableMaskView = UIView() lableMaskView.backgroundColor = self.style.maskColor return lableMaskView }() //Mark:- 构造函数 init(frame : CGRect, titles : [String], style : LZBPageStyleModel) { self.titles = titles self.style = style super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 初始化UI extension LZBTitleView { fileprivate func setupUI(){ addSubview(scrollView) setupTitles() if self.style.isShowBottomLine{ self.setupBottomLine() } if self.style.isNeedMask{ self.setupMaskView() } } private func setupBottomLine(){ scrollView.addSubview(self.bottomLine) guard let titleLabel = self.titleLabels.first else { return } bottomLine.frame = titleLabel.frame bottomLine.frame.size.height = self.style.bottomLineHeight bottomLine.frame.origin.y = bounds.height - self.style.bottomLineHeight } private func setupMaskView(){ scrollView.addSubview(self.lableMaskView) guard let titleLabel = self.titleLabels.first else { return } let maskH : CGFloat = style.maskHeight let maskY : CGFloat = (titleLabel.frame.height - maskH) * 0.5 var maskX : CGFloat = titleLabel.frame.origin.x var maskW : CGFloat = titleLabel.frame.width if self.style.isScrollEnable { maskX = maskX - self.style.maskInsetMargin maskW = maskW + self.style.maskInsetMargin * 2 } lableMaskView.layer.frame = CGRect(x: maskX, y: maskY, width: maskW, height: maskH) lableMaskView.layer.cornerRadius = style.maskLayerRadius lableMaskView.layer.masksToBounds = true } private func setupTitles(){ //1.初始化标题 let count = self.titles.count for i in 0..<count { let tilteLabel = UILabel() let title = self.titles[i] tilteLabel.tag = i tilteLabel.text = title tilteLabel.textAlignment = .center tilteLabel.textColor = i == 0 ? style.titleViewTitleSelectColor :style.titleViewTitleNormalColor tilteLabel.font = style.titleViewTitleFont tilteLabel.isUserInteractionEnabled = true scrollView.addSubview(tilteLabel) titleLabels.append(tilteLabel) //增加手势 let tapGester = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:))) tilteLabel.addGestureRecognizer(tapGester) } //2.布局frame var titleLabX : CGFloat = 0 let titleLabY : CGFloat = 0 var titleLabW : CGFloat = bounds.width/CGFloat(count) let titleLabH : CGFloat = style.titleViewHeight for (i, titleLabel) in titleLabels.enumerated() { if style.isScrollEnable //可以滚动 { titleLabW = (titleLabel.text! as NSString).size(attributes: [NSFontAttributeName : titleLabel.font]).width //计算位置 titleLabX = i == 0 ? style.titleViewMargin : titleLabels[i-1].frame.maxX + style.titleViewMargin } else //不可以滚动 { titleLabX = titleLabW * CGFloat(i) } titleLabel.frame = CGRect(x: titleLabX, y: titleLabY, width: titleLabW, height: titleLabH) } //3.设置contensize if style.isScrollEnable{ self.scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleViewMargin, height: 0) } else{ self.scrollView.contentSize = CGSize(width: scrollView.bounds.width, height: 0) } //4、设置初始位置方法 if self.style.isNeedScale{ guard let titleLabel = titleLabels.first else { return } titleLabel.transform = CGAffineTransform(scaleX: self.style.maxScale, y: self.style.maxScale) } } } //MARK:-监听标题点击 extension LZBTitleView { @objc fileprivate func titleLabelClick(_ tapGester : UITapGestureRecognizer){ //1.检验lable 是否为nil guard let targetLabel = tapGester.view as? UILabel else{ return } guard targetLabel.tag != currentIndex else { return } //2.选中三部曲 let lastLabel = self.titleLabels[currentIndex] lastLabel.textColor = style.titleViewTitleNormalColor targetLabel.textColor = style.titleViewTitleSelectColor currentIndex = targetLabel.tag //3.调整到中心位置 self.adjustTargetOffset() //4.调用代理 delegate?.titleView(self, targetIndex: currentIndex) //5.点击滚动下滑线 if self.style.isShowBottomLine { UIView.animate(withDuration: 0.25, animations: { self.bottomLine.frame.size.width = targetLabel.frame.width self.bottomLine.frame.origin.x = targetLabel.frame.origin.x }) } //6.点击放大字体 if self.style.isNeedScale { UIView.animate(withDuration: 0.25, animations: { lastLabel.transform = CGAffineTransform.identity targetLabel.transform = CGAffineTransform(scaleX: self.style.maxScale, y: self.style.maxScale) }) } //7.点击mask滚动 if self.style.isNeedMask { UIView.animate(withDuration: 0.25, animations: { self.lableMaskView.frame.size.width = self.style.isScrollEnable ? targetLabel.frame.width + 2 * self.style.maskInsetMargin : targetLabel.frame.width self.lableMaskView.frame.origin.x = self.style.isScrollEnable ? targetLabel.frame.origin.x - self.style.maskInsetMargin : targetLabel.frame.origin.x }) } } //调整位置 func adjustTargetOffset(){ let targetLabel = self.titleLabels[currentIndex] var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5 if offsetX < 0{ offsetX = 0 } let maxOffsetX = self.scrollView.contentSize.width - scrollView.bounds.width if offsetX > maxOffsetX{ offsetX = maxOffsetX } scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } //MARK:- 遵守LZBContentViewDelegate协议 extension LZBTitleView : LZBContentViewDelegate{ func contentView(contentView: LZBContentView, didScrollEnd index: Int) { guard index <= self.titleLabels.count else { return } currentIndex = index self.adjustTargetOffset() } func contentView(contentView: LZBContentView, soureIndex: Int, targetIndex: Int, progress: CGFloat) { //1.获取变化的label let soureLabel = self.titleLabels[soureIndex] let targetLabel = self.titleLabels[targetIndex] //2.颜色渐变 soureLabel.textColor = UIColor(r: (self.selectColor.0 - deltaColor.0) * progress, g: (self.selectColor.1 - deltaColor.1) * progress, b: (self.selectColor.2 - deltaColor.2) * progress) targetLabel.textColor = UIColor(r: (self.normalColor.0 + deltaColor.0) * progress, g: (self.normalColor.1 + deltaColor.1) * progress, b: (self.normalColor.2 + deltaColor.2) * progress) //4.拖动contentView,改变字体大小 if self.style.isNeedScale { let deltaScale = self.style.maxScale - 1.0 soureLabel.transform = CGAffineTransform(scaleX: self.style.maxScale - deltaScale * progress, y: self.style.maxScale - deltaScale * progress) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + deltaScale * progress, y: 1.0 + deltaScale * progress) } let deltaWidth = targetLabel.frame.width - soureLabel.frame.width let deltaX = targetLabel.frame.origin.x - soureLabel.frame.origin.x //3.拖动contentView,下划线渐变 if self.style.isShowBottomLine { bottomLine.frame.size.width = soureLabel.frame.width + deltaWidth * progress bottomLine.frame.origin.x = soureLabel.frame.origin.x + deltaX * progress } //4.拖动contenView,mask渐变 if self.style.isNeedMask { self.lableMaskView.frame.size.width = self.style.isScrollEnable ? soureLabel.frame.width + 2 * self.style.maskInsetMargin + deltaWidth * progress : soureLabel.frame.width + deltaWidth * progress self.lableMaskView.frame.origin.x = self.style.isScrollEnable ? soureLabel.frame.origin.x - self.style.maskInsetMargin + deltaX * progress : soureLabel.frame.origin.x + deltaX * progress } } }
apache-2.0
fead8b372d05fc55e1464e9970aed7ab
35.829268
206
0.632356
4.333743
false
false
false
false
nissivm/DemoShop
Demo Shop/View Controllers/ShoppingCart_VC.swift
1
23485
// // ShoppingCart_VC.swift // Demo Shop // // Created by Nissi Vieira Miranda on 1/14/16. // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import UIKit protocol ShoppingCart_VC_Delegate: class { func shoppingCartItemsListChanged(cartItems: [ShoppingCartItem]) } class ShoppingCart_VC: UIViewController, UITableViewDataSource, UITableViewDelegate, PKPaymentAuthorizationViewControllerDelegate, ShoppingCartItemCellDelegate, CardPayment_VC_Delegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var valueToPayLabel: UILabel! @IBOutlet weak var freeShippingBlueRect: UIView! @IBOutlet weak var pacBlueRect: UIView! @IBOutlet weak var sedexBlueRect: UIView! @IBOutlet weak var shopLogo: UIImageView! @IBOutlet weak var shopName: UILabel! @IBOutlet weak var shoppingCartImage: UIImageView! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var optionsSatckViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var valueToPayViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var buttonsSatckViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var shippingOptionsStackView: UIStackView! @IBOutlet weak var checkoutButton: UIButton! @IBOutlet weak var keepShoppingButton: UIButton! weak var delegate: ShoppingCart_VC_Delegate? let backend = Backend() let shippingMethods = ShippingMethods() var multiplier: CGFloat = 1 // Received from Products_VC: var shoppingCartItems: [ShoppingCartItem]! var valueToPay: CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil) if Device.IS_IPHONE_6 { multiplier = Constants.multiplier6 adjustForBiggerScreen() } else if Device.IS_IPHONE_6_PLUS { multiplier = Constants.multiplier6plus adjustForBiggerScreen() } else { calculateTableViewHeightConstraint() } let totalPurchase = totalPurchaseItemsValue() let methods = shippingMethods.availableShippingMethods() let shippingValue = methods[0].amount valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //-------------------------------------------------------------------------// // MARK: Notifications //-------------------------------------------------------------------------// func willEnterForeground() { let isTopVC = navigationController!.topViewController!.isKindOfClass(ShoppingCart_VC) if isTopVC { if Auxiliar.sessionIsValid() == false { navigationController!.popToRootViewControllerAnimated(true) } } } //-------------------------------------------------------------------------// // MARK: IBActions //-------------------------------------------------------------------------// @IBAction func shippingMethodButtonTapped(sender: UIButton) { let idx = sender.tag - 10 resetShippingMethod(idx) } var request: PKPaymentRequest! var paymentController: PKPaymentAuthorizationViewController! @IBAction func checkoutButtonTapped(sender: UIButton) { let shippingValue = valueToPay - totalPurchaseItemsValue() let idx = currentShippingMethodIndex(shippingValue) request = Stripe.paymentRequestWithMerchantIdentifier(Constants.appleMerchantId)! request.shippingMethods = shippingMethods.availablePKShippingMethods() request.paymentSummaryItems = summaryItemsForShippingMethod(request.shippingMethods![idx]) let supportedPaymentNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex] let supportsApplePay = PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(supportedPaymentNetworks) if supportsApplePay { showPaymentOptions() } else { performSegueWithIdentifier("ToCardPayment", sender: self) } } @IBAction func keepShoppingButtonTapped(sender: UIButton) { navigationController!.popViewControllerAnimated(true) } //-------------------------------------------------------------------------// // MARK: UITableViewDataSource //-------------------------------------------------------------------------// func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shoppingCartItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ShoppingCartItemCell", forIndexPath: indexPath) as! ShoppingCartItemCell cell.delegate = self cell.setupCellWithItem(shoppingCartItems[indexPath.row]) return cell } //-------------------------------------------------------------------------// // MARK: UITableViewDelegate //-------------------------------------------------------------------------// func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var starterCellHeight: CGFloat = 110 if Device.IS_IPHONE_6 { starterCellHeight = 100 } if Device.IS_IPHONE_6_PLUS { starterCellHeight = 90 } return starterCellHeight * multiplier } //-------------------------------------------------------------------------// // MARK: ShoppingCartItemCellDelegate //-------------------------------------------------------------------------// func amountForItemChanged(clickedItemId: String, newAmount: Int) { var totalPurchase = totalPurchaseItemsValue() let shippingValue = valueToPay - totalPurchase let idx = findOutCartItemIndex(clickedItemId) let item = shoppingCartItems[idx] item.amount = newAmount shoppingCartItems[idx] = item totalPurchase = totalPurchaseItemsValue() valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" delegate!.shoppingCartItemsListChanged(shoppingCartItems) } func removeItem(clickedItemId: String) { var totalPurchase = totalPurchaseItemsValue() let shippingValue = valueToPay - totalPurchase let idx = findOutCartItemIndex(clickedItemId) shoppingCartItems.removeAtIndex(idx) delegate!.shoppingCartItemsListChanged(shoppingCartItems) if shoppingCartItems.count == 0 { navigationController!.popViewControllerAnimated(true) } else { tableView.beginUpdates() let indexPaths = [NSIndexPath(forRow: idx, inSection: 0)] tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Left) tableView.endUpdates() totalPurchase = totalPurchaseItemsValue() valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" calculateTableViewHeightConstraint() } } //-------------------------------------------------------------------------// // MARK: CardPayment_VC_Delegate //-------------------------------------------------------------------------// func clearShoppingCart() { shoppingCartItems.removeAll() delegate!.shoppingCartItemsListChanged(shoppingCartItems) } //-------------------------------------------------------------------------// // MARK: PKPaymentAuthorizationViewControllerDelegate //-------------------------------------------------------------------------// // Executed when you click "Pay with Passcode": func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: (PKPaymentAuthorizationStatus) -> Void) { dismissViewControllerAnimated(true, completion: nil) Auxiliar.showLoadingHUDWithText("Processing payment, please wait...", forView: self.view) guard Reachability.connectedToNetwork() else { Auxiliar.hideLoadingHUDInView(self.view) Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) completion(PKPaymentAuthorizationStatus.Failure) return } STPAPIClient.sharedClient().createTokenWithPayment(payment) { [unowned self](token, error) -> Void in guard error == nil else { Auxiliar.hideLoadingHUDInView(self.view) Auxiliar.presentAlertControllerWithTitle("Failure", andMessage: "Error while processing payment, please try again.", forViewController: self) print("Error = \(error)") completion(PKPaymentAuthorizationStatus.Failure) return } guard token != nil else { Auxiliar.hideLoadingHUDInView(self.view) Auxiliar.presentAlertControllerWithTitle("Failure", andMessage: "Error while processing payment, please try again.", forViewController: self) completion(PKPaymentAuthorizationStatus.Failure) return } self.backend.token = token! self.backend.shoppingCartItems = self.shoppingCartItems self.backend.shippingMethod = self.getChoosenShippingMethod() self.backend.valueToPay = self.valueToPay self.backend.processPayment({ [unowned self](status, message) in Auxiliar.hideLoadingHUDInView(self.view) if status == "Success" { self.promptUserForSuccessfulPayment(status, message: message) completion(PKPaymentAuthorizationStatus.Success) return } Auxiliar.presentAlertControllerWithTitle(status, andMessage: message, forViewController: self) completion(PKPaymentAuthorizationStatus.Failure) }) } } func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didSelectShippingMethod shippingMethod: PKShippingMethod, completion: (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) { let idx = currentShippingMethodIndex(CGFloat(shippingMethod.amount)) resetShippingMethod(idx) completion(PKPaymentAuthorizationStatus.Success, summaryItemsForShippingMethod(shippingMethod)) } // Executed when you click "Cancel": func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController) { dismissViewControllerAnimated(true, completion: nil) } //-------------------------------------------------------------------------// // MARK: PKPaymentSummaryItem //-------------------------------------------------------------------------// func summaryItemsForShippingMethod(shippingMethod: PKShippingMethod) -> [PKPaymentSummaryItem] { var cartItems = gatherSummaryItems() let decimal = NSDecimalNumber(float: Float(valueToPay)) let total = PKPaymentSummaryItem(label: "Total: ", amount: decimal) cartItems.append(shippingMethod) cartItems.append(total) return cartItems } func gatherSummaryItems() -> [PKPaymentSummaryItem] { var items = [PKPaymentSummaryItem]() for item in shoppingCartItems { let name = item.itemForSale.itemName let unityPrice = item.itemForSale.itemPrice let totalPrice = Float(unityPrice * CGFloat(item.amount)) let decimal = NSDecimalNumber(float: totalPrice) items.append(PKPaymentSummaryItem(label: "\(item.amount) x \(name)", amount: decimal)) } return items } //-------------------------------------------------------------------------// // MARK: Show payment options //-------------------------------------------------------------------------// func showPaymentOptions() { let paymentOptions = UIAlertController(title: "Payment Options", message: "I'll pay using:", preferredStyle: .ActionSheet) let applePay = UIAlertAction(title: "Apple Pay", style: .Default, handler: { [unowned self](alert: UIAlertAction!) -> Void in self.paymentController = PKPaymentAuthorizationViewController(paymentRequest: self.request) self.paymentController.delegate = self self.presentViewController(self.paymentController, animated: true, completion: nil) }) let creditCard = UIAlertAction(title: "Credit Card", style: .Default, handler: { [unowned self](alert: UIAlertAction!) -> Void in self.performSegueWithIdentifier("ToCardPayment", sender: self) }) let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in }) paymentOptions.addAction(applePay) paymentOptions.addAction(creditCard) paymentOptions.addAction(cancel) presentViewController(paymentOptions, animated: true, completion: nil) } //-------------------------------------------------------------------------// // MARK: Prompt user for successful payment //-------------------------------------------------------------------------// func promptUserForSuccessfulPayment(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Ok", style: .Default) { [unowned self](action: UIAlertAction!) -> Void in self.shoppingCartItems.removeAll() self.delegate!.shoppingCartItemsListChanged(self.shoppingCartItems) self.navigationController!.popToRootViewControllerAnimated(true) } alert.addAction(saveAction) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alert, animated: true, completion: nil) } } //-------------------------------------------------------------------------// // MARK: Auxiliar functions //-------------------------------------------------------------------------// func findOutCartItemIndex(clickedItemId: String) -> Int { var idx = 0 for (index, item) in shoppingCartItems.enumerate() { if item.itemForSale.id == clickedItemId { idx = index break } } return idx } func currentShippingMethodIndex(shippingValue: CGFloat) -> Int { let methods = shippingMethods.availableShippingMethods() var idx = 0 for (index, method) in methods.enumerate() { if method.amount == shippingValue { idx = index break } } return idx } func resetShippingMethod(idx: Int) { let totalPurchase = totalPurchaseItemsValue() let methods = shippingMethods.availableShippingMethods() let method = methods[idx] let shippingValue = method.amount valueToPay = totalPurchase + shippingValue let value: NSString = NSString(format: "%.02f", valueToPay) valueToPayLabel.text = "Total: $\(value)" freeShippingBlueRect.alpha = 0.4 pacBlueRect.alpha = 0.4 sedexBlueRect.alpha = 0.4 switch idx { case 0: freeShippingBlueRect.alpha = 1 case 1: pacBlueRect.alpha = 1 case 2: sedexBlueRect.alpha = 1 default: print("Unknown") } } func totalPurchaseItemsValue() -> CGFloat { var totalValue: CGFloat = 0 for item in shoppingCartItems { let unityPrice = item.itemForSale.itemPrice let total = unityPrice * CGFloat(item.amount) totalValue += total } return totalValue } func getChoosenShippingMethod() -> ShippingMethod { let methods = shippingMethods.availableShippingMethods() var idx = 0 if pacBlueRect.alpha == 1 { idx = 1 } else if sedexBlueRect.alpha == 1 { idx = 2 } return methods[idx] } //-------------------------------------------------------------------------// // MARK: Ajust for bigger screen //-------------------------------------------------------------------------// func adjustForBiggerScreen() { for constraint in shopLogo.constraints { constraint.constant *= multiplier } for constraint in shopName.constraints { constraint.constant *= multiplier } for constraint in shoppingCartImage.constraints { constraint.constant *= multiplier } for subview in shippingOptionsStackView.subviews { for (index, subV) in subview.subviews.enumerate() { if index > 0 { for constraint in subV.constraints { constraint.constant *= multiplier } if index == 1 { let fontSize = 14 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue", size: fontSize) } if index == 2 { let fontSize = 12 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue", size: fontSize) } if index == 3 { let fontSize = 15 * multiplier let label = subV as! UILabel label.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) } } } } for constraint in valueToPayLabel.constraints { constraint.constant *= multiplier } headerHeightConstraint.constant *= multiplier optionsSatckViewHeightConstraint.constant *= multiplier valueToPayViewHeightConstraint.constant *= multiplier buttonsSatckViewHeightConstraint.constant *= multiplier calculateTableViewHeightConstraint() var fontSize = 25.0 * multiplier shopName.font = UIFont(name: "HelveticaNeue", size: fontSize) fontSize = 17.0 * multiplier checkoutButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) keepShoppingButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) fontSize = 15.0 * multiplier valueToPayLabel.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) } //-------------------------------------------------------------------------// // MARK: Calculate TableView Height Constraint //-------------------------------------------------------------------------// func calculateTableViewHeightConstraint() { let space = self.view.frame.size.height - (headerHeightConstraint.constant + optionsSatckViewHeightConstraint.constant + valueToPayViewHeightConstraint.constant + buttonsSatckViewHeightConstraint.constant) var starterCellHeight: CGFloat = 110 if Device.IS_IPHONE_6 { starterCellHeight = 100 } if Device.IS_IPHONE_6_PLUS { starterCellHeight = 90 } let cellsTotalHeight = (starterCellHeight * multiplier) * CGFloat(shoppingCartItems.count) let tvHeight = cellsTotalHeight < space ? cellsTotalHeight : space tableViewHeightConstraint.constant = tvHeight } //-------------------------------------------------------------------------// // MARK: Navigation //-------------------------------------------------------------------------// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let vc = segue.destinationViewController as! CardPayment_VC vc.shoppingCartItems = shoppingCartItems vc.shippingMethod = getChoosenShippingMethod() vc.valueToPay = valueToPay vc.delegate = self } //-------------------------------------------------------------------------// // MARK: Memory Warning //-------------------------------------------------------------------------// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
8924d7313db3fde81fd82c40d106e47d
34.36747
184
0.530106
6.480132
false
false
false
false
nathawes/swift
stdlib/public/core/SetVariant.swift
9
10168
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// This protocol is only used for compile-time checks that /// every buffer type implements all required operations. internal protocol _SetBuffer { associatedtype Element associatedtype Index var startIndex: Index { get } var endIndex: Index { get } func index(after i: Index) -> Index func index(for element: Element) -> Index? var count: Int { get } func contains(_ member: Element) -> Bool func element(at i: Index) -> Element } extension Set { @usableFromInline @frozen internal struct _Variant { @usableFromInline internal var object: _BridgeStorage<__RawSetStorage> @inlinable @inline(__always) init(dummy: ()) { #if arch(i386) || arch(arm) || arch(wasm32) self.init(native: _NativeSet()) #else self.object = _BridgeStorage(taggedPayload: 0) #endif } @inlinable @inline(__always) init(native: __owned _NativeSet<Element>) { self.object = _BridgeStorage(native: native._storage) } #if _runtime(_ObjC) @inlinable @inline(__always) init(cocoa: __owned __CocoaSet) { self.object = _BridgeStorage(objC: cocoa.object) } #endif } } extension Set._Variant { #if _runtime(_ObjC) @usableFromInline @_transparent internal var guaranteedNative: Bool { return _canBeClass(Element.self) == 0 } #endif @inlinable internal mutating func isUniquelyReferenced() -> Bool { return object.isUniquelyReferencedUnflaggedNative() } #if _runtime(_ObjC) @usableFromInline @_transparent internal var isNative: Bool { if guaranteedNative { return true } return object.isUnflaggedNative } #endif @usableFromInline @_transparent internal var asNative: _NativeSet<Element> { get { return _NativeSet(object.unflaggedNativeInstance) } set { self = .init(native: newValue) } _modify { var native = _NativeSet<Element>(object.unflaggedNativeInstance) self = .init(dummy: ()) defer { // This is in a defer block because yield might throw, and we need to // preserve Set's storage invariants when that happens. object = .init(native: native._storage) } yield &native } } #if _runtime(_ObjC) @inlinable internal var asCocoa: __CocoaSet { return __CocoaSet(object.objCInstance) } #endif /// Reserves enough space for the specified number of elements to be stored /// without reallocating additional storage. internal mutating func reserveCapacity(_ capacity: Int) { #if _runtime(_ObjC) guard isNative else { let cocoa = asCocoa let capacity = Swift.max(cocoa.count, capacity) self = .init(native: _NativeSet(cocoa, capacity: capacity)) return } #endif let isUnique = isUniquelyReferenced() asNative.reserveCapacity(capacity, isUnique: isUnique) } /// The number of elements that can be stored without expanding the current /// storage. /// /// For bridged storage, this is equal to the current count of the /// collection, since any addition will trigger a copy of the elements into /// newly allocated storage. For native storage, this is the element count /// at which adding any more elements will exceed the load factor. @inlinable internal var capacity: Int { #if _runtime(_ObjC) guard isNative else { return asCocoa.count } #endif return asNative.capacity } } extension Set._Variant: _SetBuffer { @usableFromInline internal typealias Index = Set<Element>.Index @inlinable internal var startIndex: Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.startIndex) } #endif return asNative.startIndex } @inlinable internal var endIndex: Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.endIndex) } #endif return asNative.endIndex } @inlinable internal func index(after index: Index) -> Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.index(after: index._asCocoa)) } #endif return asNative.index(after: index) } @inlinable internal func formIndex(after index: inout Index) { #if _runtime(_ObjC) guard isNative else { let isUnique = index._isUniquelyReferenced() asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique) return } #endif index = asNative.index(after: index) } @inlinable @inline(__always) internal func index(for element: Element) -> Index? { #if _runtime(_ObjC) guard isNative else { let cocoaElement = _bridgeAnythingToObjectiveC(element) guard let index = asCocoa.index(for: cocoaElement) else { return nil } return Index(_cocoa: index) } #endif return asNative.index(for: element) } @inlinable internal var count: Int { @inline(__always) get { #if _runtime(_ObjC) guard isNative else { return asCocoa.count } #endif return asNative.count } } @inlinable @inline(__always) internal func contains(_ member: Element) -> Bool { #if _runtime(_ObjC) guard isNative else { return asCocoa.contains(_bridgeAnythingToObjectiveC(member)) } #endif return asNative.contains(member) } @inlinable @inline(__always) internal func element(at index: Index) -> Element { #if _runtime(_ObjC) guard isNative else { let cocoaMember = asCocoa.element(at: index._asCocoa) return _forceBridgeFromObjectiveC(cocoaMember, Element.self) } #endif return asNative.element(at: index) } } extension Set._Variant { @inlinable internal mutating func update(with value: __owned Element) -> Element? { #if _runtime(_ObjC) guard isNative else { // Make sure we have space for an extra element. var native = _NativeSet<Element>(asCocoa, capacity: asCocoa.count + 1) let old = native.update(with: value, isUnique: true) self = .init(native: native) return old } #endif let isUnique = self.isUniquelyReferenced() return asNative.update(with: value, isUnique: isUnique) } @inlinable internal mutating func insert( _ element: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) { #if _runtime(_ObjC) guard isNative else { // Make sure we have space for an extra element. let cocoaMember = _bridgeAnythingToObjectiveC(element) let cocoa = asCocoa if let m = cocoa.member(for: cocoaMember) { return (false, _forceBridgeFromObjectiveC(m, Element.self)) } var native = _NativeSet<Element>(cocoa, capacity: cocoa.count + 1) native.insertNew(element, isUnique: true) self = .init(native: native) return (true, element) } #endif let (bucket, found) = asNative.find(element) if found { return (false, asNative.uncheckedElement(at: bucket)) } let isUnique = self.isUniquelyReferenced() asNative.insertNew(element, at: bucket, isUnique: isUnique) return (true, element) } @inlinable @discardableResult internal mutating func remove(at index: Index) -> Element { #if _runtime(_ObjC) guard isNative else { // We have to migrate the data first. But after we do so, the Cocoa // index becomes useless, so get the element first. let cocoa = asCocoa let cocoaMember = cocoa.member(for: index._asCocoa) let nativeMember = _forceBridgeFromObjectiveC(cocoaMember, Element.self) return _migrateToNative(cocoa, removing: nativeMember) } #endif let isUnique = isUniquelyReferenced() let bucket = asNative.validatedBucket(for: index) return asNative.uncheckedRemove(at: bucket, isUnique: isUnique) } @inlinable @discardableResult internal mutating func remove(_ member: Element) -> Element? { #if _runtime(_ObjC) guard isNative else { let cocoa = asCocoa let cocoaMember = _bridgeAnythingToObjectiveC(member) guard cocoa.contains(cocoaMember) else { return nil } return _migrateToNative(cocoa, removing: member) } #endif let (bucket, found) = asNative.find(member) guard found else { return nil } let isUnique = isUniquelyReferenced() return asNative.uncheckedRemove(at: bucket, isUnique: isUnique) } #if _runtime(_ObjC) @inlinable internal mutating func _migrateToNative( _ cocoa: __CocoaSet, removing member: Element ) -> Element { // FIXME(performance): fuse data migration and element deletion into one // operation. var native = _NativeSet<Element>(cocoa) let (bucket, found) = native.find(member) _precondition(found, "Bridging did not preserve equality") let old = native.uncheckedRemove(at: bucket, isUnique: true) _precondition(member == old, "Bridging did not preserve equality") self = .init(native: native) return old } #endif @inlinable internal mutating func removeAll(keepingCapacity keepCapacity: Bool) { if !keepCapacity { self = .init(native: _NativeSet<Element>()) return } guard count > 0 else { return } #if _runtime(_ObjC) guard isNative else { self = .init(native: _NativeSet(capacity: asCocoa.count)) return } #endif let isUnique = isUniquelyReferenced() asNative.removeAll(isUnique: isUnique) } } extension Set._Variant { /// Returns an iterator over the elements. /// /// - Complexity: O(1). @inlinable @inline(__always) internal __consuming func makeIterator() -> Set<Element>.Iterator { #if _runtime(_ObjC) guard isNative else { return Set.Iterator(_cocoa: asCocoa.makeIterator()) } #endif return Set.Iterator(_native: asNative.makeIterator()) } }
apache-2.0
93f8418a7a79dd2bbb7d217ea1a7dbdd
26.481081
80
0.665323
4.167213
false
false
false
false
Cessation/even.tr
eventr/Event.swift
1
2465
// // Event.swift // eventr // // Created by Clayton Petty on 3/23/16. // Copyright © 2016 cessation. All rights reserved. // import UIKit import Parse class Event: NSObject { var title: String? var desc: NSString? var startDate: String? var startTime: String? var endTime: String? var endDate: String? var picture: PFFile? var hashtags: [NSString]? var author: NSString var id: NSString var attendees: [String]? var location: String? init(dictionary: NSDictionary) { // Event Title title = dictionary["title"] as? String // Event Description desc = dictionary["description"] as? String // Start time // let timestampString = dictionary["start_time"] as? String // if let timestampString = timestampString { // let formatter = NSDateFormatter() // formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" // timestamp = formatter.dateFromString(timestampString) // } // End time // let timestampString = dictionary["end_time"] as? String // if let timestampString = timestampString { // let formatter = NSDateFormatter() // formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" // timestamp = formatter.dateFromString(timestampString) // } // Picture picture = dictionary["picture"] as? PFFile // Hashtags hashtags = dictionary["hashtags"] as? [String] // Author author = dictionary["author"] as! String // Event Id id = dictionary["id"] as! String startDate = dictionary["startDate"] as? String startTime = dictionary["startTime"] as? String endDate = dictionary["endDate"] as? String endTime = dictionary["endTime"] as? String //list of attendees by their key // the number of attendees can be found with this attendees = dictionary["attendees"] as? [String] //email address of fuckers attending location = dictionary["location"] as? String } class func eventsFromArray(dictionaries: [NSDictionary]) -> [Event] { var events = [Event]() for dictionary in dictionaries { let event = Event(dictionary: dictionary) events.append(event) } return events } }
apache-2.0
73d36401cbba634379d255e9e966ff2f
27.988235
93
0.577922
4.793774
false
false
false
false
4taras4/totp-auth
TOTP/ViperModules/AddFolderItems/Module/Presenter/AddFolderItemsPresenter.swift
1
2650
// // AddFolderItemsAddFolderItemsPresenter.swift // TOTP // // Created by Tarik on 15/02/2021. // Copyright © 2021 Taras Markevych. All rights reserved. // import UIKit import RealmSwift final class AddFolderItemsPresenter: NSObject , AddFolderItemsViewOutput { // MARK: - // MARK: Properties weak var view: AddFolderItemsViewInput! var interactor: AddFolderItemsInteractorInput! var router: AddFolderItemsRouterInput! var allAccounts: List<User>? var selectedAccounts: List<User>? var folderName = "" // MARK: - // MARK: AddFolderItemsViewOutput func viewIsReady() { view.reloadTable() } } // MARK: - // MARK: AddFolderItemsInteractorOutput extension AddFolderItemsPresenter: AddFolderItemsInteractorOutput { func updatedSelected(list: List<User>) { selectedAccounts = list view.reloadTable() } func getAllAccounts(list: List<User>?) { allAccounts = list } func getAccountsError(error: Error) { view.showError(error: error) } } // MARK: - // MARK: AddFolderItemsModuleInput extension AddFolderItemsPresenter: AddFolderItemsModuleInput, UITableViewDelegate, UITableViewDataSource { func addItemsFor(folder: Folder) { folderName = folder.name selectedAccounts = folder.codes if selectedAccounts == nil { selectedAccounts = List<User>() } interactor.getAllAccounts() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allAccounts?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AccountItemCell", for: indexPath) guard let item = allAccounts?[indexPath.row] , let selected = selectedAccounts else { return cell } cell.textLabel?.text = item.name cell.detailTextLabel?.text = item.issuer if selected.contains(item) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let item = allAccounts?[indexPath.row], let selected = selectedAccounts { interactor.addOrRemove(item: item, for: selected) } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Constants.text.addItemsToFolderHeader1 + "\(folderName)" + Constants.text.addItemsToFolderHeader2 } }
mit
50ea7ad70b0d7b5f349f06cb1d5ae1d3
30.915663
112
0.671952
4.747312
false
false
false
false
sschiau/swift
stdlib/public/core/KeyPath.swift
2
131614
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal func _abstract( methodName: StaticString = #function, file: StaticString = #file, line: UInt = #line ) -> Never { #if INTERNAL_CHECKS_ENABLED _fatalErrorMessage("abstract method", methodName, file: file, line: line, flags: _fatalErrorFlags()) #else _conditionallyUnreachable() #endif } // MARK: Type-erased abstract base classes // NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for // Swift._AnyKeyPath. @_objcRuntimeName(_TtCs11_AnyKeyPath) /// A type-erased key path, from any root type to any resulting value /// type. public class AnyKeyPath: Hashable, _AppendKeyPath { /// The root type for this key path. @inlinable public static var rootType: Any.Type { return _rootAndValueType.root } /// The value type for this key path. @inlinable public static var valueType: Any.Type { return _rootAndValueType.value } internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>? /// The hash value. final public var hashValue: Int { return _hashValue(for: self) } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @_effects(releasenone) final public func hash(into hasher: inout Hasher) { ObjectIdentifier(type(of: self)).hash(into: &hasher) return withBuffer { var buffer = $0 if buffer.data.isEmpty { return } while true { let (component, type) = buffer.next() hasher.combine(component.value) if let type = type { hasher.combine(unsafeBitCast(type, to: Int.self)) } else { break } } } } public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool { // Fast-path identical objects if a === b { return true } // Short-circuit differently-typed key paths if type(of: a) != type(of: b) { return false } return a.withBuffer { var aBuffer = $0 return b.withBuffer { var bBuffer = $0 // Two equivalent key paths should have the same reference prefix if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix { return false } // Identity is equal to identity if aBuffer.data.isEmpty { return bBuffer.data.isEmpty } while true { let (aComponent, aType) = aBuffer.next() let (bComponent, bType) = bBuffer.next() if aComponent.header.endOfReferencePrefix != bComponent.header.endOfReferencePrefix || aComponent.value != bComponent.value || aType != bType { return false } if aType == nil { return true } } } } } // SPI for the Foundation overlay to allow interop with KVC keypath-based // APIs. public var _kvcKeyPathString: String? { guard let ptr = _kvcKeyPathStringPtr else { return nil } return String(validatingUTF8: ptr) } // MARK: Implementation details // Prevent normal initialization. We use tail allocation via // allocWithTailElems(). internal init() { _internalInvariantFailure("use _create(...)") } @usableFromInline internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) { _abstract() } internal static func _create( capacityInBytes bytes: Int, initializedBy body: (UnsafeMutableRawBufferPointer) -> Void ) -> Self { _internalInvariant(bytes > 0 && bytes % 4 == 0, "capacity must be multiple of 4 bytes") let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue, Int32.self) result._kvcKeyPathStringPtr = nil let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result, Int32.self)) body(UnsafeMutableRawBufferPointer(start: base, count: bytes)) return result } internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T { defer { _fixLifetime(self) } let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self)) return try f(KeyPathBuffer(base: base)) } @usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:) internal var _storedInlineOffset: Int? { return withBuffer { var buffer = $0 // The identity key path is effectively a stored keypath of type Self // at offset zero if buffer.data.isEmpty { return 0 } var offset = 0 while true { let (rawComponent, optNextType) = buffer.next() switch rawComponent.header.kind { case .struct: offset += rawComponent._structOrClassOffset case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external: return .none } if optNextType == nil { return .some(offset) } } } } } /// A partially type-erased key path, from a concrete root type to any /// resulting value type. public class PartialKeyPath<Root>: AnyKeyPath { } // MARK: Concrete implementations internal enum KeyPathKind { case readOnly, value, reference } /// A key path from a specific root type to a specific resulting value type. public class KeyPath<Root, Value>: PartialKeyPath<Root> { @usableFromInline internal final override class var _rootAndValueType: ( root: Any.Type, value: Any.Type ) { return (Root.self, Value.self) } // MARK: Implementation internal typealias Kind = KeyPathKind internal class var kind: Kind { return .readOnly } internal static func appendedType<AppendedValue>( with t: KeyPath<Value, AppendedValue>.Type ) -> KeyPath<Root, AppendedValue>.Type { let resultKind: Kind switch (self.kind, t.kind) { case (_, .reference): resultKind = .reference case (let x, .value): resultKind = x default: resultKind = .readOnly } switch resultKind { case .readOnly: return KeyPath<Root, AppendedValue>.self case .value: return WritableKeyPath.self case .reference: return ReferenceWritableKeyPath.self } } @usableFromInline internal final func _projectReadOnly(from root: Root) -> Value { // TODO: For perf, we could use a local growable buffer instead of Any var curBase: Any = root return withBuffer { var buffer = $0 if buffer.data.isEmpty { return unsafeBitCast(root, to: Value.self) } while true { let (rawComponent, optNextType) = buffer.next() let valueType = optNextType ?? Value.self let isLast = optNextType == nil func project<CurValue>(_ base: CurValue) -> Value? { func project2<NewValue>(_: NewValue.Type) -> Value? { switch rawComponent._projectReadOnly(base, to: NewValue.self, endingWith: Value.self) { case .continue(let newBase): if isLast { _internalInvariant(NewValue.self == Value.self, "key path does not terminate in correct type") return unsafeBitCast(newBase, to: Value.self) } else { curBase = newBase return nil } case .break(let result): return result } } return _openExistential(valueType, do: project2) } if let result = _openExistential(curBase, do: project) { return result } } } } deinit { withBuffer { $0.destroy() } } } /// A key path that supports reading from and writing to the resulting value. public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> { // MARK: Implementation detail internal override class var kind: Kind { return .value } // `base` is assumed to be undergoing a formal access for the duration of the // call, so must not be mutated by an alias @usableFromInline internal func _projectMutableAddress(from base: UnsafePointer<Root>) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var p = UnsafeRawPointer(base) var type: Any.Type = Root.self var keepAlive: AnyObject? return withBuffer { var buffer = $0 _internalInvariant(!buffer.hasReferencePrefix, "WritableKeyPath should not have a reference prefix") if buffer.data.isEmpty { return ( UnsafeMutablePointer<Value>( mutating: p.assumingMemoryBound(to: Value.self)), nil) } while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent._projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == UnsafeRawPointer(base), keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(type, do: project) if optNextType == nil { break } type = nextType } // TODO: With coroutines, it would be better to yield here, so that // we don't need the hack of the keepAlive reference to manage closing // accesses. let typedPointer = p.assumingMemoryBound(to: Value.self) return (pointer: UnsafeMutablePointer(mutating: typedPointer), owner: keepAlive) } } } /// A key path that supports reading from and writing to the resulting value /// with reference semantics. public class ReferenceWritableKeyPath< Root, Value >: WritableKeyPath<Root, Value> { // MARK: Implementation detail internal final override class var kind: Kind { return .reference } internal final override func _projectMutableAddress( from base: UnsafePointer<Root> ) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { // Since we're a ReferenceWritableKeyPath, we know we don't mutate the base // in practice. return _projectMutableAddress(from: base.pointee) } @usableFromInline internal final func _projectMutableAddress(from origBase: Root) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var keepAlive: AnyObject? let address: UnsafeMutablePointer<Value> = withBuffer { var buffer = $0 // Project out the reference prefix. var base: Any = origBase while buffer.hasReferencePrefix { let (rawComponent, optNextType) = buffer.next() _internalInvariant(optNextType != nil, "reference prefix should not go to end of buffer") let nextType = optNextType.unsafelyUnwrapped func project<NewValue>(_: NewValue.Type) -> Any { func project2<CurValue>(_ base: CurValue) -> Any { return rawComponent._projectReadOnly( base, to: NewValue.self, endingWith: Value.self) .assumingContinue } return _openExistential(base, do: project2) } base = _openExistential(nextType, do: project) } // Start formal access to the mutable value, based on the final base // value. func formalMutation<MutationRoot>(_ base: MutationRoot) -> UnsafeMutablePointer<Value> { var base2 = base return withUnsafeBytes(of: &base2) { baseBytes in var p = baseBytes.baseAddress.unsafelyUnwrapped var curType: Any.Type = MutationRoot.self while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent._projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == baseBytes.baseAddress, keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(curType, do: project) if optNextType == nil { break } curType = nextType } let typedPointer = p.assumingMemoryBound(to: Value.self) return UnsafeMutablePointer(mutating: typedPointer) } } return _openExistential(base, do: formalMutation) } return (address, keepAlive) } } // MARK: Implementation details internal enum KeyPathComponentKind { /// The keypath references an externally-defined property or subscript whose /// component describes how to interact with the key path. case external /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct` /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class` /// The keypath projects using a getter/setter pair. case computed /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap } internal struct ComputedPropertyID: Hashable { internal var value: Int internal var kind: KeyPathComputedIDKind internal static func ==( x: ComputedPropertyID, y: ComputedPropertyID ) -> Bool { return x.value == y.value && x.kind == y.kind } internal func hash(into hasher: inout Hasher) { hasher.combine(value) hasher.combine(kind) } } internal struct ComputedArgumentWitnesses { internal typealias Destroy = @convention(thin) (_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Copy = @convention(thin) (_ srcInstanceArguments: UnsafeRawPointer, _ destInstanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Equals = @convention(thin) (_ xInstanceArguments: UnsafeRawPointer, _ yInstanceArguments: UnsafeRawPointer, _ size: Int) -> Bool // FIXME(hasher) Combine to an inout Hasher instead internal typealias Hash = @convention(thin) (_ instanceArguments: UnsafeRawPointer, _ size: Int) -> Int internal let destroy: Destroy? internal let copy: Copy internal let equals: Equals internal let hash: Hash } internal enum KeyPathComponent: Hashable { internal struct ArgumentRef { internal init( data: UnsafeRawBufferPointer, witnesses: UnsafePointer<ComputedArgumentWitnesses>, witnessSizeAdjustment: Int ) { self.data = data self.witnesses = witnesses self.witnessSizeAdjustment = witnessSizeAdjustment } internal var data: UnsafeRawBufferPointer internal var witnesses: UnsafePointer<ComputedArgumentWitnesses> internal var witnessSizeAdjustment: Int } /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct`(offset: Int) /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class`(offset: Int) /// The keypath projects using a getter. case get(id: ComputedPropertyID, get: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair. The setter can mutate /// the base value in-place. case mutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair that does not mutate its /// base. case nonmutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool { switch (a, b) { case (.struct(offset: let a), .struct(offset: let b)), (.class (offset: let a), .class (offset: let b)): return a == b case (.optionalChain, .optionalChain), (.optionalForce, .optionalForce), (.optionalWrap, .optionalWrap): return true case (.get(id: let id1, get: _, argument: let argument1), .get(id: let id2, get: _, argument: let argument2)), (.mutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .mutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)), (.nonmutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .nonmutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)): if id1 != id2 { return false } if let arg1 = argument1, let arg2 = argument2 { return arg1.witnesses.pointee.equals( arg1.data.baseAddress.unsafelyUnwrapped, arg2.data.baseAddress.unsafelyUnwrapped, arg1.data.count - arg1.witnessSizeAdjustment) } // If only one component has arguments, that should indicate that the // only arguments in that component were generic captures and therefore // not affecting equality. return true case (.struct, _), (.class, _), (.optionalChain, _), (.optionalForce, _), (.optionalWrap, _), (.get, _), (.mutatingGetSet, _), (.nonmutatingGetSet, _): return false } } @_effects(releasenone) internal func hash(into hasher: inout Hasher) { func appendHashFromArgument( _ argument: KeyPathComponent.ArgumentRef? ) { if let argument = argument { let hash = argument.witnesses.pointee.hash( argument.data.baseAddress.unsafelyUnwrapped, argument.data.count - argument.witnessSizeAdjustment) // Returning 0 indicates that the arguments should not impact the // hash value of the overall key path. // FIXME(hasher): hash witness should just mutate hasher directly if hash != 0 { hasher.combine(hash) } } } switch self { case .struct(offset: let a): hasher.combine(0) hasher.combine(a) case .class(offset: let b): hasher.combine(1) hasher.combine(b) case .optionalChain: hasher.combine(2) case .optionalForce: hasher.combine(3) case .optionalWrap: hasher.combine(4) case .get(id: let id, get: _, argument: let argument): hasher.combine(5) hasher.combine(id) appendHashFromArgument(argument) case .mutatingGetSet(id: let id, get: _, set: _, argument: let argument): hasher.combine(6) hasher.combine(id) appendHashFromArgument(argument) case .nonmutatingGetSet(id: let id, get: _, set: _, argument: let argument): hasher.combine(7) hasher.combine(id) appendHashFromArgument(argument) } } } // A class that maintains ownership of another object while a mutable projection // into it is underway. The lifetime of the instance of this class is also used // to begin and end exclusive 'modify' access to the projected address. internal final class ClassHolder<ProjectionType> { /// The type of the scratch record passed to the runtime to record /// accesses to guarantee exlcusive access. internal typealias AccessRecord = Builtin.UnsafeValueBuffer internal var previous: AnyObject? internal var instance: AnyObject internal init(previous: AnyObject?, instance: AnyObject) { self.previous = previous self.instance = instance } internal final class func _create( previous: AnyObject?, instance: AnyObject, accessingAddress address: UnsafeRawPointer, type: ProjectionType.Type ) -> ClassHolder { // Tail allocate the UnsafeValueBuffer used as the AccessRecord. // This avoids a second heap allocation since there is no source-level way to // initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a // stored property of that type. let holder: ClassHolder = Builtin.allocWithTailElems_1(self, 1._builtinWordValue, AccessRecord.self) // Initialize the ClassHolder's instance variables. This is done via // withUnsafeMutablePointer(to:) because the instance was just allocated with // allocWithTailElems_1 and so we need to make sure to use an initialization // rather than an assignment. withUnsafeMutablePointer(to: &holder.previous) { $0.initialize(to: previous) } withUnsafeMutablePointer(to: &holder.instance) { $0.initialize(to: instance) } let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self) // Begin a 'modify' access to the address. This access is ended in // ClassHolder's deinitializer. Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type) return holder } deinit { let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self) // Ends the access begun in _create(). Builtin.endUnpairedAccess(accessRecordPtr) } } // A class that triggers writeback to a pointer when destroyed. internal final class MutatingWritebackBuffer<CurValue, NewValue> { internal let previous: AnyObject? internal let base: UnsafeMutablePointer<CurValue> internal let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () internal let argument: UnsafeRawPointer internal let argumentSize: Int internal var value: NewValue deinit { set(value, &base.pointee, argument, argumentSize) } internal init(previous: AnyObject?, base: UnsafeMutablePointer<CurValue>, set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } // A class that triggers writeback to a non-mutated value when destroyed. internal final class NonmutatingWritebackBuffer<CurValue, NewValue> { internal let previous: AnyObject? internal let base: CurValue internal let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () internal let argument: UnsafeRawPointer internal let argumentSize: Int internal var value: NewValue deinit { set(value, base, argument, argumentSize) } internal init(previous: AnyObject?, base: CurValue, set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin) (_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int) internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin) (_ patternArguments: UnsafeRawPointer?, _ instanceArguments: UnsafeMutableRawPointer) -> () internal enum KeyPathComputedIDKind { case pointer case storedPropertyIndex case vtableOffset } internal enum KeyPathComputedIDResolution { case resolved case indirectPointer case functionCall } internal struct RawKeyPathComponent { internal init(header: Header, body: UnsafeRawBufferPointer) { self.header = header self.body = body } internal var header: Header internal var body: UnsafeRawBufferPointer internal struct Header { internal static var payloadMask: UInt32 { return _SwiftKeyPathComponentHeader_PayloadMask } internal static var discriminatorMask: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorMask } internal static var discriminatorShift: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorShift } internal static var externalTag: UInt32 { return _SwiftKeyPathComponentHeader_ExternalTag } internal static var structTag: UInt32 { return _SwiftKeyPathComponentHeader_StructTag } internal static var computedTag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedTag } internal static var classTag: UInt32 { return _SwiftKeyPathComponentHeader_ClassTag } internal static var optionalTag: UInt32 { return _SwiftKeyPathComponentHeader_OptionalTag } internal static var optionalChainPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalChainPayload } internal static var optionalWrapPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalWrapPayload } internal static var optionalForcePayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalForcePayload } internal static var endOfReferencePrefixFlag: UInt32 { return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag } internal static var storedMutableFlag: UInt32 { return _SwiftKeyPathComponentHeader_StoredMutableFlag } internal static var storedOffsetPayloadMask: UInt32 { return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask } internal static var outOfLineOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload } internal static var unresolvedFieldOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload } internal static var unresolvedIndirectOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload } internal static var maximumOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_MaximumOffsetPayload } internal var isStoredMutable: Bool { _internalInvariant(kind == .struct || kind == .class) return _value & Header.storedMutableFlag != 0 } internal static var computedMutatingFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedMutatingFlag } internal var isComputedMutating: Bool { _internalInvariant(kind == .computed) return _value & Header.computedMutatingFlag != 0 } internal static var computedSettableFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedSettableFlag } internal var isComputedSettable: Bool { _internalInvariant(kind == .computed) return _value & Header.computedSettableFlag != 0 } internal static var computedIDByStoredPropertyFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag } internal static var computedIDByVTableOffsetFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag } internal var computedIDKind: KeyPathComputedIDKind { let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0 let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0 switch (storedProperty, vtableOffset) { case (true, true): _internalInvariantFailure("not allowed") case (true, false): return .storedPropertyIndex case (false, true): return .vtableOffset case (false, false): return .pointer } } internal static var computedHasArgumentsFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag } internal var hasComputedArguments: Bool { _internalInvariant(kind == .computed) return _value & Header.computedHasArgumentsFlag != 0 } // If a computed component is instantiated from an external property // descriptor, and both components carry arguments, we need to carry some // extra matter to be able to map between the client and external generic // contexts. internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag } internal var isComputedInstantiatedFromExternalWithArguments: Bool { get { _internalInvariant(kind == .computed) return _value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0 } set { _internalInvariant(kind == .computed) _value = _value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag | (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0) } } internal static var externalWithArgumentsExtraSize: Int { return MemoryLayout<Int>.size } internal static var computedIDResolutionMask: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask } internal static var computedIDResolved: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolved } internal static var computedIDUnresolvedIndirectPointer: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer } internal static var computedIDUnresolvedFunctionCall: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall } internal var computedIDResolution: KeyPathComputedIDResolution { switch payload & Header.computedIDResolutionMask { case Header.computedIDResolved: return .resolved case Header.computedIDUnresolvedIndirectPointer: return .indirectPointer case Header.computedIDUnresolvedFunctionCall: return .functionCall default: _internalInvariantFailure("invalid key path resolution") } } internal var _value: UInt32 internal var discriminator: UInt32 { get { return (_value & Header.discriminatorMask) >> Header.discriminatorShift } set { let shifted = newValue << Header.discriminatorShift _internalInvariant(shifted & Header.discriminatorMask == shifted, "discriminator doesn't fit") _value = _value & ~Header.discriminatorMask | shifted } } internal var payload: UInt32 { get { return _value & Header.payloadMask } set { _internalInvariant(newValue & Header.payloadMask == newValue, "payload too big") _value = _value & ~Header.payloadMask | newValue } } internal var storedOffsetPayload: UInt32 { get { _internalInvariant(kind == .struct || kind == .class, "not a stored component") return _value & Header.storedOffsetPayloadMask } set { _internalInvariant(kind == .struct || kind == .class, "not a stored component") _internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue, "payload too big") _value = _value & ~Header.storedOffsetPayloadMask | newValue } } internal var endOfReferencePrefix: Bool { get { return _value & Header.endOfReferencePrefixFlag != 0 } set { if newValue { _value |= Header.endOfReferencePrefixFlag } else { _value &= ~Header.endOfReferencePrefixFlag } } } internal var kind: KeyPathComponentKind { switch (discriminator, payload) { case (Header.externalTag, _): return .external case (Header.structTag, _): return .struct case (Header.classTag, _): return .class case (Header.computedTag, _): return .computed case (Header.optionalTag, Header.optionalChainPayload): return .optionalChain case (Header.optionalTag, Header.optionalWrapPayload): return .optionalWrap case (Header.optionalTag, Header.optionalForcePayload): return .optionalForce default: _internalInvariantFailure("invalid header") } } // The component header is 4 bytes, but may be followed by an aligned // pointer field for some kinds of component, forcing padding. internal static var pointerAlignmentSkew: Int { return MemoryLayout<Int>.size - MemoryLayout<Int32>.size } internal var isTrivialPropertyDescriptor: Bool { return _value == _SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker } /// If this is the header for a component in a key path pattern, return /// the size of the body of the component. internal var patternComponentBodySize: Int { return _componentBodySize(forPropertyDescriptor: false) } /// If this is the header for a property descriptor, return /// the size of the body of the component. internal var propertyDescriptorBodySize: Int { if isTrivialPropertyDescriptor { return 0 } return _componentBodySize(forPropertyDescriptor: true) } internal func _componentBodySize(forPropertyDescriptor: Bool) -> Int { switch kind { case .struct, .class: if storedOffsetPayload == Header.unresolvedFieldOffsetPayload || storedOffsetPayload == Header.outOfLineOffsetPayload || storedOffsetPayload == Header.unresolvedIndirectOffsetPayload { // A 32-bit offset is stored in the body. return MemoryLayout<UInt32>.size } // Otherwise, there's no body. return 0 case .external: // The body holds a pointer to the external property descriptor, // and some number of substitution arguments, the count of which is // in the payload. return 4 * (1 + Int(payload)) case .computed: // The body holds at minimum the id and getter. var size = 8 // If settable, it also holds the setter. if isComputedSettable { size += 4 } // If there are arguments, there's also a layout function, // witness table, and initializer function. // Property descriptors never carry argument information, though. if !forPropertyDescriptor && hasComputedArguments { size += 12 } return size case .optionalForce, .optionalChain, .optionalWrap: // Otherwise, there's no body. return 0 } } init(discriminator: UInt32, payload: UInt32) { _value = 0 self.discriminator = discriminator self.payload = payload } init(optionalForce: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalForcePayload) } init(optionalWrap: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalWrapPayload) } init(optionalChain: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalChainPayload) } init(stored kind: KeyPathStructOrClass, mutable: Bool, inlineOffset: UInt32) { let discriminator: UInt32 switch kind { case .struct: discriminator = Header.structTag case .class: discriminator = Header.classTag } _internalInvariant(inlineOffset <= Header.maximumOffsetPayload) let payload = inlineOffset | (mutable ? Header.storedMutableFlag : 0) self.init(discriminator: discriminator, payload: payload) } init(storedWithOutOfLineOffset kind: KeyPathStructOrClass, mutable: Bool) { let discriminator: UInt32 switch kind { case .struct: discriminator = Header.structTag case .class: discriminator = Header.classTag } let payload = Header.outOfLineOffsetPayload | (mutable ? Header.storedMutableFlag : 0) self.init(discriminator: discriminator, payload: payload) } init(computedWithIDKind kind: KeyPathComputedIDKind, mutating: Bool, settable: Bool, hasArguments: Bool, instantiatedFromExternalWithArguments: Bool) { let discriminator = Header.computedTag var payload = (mutating ? Header.computedMutatingFlag : 0) | (settable ? Header.computedSettableFlag : 0) | (hasArguments ? Header.computedHasArgumentsFlag : 0) | (instantiatedFromExternalWithArguments ? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0) switch kind { case .pointer: break case .storedPropertyIndex: payload |= Header.computedIDByStoredPropertyFlag case .vtableOffset: payload |= Header.computedIDByVTableOffsetFlag } self.init(discriminator: discriminator, payload: payload) } } internal var bodySize: Int { let ptrSize = MemoryLayout<Int>.size switch header.kind { case .struct, .class: if header.storedOffsetPayload == Header.outOfLineOffsetPayload { return 4 // overflowed } return 0 case .external: _internalInvariantFailure("should be instantiated away") case .optionalChain, .optionalForce, .optionalWrap: return 0 case .computed: // align to pointer, minimum two pointers for id and get var total = Header.pointerAlignmentSkew + ptrSize * 2 // additional word for a setter if header.isComputedSettable { total += ptrSize } // include the argument size if header.hasComputedArguments { // two words for argument header: size, witnesses total += ptrSize * 2 // size of argument area total += _computedArgumentSize if header.isComputedInstantiatedFromExternalWithArguments { total += Header.externalWithArgumentsExtraSize } } return total } } internal var _structOrClassOffset: Int { _internalInvariant(header.kind == .struct || header.kind == .class, "no offset for this kind") // An offset too large to fit inline is represented by a signal and stored // in the body. if header.storedOffsetPayload == Header.outOfLineOffsetPayload { // Offset overflowed into body _internalInvariant(body.count >= MemoryLayout<UInt32>.size, "component not big enough") return Int(body.load(as: UInt32.self)) } return Int(header.storedOffsetPayload) } internal var _computedIDValue: Int { _internalInvariant(header.kind == .computed, "not a computed property") return body.load(fromByteOffset: Header.pointerAlignmentSkew, as: Int.self) } internal var _computedID: ComputedPropertyID { _internalInvariant(header.kind == .computed, "not a computed property") return ComputedPropertyID( value: _computedIDValue, kind: header.computedIDKind) } internal var _computedGetter: UnsafeRawPointer { _internalInvariant(header.kind == .computed, "not a computed property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size, as: UnsafeRawPointer.self) } internal var _computedSetter: UnsafeRawPointer { _internalInvariant(header.isComputedSettable, "not a settable property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size * 2, as: UnsafeRawPointer.self) } internal var _computedArgumentHeaderPointer: UnsafeRawPointer { _internalInvariant(header.hasComputedArguments, "no arguments") return body.baseAddress.unsafelyUnwrapped + Header.pointerAlignmentSkew + MemoryLayout<Int>.size * (header.isComputedSettable ? 3 : 2) } internal var _computedArgumentSize: Int { return _computedArgumentHeaderPointer.load(as: Int.self) } internal var _computedArgumentWitnesses: UnsafePointer<ComputedArgumentWitnesses> { return _computedArgumentHeaderPointer.load( fromByteOffset: MemoryLayout<Int>.size, as: UnsafePointer<ComputedArgumentWitnesses>.self) } internal var _computedArguments: UnsafeRawPointer { var base = _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2 // If the component was instantiated from an external property descriptor // with its own arguments, we include some additional capture info to // be able to map to the original argument context by adjusting the size // passed to the witness operations. if header.isComputedInstantiatedFromExternalWithArguments { base += Header.externalWithArgumentsExtraSize } return base } internal var _computedMutableArguments: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(mutating: _computedArguments) } internal var _computedArgumentWitnessSizeAdjustment: Int { if header.isComputedInstantiatedFromExternalWithArguments { return _computedArguments.load( fromByteOffset: -Header.externalWithArgumentsExtraSize, as: Int.self) } return 0 } internal var value: KeyPathComponent { switch header.kind { case .struct: return .struct(offset: _structOrClassOffset) case .class: return .class(offset: _structOrClassOffset) case .optionalChain: return .optionalChain case .optionalForce: return .optionalForce case .optionalWrap: return .optionalWrap case .computed: let isSettable = header.isComputedSettable let isMutating = header.isComputedMutating let id = _computedID let get = _computedGetter // Argument value is unused if there are no arguments. let argument: KeyPathComponent.ArgumentRef? if header.hasComputedArguments { argument = KeyPathComponent.ArgumentRef( data: UnsafeRawBufferPointer(start: _computedArguments, count: _computedArgumentSize), witnesses: _computedArgumentWitnesses, witnessSizeAdjustment: _computedArgumentWitnessSizeAdjustment) } else { argument = nil } switch (isSettable, isMutating) { case (false, false): return .get(id: id, get: get, argument: argument) case (true, false): return .nonmutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (true, true): return .mutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (false, true): _internalInvariantFailure("impossible") } case .external: _internalInvariantFailure("should have been instantiated away") } } internal func destroy() { switch header.kind { case .struct, .class, .optionalChain, .optionalForce, .optionalWrap: // trivial break case .computed: // Run destructor, if any if header.hasComputedArguments, let destructor = _computedArgumentWitnesses.pointee.destroy { destructor(_computedMutableArguments, _computedArgumentSize - _computedArgumentWitnessSizeAdjustment) } case .external: _internalInvariantFailure("should have been instantiated away") } } internal func clone(into buffer: inout UnsafeMutableRawBufferPointer, endOfReferencePrefix: Bool) { var newHeader = header newHeader.endOfReferencePrefix = endOfReferencePrefix var componentSize = MemoryLayout<Header>.size buffer.storeBytes(of: newHeader, as: Header.self) switch header.kind { case .struct, .class: if header.storedOffsetPayload == Header.outOfLineOffsetPayload { let overflowOffset = body.load(as: UInt32.self) buffer.storeBytes(of: overflowOffset, toByteOffset: 4, as: UInt32.self) componentSize += 4 } case .optionalChain, .optionalForce, .optionalWrap: break case .computed: // Fields are pointer-aligned after the header componentSize += Header.pointerAlignmentSkew buffer.storeBytes(of: _computedIDValue, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size buffer.storeBytes(of: _computedGetter, toByteOffset: componentSize, as: UnsafeRawPointer.self) componentSize += MemoryLayout<Int>.size if header.isComputedSettable { buffer.storeBytes(of: _computedSetter, toByteOffset: MemoryLayout<Int>.size * 3, as: UnsafeRawPointer.self) componentSize += MemoryLayout<Int>.size } if header.hasComputedArguments { let arguments = _computedArguments let argumentSize = _computedArgumentSize buffer.storeBytes(of: argumentSize, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size buffer.storeBytes(of: _computedArgumentWitnesses, toByteOffset: componentSize, as: UnsafePointer<ComputedArgumentWitnesses>.self) componentSize += MemoryLayout<Int>.size if header.isComputedInstantiatedFromExternalWithArguments { // Include the extra matter for components instantiated from // external property descriptors with arguments. buffer.storeBytes(of: _computedArgumentWitnessSizeAdjustment, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size } let adjustedSize = argumentSize - _computedArgumentWitnessSizeAdjustment let argumentDest = buffer.baseAddress.unsafelyUnwrapped + componentSize _computedArgumentWitnesses.pointee.copy( arguments, argumentDest, adjustedSize) if header.isComputedInstantiatedFromExternalWithArguments { // The extra information for external property descriptor arguments // can always be memcpy'd. _memcpy(dest: argumentDest + adjustedSize, src: arguments + adjustedSize, size: UInt(_computedArgumentWitnessSizeAdjustment)) } componentSize += argumentSize } case .external: _internalInvariantFailure("should have been instantiated away") } buffer = UnsafeMutableRawBufferPointer( start: buffer.baseAddress.unsafelyUnwrapped + componentSize, count: buffer.count - componentSize) } internal enum ProjectionResult<NewValue, LeafValue> { /// Continue projecting the key path with the given new value. case `continue`(NewValue) /// Stop projecting the key path and use the given value as the final /// result of the projection. case `break`(LeafValue) internal var assumingContinue: NewValue { switch self { case .continue(let x): return x case .break: _internalInvariantFailure("should not have stopped key path projection") } } } internal func _projectReadOnly<CurValue, NewValue, LeafValue>( _ base: CurValue, to: NewValue.Type, endingWith: LeafValue.Type ) -> ProjectionResult<NewValue, LeafValue> { switch value { case .struct(let offset): var base2 = base return .continue(withUnsafeBytes(of: &base2) { let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset) // The contents of the struct should be well-typed, so we can assume // typed memory here. return p.assumingMemoryBound(to: NewValue.self).pointee }) case .class(let offset): _internalInvariant(CurValue.self is AnyObject.Type, "base is not a class") let baseObj = unsafeBitCast(base, to: AnyObject.self) let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj)) defer { _fixLifetime(baseObj) } let offsetAddress = basePtr.advanced(by: offset) // Perform an instaneous record access on the address in order to // ensure that the read will not conflict with an already in-progress // 'modify' access. Builtin.performInstantaneousReadAccess(offsetAddress._rawValue, NewValue.self) return .continue(offsetAddress .assumingMemoryBound(to: NewValue.self) .pointee) case .get(id: _, get: let rawGet, argument: let argument), .mutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument), .nonmutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue let get = unsafeBitCast(rawGet, to: Getter.self) return .continue(get(base, argument?.data.baseAddress ?? rawGet, argument?.data.count ?? 0)) case .optionalChain: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping optional value") _internalInvariant(_isOptional(LeafValue.self), "leaf result should be optional") if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) { return .continue(baseValue) } else { // TODO: A more efficient way of getting the `none` representation // of a dynamically-optional type... return .break((Optional<()>.none as Any) as! LeafValue) } case .optionalForce: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping optional value") return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!) case .optionalWrap: _internalInvariant(NewValue.self == Optional<CurValue>.self, "should be wrapping optional value") return .continue( unsafeBitCast(base as Optional<CurValue>, to: NewValue.self)) } } internal func _projectMutableAddress<CurValue, NewValue>( _ base: UnsafeRawPointer, from _: CurValue.Type, to _: NewValue.Type, isRoot: Bool, keepAlive: inout AnyObject? ) -> UnsafeRawPointer { switch value { case .struct(let offset): return base.advanced(by: offset) case .class(let offset): // A class dereference should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _internalInvariant(isRoot, "class component should not appear in the middle of mutation") // AnyObject memory can alias any class reference memory, so we can // assume type here let object = base.assumingMemoryBound(to: AnyObject.self).pointee let offsetAddress = UnsafeRawPointer(Builtin.bridgeToRawPointer(object)) .advanced(by: offset) // Keep the base alive for the duration of the derived access and also // enforce exclusive access to the address. keepAlive = ClassHolder._create(previous: keepAlive, instance: object, accessingAddress: offsetAddress, type: NewValue.self) return offsetAddress case .mutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseTyped = UnsafeMutablePointer( mutating: base.assumingMemoryBound(to: CurValue.self)) let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = MutatingWritebackBuffer(previous: keepAlive, base: baseTyped, set: set, argument: argValue, argumentSize: argSize, value: get(baseTyped.pointee, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .nonmutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): // A nonmutating property should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _internalInvariant(isRoot, "nonmutating component should not appear in the middle of mutation") typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = NonmutatingWritebackBuffer(previous: keepAlive, base: baseValue, set: set, argument: argValue, argumentSize: argSize, value: get(baseValue, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .optionalForce: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping an optional value") // Optional's layout happens to always put the payload at the start // address of the Optional value itself, if a value is present at all. let baseOptionalPointer = base.assumingMemoryBound(to: Optional<NewValue>.self) // Assert that a value exists _ = baseOptionalPointer.pointee! return base case .optionalChain, .optionalWrap, .get: _internalInvariantFailure("not a mutable key path component") } } } internal func _pop<T>(from: inout UnsafeRawBufferPointer, as type: T.Type) -> T { let buffer = _pop(from: &from, as: type, count: 1) return buffer.baseAddress.unsafelyUnwrapped.pointee } internal func _pop<T>(from: inout UnsafeRawBufferPointer, as: T.Type, count: Int) -> UnsafeBufferPointer<T> { _internalInvariant(_isPOD(T.self), "should be POD") from = MemoryLayout<T>._roundingUpBaseToAlignment(from) let byteCount = MemoryLayout<T>.stride * count let result = UnsafeBufferPointer( start: from.baseAddress.unsafelyUnwrapped.assumingMemoryBound(to: T.self), count: count) from = UnsafeRawBufferPointer( start: from.baseAddress.unsafelyUnwrapped + byteCount, count: from.count - byteCount) return result } internal struct KeyPathBuffer { internal var data: UnsafeRawBufferPointer internal var trivial: Bool internal var hasReferencePrefix: Bool internal var mutableData: UnsafeMutableRawBufferPointer { return UnsafeMutableRawBufferPointer(mutating: data) } internal struct Header { internal var _value: UInt32 internal static var sizeMask: UInt32 { return _SwiftKeyPathBufferHeader_SizeMask } internal static var reservedMask: UInt32 { return _SwiftKeyPathBufferHeader_ReservedMask } internal static var trivialFlag: UInt32 { return _SwiftKeyPathBufferHeader_TrivialFlag } internal static var hasReferencePrefixFlag: UInt32 { return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag } internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) { _internalInvariant(size <= Int(Header.sizeMask), "key path too big") _value = UInt32(size) | (trivial ? Header.trivialFlag : 0) | (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0) } internal var size: Int { return Int(_value & Header.sizeMask) } internal var trivial: Bool { return _value & Header.trivialFlag != 0 } internal var hasReferencePrefix: Bool { get { return _value & Header.hasReferencePrefixFlag != 0 } set { if newValue { _value |= Header.hasReferencePrefixFlag } else { _value &= ~Header.hasReferencePrefixFlag } } } // In a key path pattern, the "trivial" flag is used to indicate // "instantiable in-line" internal var instantiableInLine: Bool { return trivial } internal func validateReservedBits() { _precondition(_value & Header.reservedMask == 0, "Reserved bits set to an unexpected bit pattern") } } internal init(base: UnsafeRawPointer) { let header = base.load(as: Header.self) data = UnsafeRawBufferPointer( start: base + MemoryLayout<Int>.size, count: header.size) trivial = header.trivial hasReferencePrefix = header.hasReferencePrefix } internal init(partialData: UnsafeRawBufferPointer, trivial: Bool = false, hasReferencePrefix: Bool = false) { self.data = partialData self.trivial = trivial self.hasReferencePrefix = hasReferencePrefix } internal func destroy() { // Short-circuit if nothing in the object requires destruction. if trivial { return } var bufferToDestroy = self while true { let (component, type) = bufferToDestroy.next() component.destroy() guard let _ = type else { break } } } internal mutating func next() -> (RawKeyPathComponent, Any.Type?) { let header = _pop(from: &data, as: RawKeyPathComponent.Header.self) // Track if this is the last component of the reference prefix. if header.endOfReferencePrefix { _internalInvariant(self.hasReferencePrefix, "beginMutation marker in non-reference-writable key path?") self.hasReferencePrefix = false } var component = RawKeyPathComponent(header: header, body: data) // Shrinkwrap the component buffer size. let size = component.bodySize component.body = UnsafeRawBufferPointer(start: component.body.baseAddress, count: size) _ = _pop(from: &data, as: Int8.self, count: size) // fetch type, which is in the buffer unless it's the final component let nextType: Any.Type? if data.isEmpty { nextType = nil } else { nextType = _pop(from: &data, as: Any.Type.self) } return (component, nextType) } } // MARK: Library intrinsics for projecting key paths. @_silgen_name("swift_getAtPartialKeyPath") public // COMPILER_INTRINSIC func _getAtPartialKeyPath<Root>( root: Root, keyPath: PartialKeyPath<Root> ) -> Any { func open<Value>(_: Value.Type) -> Any { return _getAtKeyPath(root: root, keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self)) } return _openExistential(type(of: keyPath).valueType, do: open) } @_silgen_name("swift_getAtAnyKeyPath") public // COMPILER_INTRINSIC func _getAtAnyKeyPath<RootValue>( root: RootValue, keyPath: AnyKeyPath ) -> Any? { let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? { guard let rootForKeyPath = root as? KeyPathRoot else { return nil } func openValue<Value>(_: Value.Type) -> Any { return _getAtKeyPath(root: rootForKeyPath, keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self)) } return _openExistential(keyPathValue, do: openValue) } return _openExistential(keyPathRoot, do: openRoot) } @_silgen_name("swift_getAtKeyPath") public // COMPILER_INTRINSIC func _getAtKeyPath<Root, Value>( root: Root, keyPath: KeyPath<Root, Value> ) -> Value { return keyPath._projectReadOnly(from: root) } // The release that ends the access scope is guaranteed to happen // immediately at the end_apply call because the continuation is a // runtime call with a manual release (access scopes cannot be extended). @_silgen_name("_swift_modifyAtWritableKeyPath_impl") public // runtime entrypoint func _modifyAtWritableKeyPath_impl<Root, Value>( root: inout Root, keyPath: WritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath._projectMutableAddress(from: &root) } // The release that ends the access scope is guaranteed to happen // immediately at the end_apply call because the continuation is a // runtime call with a manual release (access scopes cannot be extended). @_silgen_name("_swift_modifyAtReferenceWritableKeyPath_impl") public // runtime entrypoint func _modifyAtReferenceWritableKeyPath_impl<Root, Value>( root: Root, keyPath: ReferenceWritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath._projectMutableAddress(from: root) } @_silgen_name("swift_setAtWritableKeyPath") public // COMPILER_INTRINSIC func _setAtWritableKeyPath<Root, Value>( root: inout Root, keyPath: WritableKeyPath<Root, Value>, value: __owned Value ) { // TODO: we should be able to do this more efficiently than projecting. let (addr, owner) = keyPath._projectMutableAddress(from: &root) addr.pointee = value _fixLifetime(owner) // FIXME: this needs a deallocation barrier to ensure that the // release isn't extended, along with the access scope. } @_silgen_name("swift_setAtReferenceWritableKeyPath") public // COMPILER_INTRINSIC func _setAtReferenceWritableKeyPath<Root, Value>( root: Root, keyPath: ReferenceWritableKeyPath<Root, Value>, value: __owned Value ) { // TODO: we should be able to do this more efficiently than projecting. let (addr, owner) = keyPath._projectMutableAddress(from: root) addr.pointee = value _fixLifetime(owner) // FIXME: this needs a deallocation barrier to ensure that the // release isn't extended, along with the access scope. } // MARK: Appending type system // FIXME(ABI): The type relationships between KeyPath append operands are tricky // and don't interact well with our overriding rules. Hack things by injecting // a bunch of `appending` overloads as protocol extensions so they aren't // constrained by being overrides, and so that we can use exact-type constraints // on `Self` to prevent dynamically-typed methods from being inherited by // statically-typed key paths. /// An implementation detail of key path expressions; do not use this protocol /// directly. @_show_in_interface public protocol _AppendKeyPath {} extension _AppendKeyPath where Self == AnyKeyPath { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: AnyKeyPath = \Array<Int>.description /// let stringLength: AnyKeyPath = \String.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending(path: AnyKeyPath) -> AnyKeyPath? { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// let stringLength: PartialKeyPath<String> = \.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates a key path from `Array<Int>` to `String`, and then tries /// appending compatible and incompatible key paths: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: \String.count) /// /// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` because the root type /// of the `path` parameter, `Double`, does not match the value type of /// `arrayDescription`, `String`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root, AppendedRoot, AppendedValue>( path: KeyPath<AppendedRoot, AppendedValue> ) -> KeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. /// /// - Parameter path: The reference writeable key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root, AppendedRoot, AppendedValue>( path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == KeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. In the following /// example, `keyPath1` and `keyPath2` are equivalent: /// /// let arrayDescription = \Array<Int>.description /// let keyPath1 = arrayDescription.appending(path: \String.count) /// /// let keyPath2 = \Array<Int>.description.count /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> KeyPath<Root, AppendedValue> where Self: KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /* TODO public func appending<Root, Value, Leaf>( path: Leaf, // FIXME: Satisfy "Value generic param not used in signature" constraint _: Value.Type = Value.self ) -> PartialKeyPath<Root>? where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath { return _tryToAppendKeyPaths(root: self, leaf: path) } */ /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> WritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == ReferenceWritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } @usableFromInline internal func _tryToAppendKeyPaths<Result: AnyKeyPath>( root: AnyKeyPath, leaf: AnyKeyPath ) -> Result? { let (rootRoot, rootValue) = type(of: root)._rootAndValueType let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType if rootValue != leafRoot { return nil } func open<Root>(_: Root.Type) -> Result { func open2<Value>(_: Value.Type) -> Result { func open3<AppendedValue>(_: AppendedValue.Type) -> Result { let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self) let typedLeaf = unsafeDowncast(leaf, to: KeyPath<Value, AppendedValue>.self) let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf) return unsafeDowncast(result, to: Result.self) } return _openExistential(leafValue, do: open3) } return _openExistential(rootValue, do: open2) } return _openExistential(rootRoot, do: open) } @usableFromInline internal func _appendingKeyPaths< Root, Value, AppendedValue, Result: KeyPath<Root, AppendedValue> >( root: KeyPath<Root, Value>, leaf: KeyPath<Value, AppendedValue> ) -> Result { let resultTy = type(of: root).appendedType(with: type(of: leaf)) return root.withBuffer { var rootBuffer = $0 return leaf.withBuffer { var leafBuffer = $0 // If either operand is the identity key path, then we should return // the other operand back untouched. if leafBuffer.data.isEmpty { return unsafeDowncast(root, to: Result.self) } if rootBuffer.data.isEmpty { return unsafeDowncast(leaf, to: Result.self) } // Reserve room for the appended KVC string, if both key paths are // KVC-compatible. let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int if let rootPtr = root._kvcKeyPathStringPtr, let leafPtr = leaf._kvcKeyPathStringPtr { rootKVCLength = Int(_swift_stdlib_strlen(rootPtr)) leafKVCLength = Int(_swift_stdlib_strlen(leafPtr)) // root + "." + leaf appendedKVCLength = rootKVCLength + 1 + leafKVCLength + 1 } else { rootKVCLength = 0 leafKVCLength = 0 appendedKVCLength = 0 } // Result buffer has room for both key paths' components, plus the // header, plus space for the middle type. // Align up the root so that we can put the component type after it. let rootSize = MemoryLayout<Int>._roundingUpToAlignment(rootBuffer.data.count) let resultSize = rootSize + leafBuffer.data.count + 2 * MemoryLayout<Int>.size // Tail-allocate space for the KVC string. let totalResultSize = MemoryLayout<Int32> ._roundingUpToAlignment(resultSize + appendedKVCLength) var kvcStringBuffer: UnsafeMutableRawPointer? = nil let result = resultTy._create(capacityInBytes: totalResultSize) { var destBuffer = $0 // Remember where the tail-allocated KVC string buffer begins. if appendedKVCLength > 0 { kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped .advanced(by: resultSize) destBuffer = .init(start: destBuffer.baseAddress, count: resultSize) } func pushRaw(size: Int, alignment: Int) -> UnsafeMutableRawBufferPointer { var baseAddress = destBuffer.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } let result = UnsafeMutableRawBufferPointer( start: baseAddress, count: size) destBuffer = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destBuffer.count - size - misalign) return result } func push<T>(_ value: T) { let buf = pushRaw(size: MemoryLayout<T>.size, alignment: MemoryLayout<T>.alignment) buf.storeBytes(of: value, as: T.self) } // Save space for the header. let leafIsReferenceWritable = type(of: leaf).kind == .reference let header = KeyPathBuffer.Header( size: resultSize - MemoryLayout<Int>.size, trivial: rootBuffer.trivial && leafBuffer.trivial, hasReferencePrefix: rootBuffer.hasReferencePrefix || leafIsReferenceWritable ) push(header) // Start the components at pointer alignment _ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew, alignment: 4) let leafHasReferencePrefix = leafBuffer.hasReferencePrefix // Clone the root components into the buffer. while true { let (component, type) = rootBuffer.next() let isLast = type == nil // If the leaf appended path has a reference prefix, then the // entire root is part of the reference prefix. let endOfReferencePrefix: Bool if leafHasReferencePrefix { endOfReferencePrefix = false } else if isLast && leafIsReferenceWritable { endOfReferencePrefix = true } else { endOfReferencePrefix = component.header.endOfReferencePrefix } component.clone( into: &destBuffer, endOfReferencePrefix: endOfReferencePrefix) if let type = type { push(type) } else { // Insert our endpoint type between the root and leaf components. push(Value.self as Any.Type) break } } // Clone the leaf components into the buffer. while true { let (component, type) = leafBuffer.next() component.clone( into: &destBuffer, endOfReferencePrefix: component.header.endOfReferencePrefix) if let type = type { push(type) } else { break } } _internalInvariant(destBuffer.isEmpty, "did not fill entire result buffer") } // Build the KVC string if there is one. if let kvcStringBuffer = kvcStringBuffer { let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped _memcpy(dest: kvcStringBuffer, src: rootPtr, size: UInt(rootKVCLength)) kvcStringBuffer.advanced(by: rootKVCLength) .storeBytes(of: 0x2E /* '.' */, as: CChar.self) _memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1), src: leafPtr, size: UInt(leafKVCLength)) result._kvcKeyPathStringPtr = UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self)) kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1) .storeBytes(of: 0 /* '\0' */, as: CChar.self) } return unsafeDowncast(result, to: Result.self) } } } // The distance in bytes from the address point of a KeyPath object to its // buffer header. Includes the size of the Swift heap object header and the // pointer to the KVC string. internal var keyPathObjectHeaderSize: Int { return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size } internal var keyPathPatternHeaderSize: Int { return 16 } // Runtime entry point to instantiate a key path object. // Note that this has a compatibility override shim in the runtime so that // future compilers can backward-deploy support for instantiating new key path // pattern features. @_cdecl("swift_getKeyPathImpl") public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer, arguments: UnsafeRawPointer) -> UnsafeRawPointer { // The key path pattern is laid out like a key path object, with a few // modifications: // - Pointers in the instantiated object are compressed into 32-bit // relative offsets in the pattern. // - The pattern begins with a field that's either zero, for a pattern that // depends on instantiation arguments, or that's a relative reference to // a global mutable pointer variable, which can be initialized to a single // shared instantiation of this pattern. // - Instead of the two-word object header with isa and refcount, two // pointers to metadata accessors are provided for the root and leaf // value types of the key path. // - Components may have unresolved forms that require instantiation. // - Type metadata and protocol conformance pointers are replaced with // relative-referenced accessor functions that instantiate the // needed generic argument when called. // // The pattern never precomputes the capabilities of the key path (readonly/ // writable/reference-writable), nor does it encode the reference prefix. // These are resolved dynamically, so that they always reflect the dynamic // capability of the properties involved. let oncePtrPtr = pattern let patternPtr = pattern.advanced(by: 4) let bufferHeader = patternPtr.load(fromByteOffset: keyPathPatternHeaderSize, as: KeyPathBuffer.Header.self) bufferHeader.validateReservedBits() // If the first word is nonzero, it relative-references a cache variable // we can use to reference a single shared instantiation of this key path. let oncePtrOffset = oncePtrPtr.load(as: Int32.self) let oncePtr: UnsafeRawPointer? if oncePtrOffset != 0 { let theOncePtr = _resolveRelativeAddress(oncePtrPtr, oncePtrOffset) oncePtr = theOncePtr // See whether we already instantiated this key path. // This is a non-atomic load because the instantiated pointer will be // written with a release barrier, and loads of the instantiated key path // ought to carry a dependency through this loaded pointer. let existingInstance = theOncePtr.load(as: UnsafeRawPointer?.self) if let existingInstance = existingInstance { // Return the instantiated object at +1. let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance) // TODO: This retain will be unnecessary once we support global objects // with inert refcounting. _ = object.retain() return existingInstance } } else { oncePtr = nil } // Instantiate a new key path object modeled on the pattern. // Do a pass to determine the class of the key path we'll be instantiating // and how much space we'll need for it. let (keyPathClass, rootType, size, _) = _getKeyPathClassAndInstanceSizeFromPattern(patternPtr, arguments) // Allocate the instance. let instance = keyPathClass._create(capacityInBytes: size) { instanceData in // Instantiate the pattern into the instance. _instantiateKeyPathBuffer(patternPtr, instanceData, rootType, arguments) } // Adopt the KVC string from the pattern. let kvcStringBase = patternPtr.advanced(by: 12) let kvcStringOffset = kvcStringBase.load(as: Int32.self) if kvcStringOffset == 0 { // Null pointer. instance._kvcKeyPathStringPtr = nil } else { let kvcStringPtr = _resolveRelativeAddress(kvcStringBase, kvcStringOffset) instance._kvcKeyPathStringPtr = kvcStringPtr.assumingMemoryBound(to: CChar.self) } // If we can cache this instance as a shared instance, do so. if let oncePtr = oncePtr { // Try to replace a null pointer in the cache variable with the instance // pointer. let instancePtr = Unmanaged.passRetained(instance) while true { let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word( oncePtr._rawValue, 0._builtinWordValue, UInt(bitPattern: instancePtr.toOpaque())._builtinWordValue) // If the exchange succeeds, then the instance we formed is the canonical // one. if Bool(won) { break } // Otherwise, someone raced with us to instantiate the key path pattern // and won. Their instance should be just as good as ours, so we can take // that one and let ours get deallocated. if let existingInstance = UnsafeRawPointer(bitPattern: Int(oldValue)) { // Return the instantiated object at +1. let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance) // TODO: This retain will be unnecessary once we support global objects // with inert refcounting. _ = object.retain() // Release the instance we created. instancePtr.release() return existingInstance } else { // Try the cmpxchg again if it spuriously failed. continue } } } return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque()) } // A reference to metadata, which is a pointer to a mangled name. internal typealias MetadataReference = UnsafeRawPointer // Determine the length of the given mangled name. internal func _getSymbolicMangledNameLength(_ base: UnsafeRawPointer) -> Int { var end = base while let current = Optional(end.load(as: UInt8.self)), current != 0 { // Skip the current character end = end + 1 // Skip over a symbolic reference if current >= 0x1 && current <= 0x17 { end += 4 } else if current >= 0x18 && current <= 0x1F { end += MemoryLayout<Int>.size } } return end - base } // Resolve a mangled name in a generic environment, described by either a // flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested // ContextDescriptor * (if the bottom tag bit is 1) internal func _getTypeByMangledNameInEnvironmentOrContext( _ name: UnsafePointer<UInt8>, _ nameLength: UInt, genericEnvironmentOrContext: UnsafeRawPointer?, genericArguments: UnsafeRawPointer?) -> Any.Type? { let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext) if taggedPointer & 1 == 0 { return _getTypeByMangledNameInEnvironment(name, nameLength, genericEnvironment: genericEnvironmentOrContext, genericArguments: genericArguments) } else { let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1) return _getTypeByMangledNameInContext(name, nameLength, genericContext: context, genericArguments: genericArguments) } } // Resolve the given generic argument reference to a generic argument. internal func _resolveKeyPathGenericArgReference( _ reference: UnsafeRawPointer, genericEnvironment: UnsafeRawPointer?, arguments: UnsafeRawPointer?) -> UnsafeRawPointer { // If the low bit is clear, it's a direct reference to the argument. if (UInt(bitPattern: reference) & 0x01 == 0) { return reference } // Adjust the reference. let referenceStart = reference - 1 let nameLength = _getSymbolicMangledNameLength(referenceStart) let namePtr = referenceStart.bindMemory(to: UInt8.self, capacity: nameLength + 1) // FIXME: Could extract this information from the mangled name. guard let result = _getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength), genericEnvironmentOrContext: genericEnvironment, genericArguments: arguments) else { let nameStr = String._fromUTF8Repairing( UnsafeBufferPointer(start: namePtr, count: nameLength) ).0 fatalError("could not demangle keypath type from '\(nameStr)'") } return unsafeBitCast(result, to: UnsafeRawPointer.self) } // Resolve the given metadata reference to (type) metadata. internal func _resolveKeyPathMetadataReference( _ reference: UnsafeRawPointer, genericEnvironment: UnsafeRawPointer?, arguments: UnsafeRawPointer?) -> Any.Type { return unsafeBitCast( _resolveKeyPathGenericArgReference( reference, genericEnvironment: genericEnvironment, arguments: arguments), to: Any.Type.self) } internal enum KeyPathStructOrClass { case `struct`, `class` } internal enum KeyPathPatternStoredOffset { case inline(UInt32) case outOfLine(UInt32) case unresolvedFieldOffset(UInt32) case unresolvedIndirectOffset(UnsafePointer<UInt>) } internal struct KeyPathPatternComputedArguments { var getLayout: KeyPathComputedArgumentLayoutFn var witnesses: UnsafePointer<ComputedArgumentWitnesses> var initializer: KeyPathComputedArgumentInitializerFn } internal protocol KeyPathPatternVisitor { mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) mutating func visitOptionalChainComponent() mutating func visitOptionalForceComponent() mutating func visitOptionalWrapComponent() mutating func visitIntermediateComponentType(metadataRef: MetadataReference) mutating func finish() } internal func _resolveRelativeAddress(_ base: UnsafeRawPointer, _ offset: Int32) -> UnsafeRawPointer { // Sign-extend the offset to pointer width and add with wrap on overflow. return UnsafeRawPointer(bitPattern: Int(bitPattern: base) &+ Int(offset)) .unsafelyUnwrapped } internal func _resolveRelativeIndirectableAddress(_ base: UnsafeRawPointer, _ offset: Int32) -> UnsafeRawPointer { // Low bit indicates whether the reference is indirected or not. if offset & 1 != 0 { let ptrToPtr = _resolveRelativeAddress(base, offset - 1) return ptrToPtr.load(as: UnsafeRawPointer.self) } return _resolveRelativeAddress(base, offset) } internal func _loadRelativeAddress<T>(at: UnsafeRawPointer, fromByteOffset: Int = 0, as: T.Type) -> T { let offset = at.load(fromByteOffset: fromByteOffset, as: Int32.self) return unsafeBitCast(_resolveRelativeAddress(at + fromByteOffset, offset), to: T.self) } internal func _walkKeyPathPattern<W: KeyPathPatternVisitor>( _ pattern: UnsafeRawPointer, walker: inout W) { // Visit the header. let genericEnvironment = _loadRelativeAddress(at: pattern, as: UnsafeRawPointer.self) let rootMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 4, as: MetadataReference.self) let leafMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 8, as: MetadataReference.self) let kvcString = _loadRelativeAddress(at: pattern, fromByteOffset: 12, as: UnsafeRawPointer.self) walker.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcString) func visitStored(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) { // Decode a stored property. A small offset may be stored inline in the // header word, or else be stored out-of-line, or need instantiation of some // kind. let offset: KeyPathPatternStoredOffset switch header.storedOffsetPayload { case RawKeyPathComponent.Header.outOfLineOffsetPayload: offset = .outOfLine(_pop(from: &componentBuffer, as: UInt32.self)) case RawKeyPathComponent.Header.unresolvedFieldOffsetPayload: offset = .unresolvedFieldOffset(_pop(from: &componentBuffer, as: UInt32.self)) case RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload: let base = componentBuffer.baseAddress.unsafelyUnwrapped let relativeOffset = _pop(from: &componentBuffer, as: Int32.self) let ptr = _resolveRelativeIndirectableAddress(base, relativeOffset) offset = .unresolvedIndirectOffset( ptr.assumingMemoryBound(to: UInt.self)) default: offset = .inline(header.storedOffsetPayload) } let kind: KeyPathStructOrClass = header.kind == .struct ? .struct : .class walker.visitStoredComponent(kind: kind, mutable: header.isStoredMutable, offset: offset) } func popComputedAccessors(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) -> (idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?) { let idValueBase = componentBuffer.baseAddress.unsafelyUnwrapped let idValue = _pop(from: &componentBuffer, as: Int32.self) let getterBase = componentBuffer.baseAddress.unsafelyUnwrapped let getterRef = _pop(from: &componentBuffer, as: Int32.self) let getter = _resolveRelativeAddress(getterBase, getterRef) let setter: UnsafeRawPointer? if header.isComputedSettable { let setterBase = componentBuffer.baseAddress.unsafelyUnwrapped let setterRef = _pop(from: &componentBuffer, as: Int32.self) setter = _resolveRelativeAddress(setterBase, setterRef) } else { setter = nil } return (idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter) } func popComputedArguments(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) -> KeyPathPatternComputedArguments? { if header.hasComputedArguments { let getLayoutBase = componentBuffer.baseAddress.unsafelyUnwrapped let getLayoutRef = _pop(from: &componentBuffer, as: Int32.self) let getLayoutRaw = _resolveRelativeAddress(getLayoutBase, getLayoutRef) let getLayout = unsafeBitCast(getLayoutRaw, to: KeyPathComputedArgumentLayoutFn.self) let witnessesBase = componentBuffer.baseAddress.unsafelyUnwrapped let witnessesRef = _pop(from: &componentBuffer, as: Int32.self) let witnesses: UnsafeRawPointer if witnessesRef == 0 { witnesses = __swift_keyPathGenericWitnessTable_addr() } else { witnesses = _resolveRelativeAddress(witnessesBase, witnessesRef) } let initializerBase = componentBuffer.baseAddress.unsafelyUnwrapped let initializerRef = _pop(from: &componentBuffer, as: Int32.self) let initializerRaw = _resolveRelativeAddress(initializerBase, initializerRef) let initializer = unsafeBitCast(initializerRaw, to: KeyPathComputedArgumentInitializerFn.self) return KeyPathPatternComputedArguments(getLayout: getLayout, witnesses: witnesses.assumingMemoryBound(to: ComputedArgumentWitnesses.self), initializer: initializer) } else { return nil } } // We declare this down here to avoid the temptation to use it within // the functions above. let bufferPtr = pattern.advanced(by: keyPathPatternHeaderSize) let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self) var buffer = UnsafeRawBufferPointer(start: bufferPtr + 4, count: bufferHeader.size) while !buffer.isEmpty { let header = _pop(from: &buffer, as: RawKeyPathComponent.Header.self) // Ensure that we pop an amount of data consistent with what // RawKeyPathComponent.Header.patternComponentBodySize computes. var bufferSizeBefore = 0 var expectedPop = 0 _internalInvariant({ bufferSizeBefore = buffer.count expectedPop = header.patternComponentBodySize return true }()) switch header.kind { case .class, .struct: visitStored(header: header, componentBuffer: &buffer) case .computed: let (idValueBase, idValue, getter, setter) = popComputedAccessors(header: header, componentBuffer: &buffer) // If there are arguments, gather those too. let arguments = popComputedArguments(header: header, componentBuffer: &buffer) walker.visitComputedComponent(mutating: header.isComputedMutating, idKind: header.computedIDKind, idResolution: header.computedIDResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: nil) case .optionalChain: walker.visitOptionalChainComponent() case .optionalWrap: walker.visitOptionalWrapComponent() case .optionalForce: walker.visitOptionalForceComponent() case .external: // Look at the external property descriptor to see if we should take it // over the component given in the pattern. let genericParamCount = Int(header.payload) let descriptorBase = buffer.baseAddress.unsafelyUnwrapped let descriptorOffset = _pop(from: &buffer, as: Int32.self) let descriptor = _resolveRelativeIndirectableAddress(descriptorBase, descriptorOffset) let descriptorHeader = descriptor.load(as: RawKeyPathComponent.Header.self) if descriptorHeader.isTrivialPropertyDescriptor { // If the descriptor is trivial, then use the local candidate. // Skip the external generic parameter accessors to get to it. _ = _pop(from: &buffer, as: Int32.self, count: genericParamCount) continue } // Grab the generic parameter accessors to pass to the external component. let externalArgs = _pop(from: &buffer, as: Int32.self, count: genericParamCount) // Grab the header for the local candidate in case we need it for // a computed property. let localCandidateHeader = _pop(from: &buffer, as: RawKeyPathComponent.Header.self) let localCandidateSize = localCandidateHeader.patternComponentBodySize _internalInvariant({ expectedPop += localCandidateSize + 4 return true }()) let descriptorSize = descriptorHeader.propertyDescriptorBodySize var descriptorBuffer = UnsafeRawBufferPointer(start: descriptor + 4, count: descriptorSize) // Look at what kind of component the external property has. switch descriptorHeader.kind { case .struct, .class: // A stored component. We can instantiate it // without help from the local candidate. _ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize) visitStored(header: descriptorHeader, componentBuffer: &descriptorBuffer) case .computed: // A computed component. The accessors come from the descriptor. let (idValueBase, idValue, getter, setter) = popComputedAccessors(header: descriptorHeader, componentBuffer: &descriptorBuffer) // Get the arguments from the external descriptor and/or local candidate // component. let arguments: KeyPathPatternComputedArguments? if localCandidateHeader.kind == .computed && localCandidateHeader.hasComputedArguments { // If both have arguments, then we have to build a bit of a chimera. // The canonical identity and accessors come from the descriptor, // but the argument equality/hash handling is still as described // in the local candidate. // We don't need the local candidate's accessors. _ = popComputedAccessors(header: localCandidateHeader, componentBuffer: &buffer) // We do need the local arguments. arguments = popComputedArguments(header: localCandidateHeader, componentBuffer: &buffer) } else { // If the local candidate doesn't have arguments, we don't need // anything from it at all. _ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize) arguments = nil } walker.visitComputedComponent( mutating: descriptorHeader.isComputedMutating, idKind: descriptorHeader.computedIDKind, idResolution: descriptorHeader.computedIDResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: genericParamCount > 0 ? externalArgs : nil) case .optionalChain, .optionalWrap, .optionalForce, .external: _internalInvariantFailure("not possible for property descriptor") } } // Check that we consumed the expected amount of data from the pattern. _internalInvariant( { // Round the amount of data we read up to alignment. let popped = MemoryLayout<Int32>._roundingUpToAlignment( bufferSizeBefore - buffer.count) return expectedPop == popped }(), """ component size consumed during pattern walk does not match \ component size returned by patternComponentBodySize """) // Break if this is the last component. if buffer.isEmpty { break } // Otherwise, pop the intermediate component type accessor and // go around again. let componentTypeBase = buffer.baseAddress.unsafelyUnwrapped let componentTypeOffset = _pop(from: &buffer, as: Int32.self) let componentTypeRef = _resolveRelativeAddress(componentTypeBase, componentTypeOffset) walker.visitIntermediateComponentType(metadataRef: componentTypeRef) _internalInvariant(!buffer.isEmpty) } // We should have walked the entire pattern. _internalInvariant(buffer.isEmpty, "did not walk entire pattern buffer") walker.finish() } internal struct GetKeyPathClassAndInstanceSizeFromPattern : KeyPathPatternVisitor { var size: Int = MemoryLayout<Int>.size // start with one word for the header var capability: KeyPathKind = .value var didChain: Bool = false var root: Any.Type! var leaf: Any.Type! var genericEnvironment: UnsafeRawPointer? let patternArgs: UnsafeRawPointer? init(patternArgs: UnsafeRawPointer?) { self.patternArgs = patternArgs } mutating func roundUpToPointerAlignment() { size = MemoryLayout<Int>._roundingUpToAlignment(size) } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { self.genericEnvironment = genericEnvironment // Get the root and leaf type metadata so we can form the class type // for the entire key path. root = _resolveKeyPathMetadataReference( rootMetadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) leaf = _resolveKeyPathMetadataReference( leafMetadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { // Mutable class properties can be the root of a reference mutation. // Mutable struct properties pass through the existing capability. if mutable { switch kind { case .class: capability = .reference case .struct: break } } else { // Immutable properties can only be read. capability = .readOnly } // The size of the instantiated component depends on whether we can fit // the offset inline. switch offset { case .inline: size += 4 case .outOfLine, .unresolvedFieldOffset, .unresolvedIndirectOffset: size += 8 } } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { let settable = setter != nil switch (settable, mutating) { case (false, false): // If the property is get-only, the capability becomes read-only, unless // we get another reference-writable component. capability = .readOnly case (true, false): capability = .reference case (true, true): // Writable if the base is. No effect. break case (false, true): _internalInvariantFailure("unpossible") } // Save space for the header... size += 4 roundUpToPointerAlignment() // ...id, getter, and maybe setter... size += MemoryLayout<Int>.size * 2 if settable { size += MemoryLayout<Int>.size } // ...and the arguments, if any. let argumentHeaderSize = MemoryLayout<Int>.size * 2 switch (arguments, externalArgs) { case (nil, nil): break case (let arguments?, nil): size += argumentHeaderSize // If we have arguments, calculate how much space they need by invoking // the layout function. let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs) // TODO: Handle over-aligned values _internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment, "overaligned computed property element not supported") size += addedSize case (let arguments?, let externalArgs?): // If we're referencing an external declaration, and it takes captured // arguments, then we have to build a bit of a chimera. The canonical // identity and accessors come from the descriptor, but the argument // handling is still as described in the local candidate. size += argumentHeaderSize let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs) // TODO: Handle over-aligned values _internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment, "overaligned computed property element not supported") size += addedSize // We also need to store the size of the local arguments so we can // find the external component arguments. roundUpToPointerAlignment() size += RawKeyPathComponent.Header.externalWithArgumentsExtraSize size += MemoryLayout<Int>.size * externalArgs.count case (nil, let externalArgs?): // If we're instantiating an external property with a local // candidate that has no arguments, then things are a little // easier. We only need to instantiate the generic // arguments for the external component's accessors. size += argumentHeaderSize size += MemoryLayout<Int>.size * externalArgs.count } } mutating func visitOptionalChainComponent() { // Optional chaining forces the entire keypath to be read-only, even if // there are further reference-writable components. didChain = true capability = .readOnly size += 4 } mutating func visitOptionalWrapComponent() { // Optional chaining forces the entire keypath to be read-only, even if // there are further reference-writable components. didChain = true capability = .readOnly size += 4 } mutating func visitOptionalForceComponent() { // Force-unwrapping passes through the mutability of the preceding keypath. size += 4 } mutating func visitIntermediateComponentType(metadataRef _: MetadataReference) { // The instantiated component type will be stored in the instantiated // object. roundUpToPointerAlignment() size += MemoryLayout<Int>.size } mutating func finish() { } } internal func _getKeyPathClassAndInstanceSizeFromPattern( _ pattern: UnsafeRawPointer, _ arguments: UnsafeRawPointer ) -> ( keyPathClass: AnyKeyPath.Type, rootType: Any.Type, size: Int, alignmentMask: Int ) { var walker = GetKeyPathClassAndInstanceSizeFromPattern(patternArgs: arguments) _walkKeyPathPattern(pattern, walker: &walker) // Chaining always renders the whole key path read-only. if walker.didChain { walker.capability = .readOnly } // Grab the class object for the key path type we'll end up with. func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type { func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type { switch walker.capability { case .readOnly: return KeyPath<Root, Leaf>.self case .value: return WritableKeyPath<Root, Leaf>.self case .reference: return ReferenceWritableKeyPath<Root, Leaf>.self } } return _openExistential(walker.leaf!, do: openLeaf) } let classTy = _openExistential(walker.root!, do: openRoot) return (keyPathClass: classTy, rootType: walker.root!, size: walker.size, // FIXME: Handle overalignment alignmentMask: MemoryLayout<Int>._alignmentMask) } internal struct InstantiateKeyPathBuffer: KeyPathPatternVisitor { var destData: UnsafeMutableRawBufferPointer var genericEnvironment: UnsafeRawPointer? let patternArgs: UnsafeRawPointer? var base: Any.Type init(destData: UnsafeMutableRawBufferPointer, patternArgs: UnsafeRawPointer?, root: Any.Type) { self.destData = destData self.patternArgs = patternArgs self.base = root } // Track the triviality of the resulting object data. var isTrivial: Bool = true // Track where the reference prefix begins. var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil var previousComponentAddr: UnsafeMutableRawPointer? = nil mutating func pushDest<T>(_ value: T) { _internalInvariant(_isPOD(T.self)) let size = MemoryLayout<T>.size let alignment = MemoryLayout<T>.alignment var baseAddress = destData.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } withUnsafeBytes(of: value) { _memcpy(dest: baseAddress, src: $0.baseAddress.unsafelyUnwrapped, size: UInt(size)) } destData = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destData.count - size - misalign) } mutating func updatePreviousComponentAddr() -> UnsafeMutableRawPointer? { let oldValue = previousComponentAddr previousComponentAddr = destData.baseAddress.unsafelyUnwrapped return oldValue } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { self.genericEnvironment = genericEnvironment } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { let previous = updatePreviousComponentAddr() switch kind { case .class: // A mutable class property can end the reference prefix. if mutable { endOfReferencePrefixComponent = previous } fallthrough case .struct: // Resolve the offset. switch offset { case .inline(let value): let header = RawKeyPathComponent.Header(stored: kind, mutable: mutable, inlineOffset: value) pushDest(header) case .outOfLine(let offset): let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) case .unresolvedFieldOffset(let offsetOfOffset): // Look up offset in the type metadata. The value in the pattern is // the offset within the metadata object. let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self) let offset: UInt32 switch kind { case .class: offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset), as: UInt.self)) case .struct: offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset), as: UInt32.self)) } let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) case .unresolvedIndirectOffset(let pointerToOffset): // Look up offset in the indirectly-referenced variable we have a // pointer. assert(pointerToOffset.pointee <= UInt32.max) let offset = UInt32(truncatingIfNeeded: pointerToOffset.pointee) let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) } } } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { let previous = updatePreviousComponentAddr() let settable = setter != nil // A nonmutating settable property can end the reference prefix. if settable && !mutating { endOfReferencePrefixComponent = previous } // Resolve the ID. let resolvedID: UnsafeRawPointer? switch idKind { case .storedPropertyIndex, .vtableOffset: _internalInvariant(idResolution == .resolved) // Zero-extend the integer value to get the instantiated id. let value = UInt(UInt32(bitPattern: idValue)) resolvedID = UnsafeRawPointer(bitPattern: value) case .pointer: // Resolve the sign-extended relative reference. var absoluteID: UnsafeRawPointer? = idValueBase + Int(idValue) // If the pointer ID is unresolved, then it needs work to get to // the final value. switch idResolution { case .resolved: break case .indirectPointer: // The pointer in the pattern is an indirect pointer to the real // identifier pointer. absoluteID = absoluteID.unsafelyUnwrapped .load(as: UnsafeRawPointer?.self) case .functionCall: // The pointer in the pattern is to a function that generates the // identifier pointer. typealias Resolver = @convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer? let resolverFn = unsafeBitCast(absoluteID.unsafelyUnwrapped, to: Resolver.self) absoluteID = resolverFn(patternArgs) } resolvedID = absoluteID } // Bring over the header, getter, and setter. let header = RawKeyPathComponent.Header(computedWithIDKind: idKind, mutating: mutating, settable: settable, hasArguments: arguments != nil || externalArgs != nil, instantiatedFromExternalWithArguments: arguments != nil && externalArgs != nil) pushDest(header) pushDest(resolvedID) pushDest(getter) if let setter = setter { pushDest(setter) } if let arguments = arguments { // Instantiate the arguments. let (baseSize, alignmentMask) = arguments.getLayout(patternArgs) _internalInvariant(alignmentMask < MemoryLayout<Int>.alignment, "overaligned computed arguments not implemented yet") // The real buffer stride will be rounded up to alignment. var totalSize = (baseSize + alignmentMask) & ~alignmentMask // If an external property descriptor also has arguments, they'll be // added to the end with pointer alignment. if let externalArgs = externalArgs { totalSize = MemoryLayout<Int>._roundingUpToAlignment(totalSize) totalSize += MemoryLayout<Int>.size * externalArgs.count } pushDest(totalSize) pushDest(arguments.witnesses) // A nonnull destructor in the witnesses file indicates the instantiated // payload is nontrivial. if let _ = arguments.witnesses.pointee.destroy { isTrivial = false } // If the descriptor has arguments, store the size of its specific // arguments here, so we can drop them when trying to invoke // the component's witnesses. if let externalArgs = externalArgs { pushDest(externalArgs.count * MemoryLayout<Int>.size) } // Initialize the local candidate arguments here. _internalInvariant(Int(bitPattern: destData.baseAddress) & alignmentMask == 0, "argument destination not aligned") arguments.initializer(patternArgs, destData.baseAddress.unsafelyUnwrapped) destData = UnsafeMutableRawBufferPointer( start: destData.baseAddress.unsafelyUnwrapped + baseSize, count: destData.count - baseSize) } if let externalArgs = externalArgs { if arguments == nil { // If we're instantiating an external property without any local // arguments, then we only need to instantiate the arguments to the // property descriptor. let stride = MemoryLayout<Int>.size * externalArgs.count pushDest(stride) pushDest(__swift_keyPathGenericWitnessTable_addr()) } // Write the descriptor's generic arguments, which should all be relative // references to metadata accessor functions. for i in externalArgs.indices { let base = externalArgs.baseAddress.unsafelyUnwrapped + i let offset = base.pointee let metadataRef = UnsafeRawPointer(base) + Int(offset) let result = _resolveKeyPathGenericArgReference( metadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) pushDest(result) } } } mutating func visitOptionalChainComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalChain: ()) pushDest(header) } mutating func visitOptionalWrapComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalWrap: ()) pushDest(header) } mutating func visitOptionalForceComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalForce: ()) pushDest(header) } mutating func visitIntermediateComponentType(metadataRef: MetadataReference) { // Get the metadata for the intermediate type. let metadata = _resolveKeyPathMetadataReference( metadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) pushDest(metadata) base = metadata } mutating func finish() { // Should have filled the entire buffer by the time we reach the end of the // pattern. _internalInvariant(destData.isEmpty, "should have filled entire destination buffer") } } #if INTERNAL_CHECKS_ENABLED // In debug builds of the standard library, check that instantiation produces // components whose sizes are consistent with the sizing visitor pass. internal struct ValidatingInstantiateKeyPathBuffer: KeyPathPatternVisitor { var sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern var instantiateVisitor: InstantiateKeyPathBuffer let origDest: UnsafeMutableRawPointer init(sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern, instantiateVisitor: InstantiateKeyPathBuffer) { self.sizeVisitor = sizeVisitor self.instantiateVisitor = instantiateVisitor origDest = self.instantiateVisitor.destData.baseAddress.unsafelyUnwrapped } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { sizeVisitor.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcCompatibilityString) instantiateVisitor.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcCompatibilityString) } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { sizeVisitor.visitStoredComponent(kind: kind, mutable: mutable, offset: offset) instantiateVisitor.visitStoredComponent(kind: kind, mutable: mutable, offset: offset) checkSizeConsistency() } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { sizeVisitor.visitComputedComponent(mutating: mutating, idKind: idKind, idResolution: idResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: externalArgs) instantiateVisitor.visitComputedComponent(mutating: mutating, idKind: idKind, idResolution: idResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: externalArgs) checkSizeConsistency() } mutating func visitOptionalChainComponent() { sizeVisitor.visitOptionalChainComponent() instantiateVisitor.visitOptionalChainComponent() checkSizeConsistency() } mutating func visitOptionalWrapComponent() { sizeVisitor.visitOptionalWrapComponent() instantiateVisitor.visitOptionalWrapComponent() checkSizeConsistency() } mutating func visitOptionalForceComponent() { sizeVisitor.visitOptionalForceComponent() instantiateVisitor.visitOptionalForceComponent() checkSizeConsistency() } mutating func visitIntermediateComponentType(metadataRef: MetadataReference) { sizeVisitor.visitIntermediateComponentType(metadataRef: metadataRef) instantiateVisitor.visitIntermediateComponentType(metadataRef: metadataRef) checkSizeConsistency() } mutating func finish() { sizeVisitor.finish() instantiateVisitor.finish() checkSizeConsistency() } func checkSizeConsistency() { let nextDest = instantiateVisitor.destData.baseAddress.unsafelyUnwrapped let curSize = nextDest - origDest + MemoryLayout<Int>.size _internalInvariant(curSize == sizeVisitor.size, "size and instantiation visitors out of sync") } } #endif // INTERNAL_CHECKS_ENABLED internal func _instantiateKeyPathBuffer( _ pattern: UnsafeRawPointer, _ origDestData: UnsafeMutableRawBufferPointer, _ rootType: Any.Type, _ arguments: UnsafeRawPointer ) { let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped var destData = UnsafeMutableRawBufferPointer( start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size), count: origDestData.count - MemoryLayout<Int>.size) #if INTERNAL_CHECKS_ENABLED // If checks are enabled, use a validating walker that ensures that the // size pre-walk and instantiation walk are in sync. let sizeWalker = GetKeyPathClassAndInstanceSizeFromPattern( patternArgs: arguments) let instantiateWalker = InstantiateKeyPathBuffer( destData: destData, patternArgs: arguments, root: rootType) var walker = ValidatingInstantiateKeyPathBuffer(sizeVisitor: sizeWalker, instantiateVisitor: instantiateWalker) #else var walker = InstantiateKeyPathBuffer( destData: destData, patternArgs: arguments, root: rootType) #endif _walkKeyPathPattern(pattern, walker: &walker) #if INTERNAL_CHECKS_ENABLED let isTrivial = walker.instantiateVisitor.isTrivial let endOfReferencePrefixComponent = walker.instantiateVisitor.endOfReferencePrefixComponent #else let isTrivial = walker.isTrivial let endOfReferencePrefixComponent = walker.endOfReferencePrefixComponent #endif // Write out the header. let destHeader = KeyPathBuffer.Header( size: origDestData.count - MemoryLayout<Int>.size, trivial: isTrivial, hasReferencePrefix: endOfReferencePrefixComponent != nil) destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self) // Mark the reference prefix if there is one. if let endOfReferencePrefixComponent = endOfReferencePrefixComponent { var componentHeader = endOfReferencePrefixComponent .load(as: RawKeyPathComponent.Header.self) componentHeader.endOfReferencePrefix = true endOfReferencePrefixComponent.storeBytes(of: componentHeader, as: RawKeyPathComponent.Header.self) } }
apache-2.0
34e9e700ab38164c2daf014c7a98e036
36.668575
96
0.652362
5.010049
false
false
false
false
montehurd/apps-ios-wikipedia
Wikipedia/Code/PageHistoryViewController.swift
1
38076
import UIKit import WMF typealias PageHistoryCollectionViewCellSelectionThemeModel = PageHistoryViewController.SelectionThemeModel enum SelectionOrder: Int, CaseIterable { case first case second init?(_ rawValue: Int?) { if let rawValue = rawValue, let SelectionOrder = SelectionOrder(rawValue: rawValue) { self = SelectionOrder } else { return nil } } } @objc(WMFPageHistoryViewController) class PageHistoryViewController: ColumnarCollectionViewController { private let pageTitle: String private let pageURL: URL private let pageHistoryFetcher = PageHistoryFetcher() private var pageHistoryFetcherParams: PageHistoryRequestParameters private var batchComplete = false private var isLoadingData = false private var cellLayoutEstimate: ColumnarCollectionViewLayoutHeightEstimate? private var firstRevision: WMFPageHistoryRevision? var shouldLoadNewData: Bool { if batchComplete || isLoadingData { return false } let maxY = collectionView.contentOffset.y + collectionView.frame.size.height + 200.0; if (maxY >= collectionView.contentSize.height) { return true } return false; } private lazy var countsViewController = PageHistoryCountsViewController(pageTitle: pageTitle, locale: NSLocale.wmf_locale(for: pageURL.wmf_language)) private lazy var comparisonSelectionViewController: PageHistoryComparisonSelectionViewController = { let comparisonSelectionViewController = PageHistoryComparisonSelectionViewController(nibName: "PageHistoryComparisonSelectionViewController", bundle: nil) comparisonSelectionViewController.delegate = self return comparisonSelectionViewController }() @objc init(pageTitle: String, pageURL: URL) { self.pageTitle = pageTitle self.pageURL = pageURL self.pageHistoryFetcherParams = PageHistoryRequestParameters(title: pageTitle) super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var pageHistorySections: [PageHistorySection] = [] override var headerStyle: ColumnarCollectionViewController.HeaderStyle { return .sections } private lazy var compareButton: UIBarButtonItem = { let button = UIBarButtonItem(title: CommonStrings.compareTitle, style: .plain, target: self, action: #selector(compare(_:))) button.accessibilityHint = WMFLocalizedString("page-history-compare-accessibility-hint", value: "Tap to select two revisions to compare", comment: "Accessibility hint describing the role of the Compare button") return button }() private lazy var cancelComparisonButton = UIBarButtonItem(title: CommonStrings.cancelActionTitle, style: .done, target: self, action: #selector(cancelComparison(_:))) private var comparisonSelectionViewHeightConstraint: NSLayoutConstraint? private var comparisonSelectionViewVisibleConstraint: NSLayoutConstraint? private var comparisonSelectionViewHiddenConstraint: NSLayoutConstraint? private enum State { case idle case editing } private var maxNumberOfRevisionsSelected: Bool { assert((0...SelectionOrder.allCases.count).contains(selectedCellsCount)) return selectedCellsCount == 2 } private var selectedCellsCount = 0 private var pageHistoryHintController: PageHistoryHintController? { return hintController as? PageHistoryHintController } private var state: State = .idle { didSet { switch state { case .idle: selectedCellsCount = 0 pageHistoryHintController?.hide(true, presenter: self, subview: comparisonSelectionViewController.view, additionalBottomSpacing: comparisonSelectionViewController.view.frame.height - view.safeAreaInsets.bottom, theme: theme) openSelectionIndex = 0 UIView.performWithoutAnimation { self.navigationItem.rightBarButtonItem = compareButton } indexPathsSelectedForComparisonGroupedByButtonTags.removeAll(keepingCapacity: true) comparisonSelectionViewController.resetSelectionButtons() case .editing: UIView.performWithoutAnimation { self.navigationItem.rightBarButtonItem = cancelComparisonButton } collectionView.allowsMultipleSelection = true comparisonSelectionViewController.setCompareButtonEnabled(false) } setComparisonSelectionViewHidden(state == .idle, animated: true) layoutCache.reset() collectionView.performBatchUpdates({ self.collectionView.reloadSections(IndexSet(integersIn: 0..<collectionView.numberOfSections)) }) } } private var comparisonSelectionButtonWidthConstraints = [NSLayoutConstraint]() private func setupComparisonSelectionViewController() { addChild(comparisonSelectionViewController) comparisonSelectionViewController.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(comparisonSelectionViewController.view) comparisonSelectionViewController.didMove(toParent: self) comparisonSelectionViewVisibleConstraint = view.bottomAnchor.constraint(equalTo: comparisonSelectionViewController.view.bottomAnchor) comparisonSelectionViewHiddenConstraint = view.bottomAnchor.constraint(equalTo: comparisonSelectionViewController.view.topAnchor) let leadingConstraint = view.leadingAnchor.constraint(equalTo: comparisonSelectionViewController.view.leadingAnchor) let trailingConstraint = view.trailingAnchor.constraint(equalTo: comparisonSelectionViewController.view.trailingAnchor) NSLayoutConstraint.activate([comparisonSelectionViewHiddenConstraint!, leadingConstraint, trailingConstraint]) } private func setComparisonSelectionViewHidden(_ hidden: Bool, animated: Bool) { let changes = { if hidden { self.comparisonSelectionViewVisibleConstraint?.isActive = false self.comparisonSelectionViewHiddenConstraint?.isActive = true } else { self.comparisonSelectionViewHiddenConstraint?.isActive = false self.comparisonSelectionViewVisibleConstraint?.isActive = true } self.view.layoutIfNeeded() } if animated { UIView.animate(withDuration: 0.3, animations: changes) } else { changes() } } override func viewDidLoad() { super.viewDidLoad() hintController = PageHistoryHintController() title = CommonStrings.historyTabTitle navigationItem.rightBarButtonItem = compareButton addChild(countsViewController) navigationBar.addUnderNavigationBarView(countsViewController.view) navigationBar.shadowColorKeyPath = \Theme.colors.border countsViewController.didMove(toParent: self) navigationBar.isBarHidingEnabled = false navigationBar.isUnderBarViewHidingEnabled = true layoutManager.register(PageHistoryCollectionViewCell.self, forCellWithReuseIdentifier: PageHistoryCollectionViewCell.identifier, addPlaceholder: true) collectionView.dataSource = self view.wmf_addSubviewWithConstraintsToEdges(collectionView) setupComparisonSelectionViewController() apply(theme: theme) getEditCounts() getPageHistory() } private func getEditCounts() { pageHistoryFetcher.fetchFirstRevision(for: pageTitle, pageURL: pageURL) { [weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.showNoInternetConnectionAlertOrOtherWarning(from: error) case .success(let firstRevision): self.firstRevision = firstRevision let firstEditDate = firstRevision.revisionDate self.pageHistoryFetcher.fetchEditCounts(.edits, for: self.pageTitle, pageURL: self.pageURL) { [weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.showNoInternetConnectionAlertOrOtherWarning(from: error) case .success(let editCounts): if let totalEditResponse = editCounts[.edits] { DispatchQueue.main.async { let totalEditCount = totalEditResponse.count if let firstEditDate = firstEditDate, totalEditResponse.limit == false { self.countsViewController.set(totalEditCount: totalEditCount, firstEditDate: firstEditDate) } } } } } } } pageHistoryFetcher.fetchEditCounts(.edits, .userEdits, .anonymous, .bot, for: pageTitle, pageURL: pageURL) { [weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.showNoInternetConnectionAlertOrOtherWarning(from: error) case .success(let editCountsGroupedByType): DispatchQueue.main.async { self.countsViewController.editCountsGroupedByType = editCountsGroupedByType } } } pageHistoryFetcher.fetchEditMetrics(for: pageTitle, pageURL: pageURL) { [weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.showNoInternetConnectionAlertOrOtherWarning(from: error) self.countsViewController.timeseriesOfEditsCounts = [] case .success(let timeseriesOfEditCounts): DispatchQueue.main.async { self.countsViewController.timeseriesOfEditsCounts = timeseriesOfEditCounts } } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cancelComparison(nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) cellLayoutEstimate = nil } private func getPageHistory() { isLoadingData = true pageHistoryFetcher.fetchRevisionInfo(pageURL, requestParams: pageHistoryFetcherParams, failure: { [weak self] error in guard let self = self else { return } self.isLoadingData = false self.showNoInternetConnectionAlertOrOtherWarning(from: error) }) { results in self.pageHistorySections.append(contentsOf: results.items()) self.pageHistoryFetcherParams = results.getPageHistoryRequestParameters(self.pageURL) self.batchComplete = results.batchComplete() self.isLoadingData = false DispatchQueue.main.async { self.collectionView.reloadData() } } } override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) guard shouldLoadNewData else { return } getPageHistory() } @objc private func compare(_ sender: UIBarButtonItem) { state = .editing } @objc private func cancelComparison(_ sender: UIBarButtonItem?) { state = .idle } private func forEachVisibleCell(_ block: (IndexPath, PageHistoryCollectionViewCell) -> Void) { for indexPath in collectionView.indexPathsForVisibleItems { guard let pageHistoryCollectionViewCell = collectionView.cellForItem(at: indexPath) as? PageHistoryCollectionViewCell else { continue } block(indexPath, pageHistoryCollectionViewCell) } } private func showDiff(from: WMFPageHistoryRevision?, to: WMFPageHistoryRevision, type: DiffContainerViewModel.DiffType) { if let siteURL = pageURL.wmf_site { let diffContainerVC = DiffContainerViewController(articleTitle: pageTitle, siteURL: siteURL, type: type, fromModel: from, toModel: to, pageHistoryFetcher: pageHistoryFetcher, theme: theme, revisionRetrievingDelegate: self, firstRevision: firstRevision) wmf_push(diffContainerVC, animated: true) } } override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = view.backgroundColor compareButton.tintColor = theme.colors.link cancelComparisonButton.tintColor = theme.colors.link countsViewController.apply(theme: theme) comparisonSelectionViewController.apply(theme: theme) } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return pageHistorySections.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageHistorySections[section].items.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PageHistoryCollectionViewCell.identifier, for: indexPath) as? PageHistoryCollectionViewCell else { return UICollectionViewCell() } configure(cell: cell, at: indexPath) return cell } override func configure(header: CollectionViewHeader, forSectionAt sectionIndex: Int, layoutOnly: Bool) { let section = pageHistorySections[sectionIndex] let sectionTitle: String? if sectionIndex == 0, let date = section.items.first?.revisionDate { sectionTitle = (date as NSDate).wmf_localizedRelativeDateFromMidnightUTCDate() } else { sectionTitle = section.sectionTitle } header.style = .pageHistory header.title = sectionTitle header.titleTextColorKeyPath = \Theme.colors.secondaryText header.layoutMargins = .zero header.apply(theme: theme) } // MARK: Layout // Reset on refresh private var cellContentCache = NSCache<NSNumber, CellContent>() private class CellContent: NSObject { let time: String? let displayTime: String? let author: String? let authorImage: UIImage? let sizeDiff: Int? let comment: String? var selectionThemeModel: SelectionThemeModel? var selectionOrderRawValue: Int? init(time: String?, displayTime: String?, author: String?, authorImage: UIImage?, sizeDiff: Int?, comment: String?, selectionThemeModel: SelectionThemeModel?, selectionOrderRawValue: Int?) { self.time = time self.displayTime = displayTime self.author = author self.authorImage = authorImage self.sizeDiff = sizeDiff self.comment = comment self.selectionThemeModel = selectionThemeModel self.selectionOrderRawValue = selectionOrderRawValue super.init() } } private func configure(cell: PageHistoryCollectionViewCell, for item: WMFPageHistoryRevision? = nil, at indexPath: IndexPath) { let item = item ?? pageHistorySections[indexPath.section].items[indexPath.item] let revisionID = NSNumber(value: item.revisionID) let isSelected = indexPathsSelectedForComparison.contains(indexPath) defer { cell.setEditing(state == .editing) if !isSelected { cell.enableEditing(!maxNumberOfRevisionsSelected) } cell.apply(theme: theme) } if let cachedCellContent = cellContentCache.object(forKey: revisionID) { cell.time = cachedCellContent.time cell.displayTime = cachedCellContent.displayTime cell.authorImage = cachedCellContent.authorImage cell.author = cachedCellContent.author cell.sizeDiff = cachedCellContent.sizeDiff cell.comment = cachedCellContent.comment if state == .editing { if cachedCellContent.selectionOrderRawValue != nil { cell.isSelected = true collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) } if isSelected { cell.selectionThemeModel = cachedCellContent.selectionThemeModel } else { cell.selectionThemeModel = maxNumberOfRevisionsSelected ? disabledSelectionThemeModel : nil cell.isSelected = false } cell.selectionOrder = SelectionOrder(cachedCellContent.selectionOrderRawValue) } else { cell.selectionOrder = nil cell.selectionThemeModel = nil cell.isSelected = false } } else { if let date = item.revisionDate { if indexPath.section == 0, (date as NSDate).wmf_isTodayUTC() { let dateStrings = (date as NSDate).wmf_localizedRelativeDateStringFromLocalDateToNowAbbreviated() cell.time = dateStrings[WMFAbbreviatedRelativeDate] cell.displayTime = dateStrings[WMFAbbreviatedRelativeDateAgo] } else { cell.time = DateFormatter.wmf_24hshortTime()?.string(from: date) cell.displayTime = DateFormatter.wmf_24hshortTimeWithUTCTimeZone()?.string(from: date) } } cell.authorImage = item.isAnon ? UIImage(named: "anon") : UIImage(named: "user-edit") cell.author = item.user cell.sizeDiff = item.revisionSize cell.comment = item.parsedComment?.removingHTML if isSelected, let selectionIndex = indexPathsSelectedForComparisonGroupedByButtonTags.first(where: { $0.value == indexPath })?.key { cell.isSelected = true collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) cell.selectionThemeModel = selectionIndex == 0 ? firstSelectionThemeModel : secondSelectionThemeModel cell.selectionOrder = SelectionOrder(rawValue: selectionIndex) } else { cell.selectionThemeModel = maxNumberOfRevisionsSelected ? disabledSelectionThemeModel : nil } } cell.isMinor = item.isMinor cell.layoutMargins = layout.itemLayoutMargins cellContentCache.setObject(CellContent(time: cell.time, displayTime: cell.displayTime, author: cell.author, authorImage: cell.authorImage, sizeDiff: cell.sizeDiff, comment: cell.comment, selectionThemeModel: cell.selectionThemeModel, selectionOrderRawValue: cell.selectionOrder?.rawValue), forKey: revisionID) cell.apply(theme: theme) } private func revisionID(forItemAtIndexPath indexPath: IndexPath) -> NSNumber { let item = pageHistorySections[indexPath.section].items[indexPath.item] return NSNumber(value: item.revisionID) } override func contentSizeCategoryDidChange(_ notification: Notification?) { layoutCache.reset() super.contentSizeCategoryDidChange(notification) } private func updateSelectionThemeModel(_ selectionThemeModel: SelectionThemeModel?, for cell: PageHistoryCollectionViewCell, at indexPath: IndexPath) { cell.selectionThemeModel = selectionThemeModel cellContentCache.object(forKey: revisionID(forItemAtIndexPath: indexPath))?.selectionThemeModel = selectionThemeModel } private func updateSelectionOrder(_ selectionOrder: SelectionOrder?, for cell: PageHistoryCollectionViewCell, at indexPath: IndexPath) { cell.selectionOrder = selectionOrder cellContentCache.object(forKey: revisionID(forItemAtIndexPath: indexPath))?.selectionOrderRawValue = selectionOrder?.rawValue } public class SelectionThemeModel { let selectedImage: UIImage? let borderColor: UIColor let backgroundColor: UIColor let authorColor: UIColor let commentColor: UIColor let timeColor: UIColor let sizeDiffAdditionColor: UIColor let sizeDiffSubtractionColor: UIColor let sizeDiffNoDifferenceColor: UIColor init(selectedImage: UIImage?, borderColor: UIColor, backgroundColor: UIColor, authorColor: UIColor, commentColor: UIColor, timeColor: UIColor, sizeDiffAdditionColor: UIColor, sizeDiffSubtractionColor: UIColor, sizeDiffNoDifferenceColor: UIColor) { self.selectedImage = selectedImage self.borderColor = borderColor self.backgroundColor = backgroundColor self.authorColor = authorColor self.commentColor = commentColor self.timeColor = timeColor self.sizeDiffAdditionColor = sizeDiffAdditionColor self.sizeDiffSubtractionColor = sizeDiffSubtractionColor self.sizeDiffNoDifferenceColor = sizeDiffNoDifferenceColor } } private lazy var firstSelectionThemeModel: SelectionThemeModel = { let backgroundColor: UIColor let timeColor: UIColor if theme.isDark { backgroundColor = UIColor.osage15PercentAlpha timeColor = theme.colors.tertiaryText } else { backgroundColor = UIColor.wmf_lightYellow timeColor = .battleshipGray } return SelectionThemeModel(selectedImage: UIImage(named: "selected-accent"), borderColor: UIColor.osage.withAlphaComponent(0.5), backgroundColor: backgroundColor, authorColor: UIColor.osage, commentColor: theme.colors.primaryText, timeColor: timeColor, sizeDiffAdditionColor: theme.colors.accent, sizeDiffSubtractionColor: theme.colors.destructive, sizeDiffNoDifferenceColor: theme.colors.link) }() private lazy var secondSelectionThemeModel: SelectionThemeModel = { let backgroundColor: UIColor let timeColor: UIColor if theme.isDark { backgroundColor = theme.colors.link.withAlphaComponent(0.2) timeColor = theme.colors.tertiaryText } else { backgroundColor = UIColor.wmf_lightBlue timeColor = .battleshipGray } return SelectionThemeModel(selectedImage: nil, borderColor: theme.colors.link, backgroundColor: backgroundColor, authorColor: theme.colors.link, commentColor: theme.colors.primaryText, timeColor: timeColor, sizeDiffAdditionColor: theme.colors.accent, sizeDiffSubtractionColor: theme.colors.destructive, sizeDiffNoDifferenceColor: theme.colors.link) }() private lazy var disabledSelectionThemeModel: SelectionThemeModel = { return SelectionThemeModel(selectedImage: nil, borderColor: theme.colors.border, backgroundColor: theme.colors.paperBackground, authorColor: theme.colors.secondaryText, commentColor: theme.colors.secondaryText, timeColor: .battleshipGray, sizeDiffAdditionColor: theme.colors.secondaryText, sizeDiffSubtractionColor: theme.colors.secondaryText, sizeDiffNoDifferenceColor: theme.colors.secondaryText) }() override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { let identifier = PageHistoryCollectionViewCell.identifier let item = pageHistorySections[indexPath.section].items[indexPath.item] let userInfo = "phc-cell-\(item.revisionID)" if let cachedHeight = layoutCache.cachedHeightForCellWithIdentifier(identifier, columnWidth: columnWidth, userInfo: userInfo) { return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: cachedHeight) } var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 80) guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: PageHistoryCollectionViewCell.identifier) as? PageHistoryCollectionViewCell else { return estimate } configure(cell: placeholderCell, for: item, at: indexPath) estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true layoutCache.setHeight(estimate.height, forCellWithIdentifier: identifier, columnWidth: columnWidth, userInfo: userInfo) return estimate } override func metrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics { return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: boundsSize, readableWidth: readableWidth, layoutMargins: layoutMargins, interSectionSpacing: 0, interItemSpacing: 20) } private var postedMaxRevisionsSelectedAccessibilityNotification = false func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { switch state { case .editing: if maxNumberOfRevisionsSelected { pageHistoryHintController?.hide(false, presenter: self, subview: comparisonSelectionViewController.view, additionalBottomSpacing: comparisonSelectionViewController.view.frame.height - view.safeAreaInsets.bottom, theme: theme) if !postedMaxRevisionsSelectedAccessibilityNotification { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: CommonStrings.maxRevisionsSelectedWarningTitle) postedMaxRevisionsSelectedAccessibilityNotification = true } return false } else { return true } case .idle: return true } } private func pushToSingleRevisionDiff(indexPath: IndexPath) { guard let section = pageHistorySections[safeIndex: indexPath.section] else { return } if let toRevision = section.items[safeIndex: indexPath.item] { var sectionOffset = 0 var fromItemIndex = indexPath.item + 1 //if last revision in section, go to next section for selecting second let isLastInSection = indexPath.item == section.items.count - 1 if isLastInSection { sectionOffset = 1 fromItemIndex = 0 } let fromRevision = pageHistorySections[safeIndex: indexPath.section + sectionOffset]?.items[safeIndex: fromItemIndex] showDiff(from: fromRevision, to: toRevision, type: .single) } } var openSelectionIndex = 0 private var indexPathsSelectedForComparisonGroupedByButtonTags = [Int: IndexPath]() { didSet { indexPathsSelectedForComparison = Set(indexPathsSelectedForComparisonGroupedByButtonTags.values) } } private var indexPathsSelectedForComparison = Set<IndexPath>() private func selectionThemeModel(for selectionOrder: SelectionOrder) -> SelectionThemeModel? { if selectionOrder == .first { return firstSelectionThemeModel } else if selectionOrder == .second { return secondSelectionThemeModel } else { return nil } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if state == .editing { selectedCellsCount += 1 defer { comparisonSelectionViewController.setCompareButtonEnabled(maxNumberOfRevisionsSelected) } guard let cell = collectionView.cellForItem(at: indexPath) as? PageHistoryCollectionViewCell else { return } if maxNumberOfRevisionsSelected { assert(indexPathsSelectedForComparisonGroupedByButtonTags.count == 1) if let previouslySelectedIndexPath = indexPathsSelectedForComparisonGroupedByButtonTags.first?.value, let previouslySelectedCell = collectionView.cellForItem(at: previouslySelectedIndexPath) as? PageHistoryCollectionViewCell, let newSelectionOrder = SelectionOrder(rawValue: openSelectionIndex), let previousSelectionOrder = previouslySelectedCell.selectionOrder { if previouslySelectedIndexPath > indexPath, previousSelectionOrder == .first { swapSelection(.second, newSelectionOrder: newSelectionOrder, for: previouslySelectedCell, at: previouslySelectedIndexPath) openSelectionIndex = previousSelectionOrder.rawValue } else if previouslySelectedIndexPath < indexPath, previousSelectionOrder == .second { swapSelection(.first, newSelectionOrder: newSelectionOrder, for: previouslySelectedCell, at: previouslySelectedIndexPath) openSelectionIndex = previousSelectionOrder.rawValue } } forEachVisibleCell { (indexPath: IndexPath, cell: PageHistoryCollectionViewCell) in if !cell.isSelected { self.updateSelectionThemeModel(self.disabledSelectionThemeModel, for: cell, at: indexPath) } cell.enableEditing(false) } } if let selectionOrder = SelectionOrder(rawValue: openSelectionIndex), let themeModel = selectionThemeModel(for: selectionOrder) { comparisonSelectionViewController.updateSelectionButton(selectionOrder, with: themeModel, cell: cell) updateSelectionThemeModel(themeModel, for: cell, at: indexPath) indexPathsSelectedForComparisonGroupedByButtonTags[openSelectionIndex] = indexPath updateSelectionOrder(selectionOrder, for: cell, at: indexPath) openSelectionIndex += 1 collectionView.reloadData() } } else { let cell = collectionView.cellForItem(at: indexPath) cell?.isSelected = false pushToSingleRevisionDiff(indexPath: indexPath) } } private func swapSelection(_ selectionOrder: SelectionOrder, newSelectionOrder: SelectionOrder, for cell: PageHistoryCollectionViewCell, at indexPath: IndexPath) { guard let newSelectionThemeModel = selectionThemeModel(for: selectionOrder) else { return } comparisonSelectionViewController.updateSelectionButton(newSelectionOrder, with: newSelectionThemeModel, cell: cell) indexPathsSelectedForComparisonGroupedByButtonTags[selectionOrder.rawValue] = indexPath updateSelectionOrder(newSelectionOrder, for: cell, at: indexPath) updateSelectionThemeModel(newSelectionThemeModel, for: cell, at: indexPath) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { selectedCellsCount -= 1 pageHistoryHintController?.hide(true, presenter: self, subview: comparisonSelectionViewController.view, additionalBottomSpacing: comparisonSelectionViewController.view.frame.height - view.safeAreaInsets.bottom, theme: theme) if let cell = collectionView.cellForItem(at: indexPath) as? PageHistoryCollectionViewCell, let selectionOrder = cell.selectionOrder { indexPathsSelectedForComparisonGroupedByButtonTags.removeValue(forKey: selectionOrder.rawValue) openSelectionIndex = indexPathsSelectedForComparisonGroupedByButtonTags.isEmpty ? 0 : selectionOrder.rawValue forEachVisibleCell { (indexPath: IndexPath, cell: PageHistoryCollectionViewCell) in if !cell.isSelected { self.updateSelectionThemeModel(nil, for: cell, at: indexPath) cell.enableEditing(true) } } comparisonSelectionViewController.resetSelectionButton(selectionOrder) updateSelectionOrder(nil, for: cell, at: indexPath) updateSelectionThemeModel(nil, for: cell, at: indexPath) cell.apply(theme: theme) collectionView.reloadData() } comparisonSelectionViewController.setCompareButtonEnabled(maxNumberOfRevisionsSelected) } // MARK: Error handling private func showNoInternetConnectionAlertOrOtherWarning(from error: Error, noInternetConnectionAlertMessage: String = CommonStrings.noInternetConnection) { DispatchQueue.main.async { if (error as NSError).wmf_isNetworkConnectionError() { if UIAccessibility.isVoiceOverRunning { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: noInternetConnectionAlertMessage) } else { WMFAlertManager.sharedInstance.showErrorAlertWithMessage(noInternetConnectionAlertMessage, sticky: true, dismissPreviousAlerts: true) } } else { if UIAccessibility.isVoiceOverRunning { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: error.localizedDescription) } else { WMFAlertManager.sharedInstance.showErrorAlertWithMessage(error.localizedDescription, sticky: true, dismissPreviousAlerts: true) } } } } } extension PageHistoryViewController: PageHistoryComparisonSelectionViewControllerDelegate { func pageHistoryComparisonSelectionViewController(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController, selectionOrder: SelectionOrder) { guard let indexPath = indexPathsSelectedForComparisonGroupedByButtonTags[selectionOrder.rawValue] else { return } collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true) } func pageHistoryComparisonSelectionViewControllerDidTapCompare(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController) { guard let firstIndexPath = indexPathsSelectedForComparisonGroupedByButtonTags[SelectionOrder.first.rawValue], let secondIndexPath = indexPathsSelectedForComparisonGroupedByButtonTags[SelectionOrder.second.rawValue] else { return } let revision1 = pageHistorySections[firstIndexPath.section].items[firstIndexPath.item] let revision2 = pageHistorySections[secondIndexPath.section].items[secondIndexPath.item] guard let date1 = revision1.revisionDate, let date2 = revision2.revisionDate else { return } //show older revision as "from" no matter what order was selected let fromRevision: WMFPageHistoryRevision let toRevision: WMFPageHistoryRevision if date1.compare(date2) == .orderedAscending { fromRevision = revision1 toRevision = revision2 } else { fromRevision = revision2 toRevision = revision1 } showDiff(from: fromRevision, to: toRevision, type: .compare) } } extension PageHistoryViewController: DiffRevisionRetrieving { func retrievePreviousRevision(with sourceRevision: WMFPageHistoryRevision) -> WMFPageHistoryRevision? { for (sectionIndex, section) in pageHistorySections.enumerated() { for (itemIndex, item) in section.items.enumerated() { if item.revisionID == sourceRevision.revisionID { if itemIndex == (section.items.count - 1) { return pageHistorySections[safeIndex: sectionIndex + 1]?.items.first } else { return section.items[safeIndex: itemIndex + 1] } } } } return nil } func retrieveNextRevision(with sourceRevision: WMFPageHistoryRevision) -> WMFPageHistoryRevision? { var previousSection: PageHistorySection? var previousItem: WMFPageHistoryRevision? for section in pageHistorySections { for item in section.items { if item.revisionID == sourceRevision.revisionID { guard let previousItem = previousItem else { guard let previousSection = previousSection else { //user tapped latest revision, no later revision available. return nil } return previousSection.items.last } return previousItem } previousItem = item } previousSection = section previousItem = nil } return nil } }
mit
39be399023087f8b99c2931cb64eef27
46.476309
406
0.670291
5.865065
false
false
false
false
Tj3n/TVNExtensions
UIKit/UICollectionView.swift
1
2652
// // UICollectionView.swift // TVNExtensions // // Created by Tien Nhat Vu on 6/18/18. // import Foundation extension UICollectionView { /// Auto dequeue cell with custom cell class, the identifier must have the same name as the cell class /// /// - Parameter type: Custom cell class /// - Returns: Custom cell public func dequeueReusableCell<T: UICollectionViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T { guard let cell = self.dequeueReusableCell(withReuseIdentifier: String(describing: type), for: indexPath) as? T else { fatalError("\(String(describing: type)) cell could not be instantiated because it was not found on the tableView") } return cell } /// Get indexPath from cell's subview /// /// - Parameter subview: cell's subview /// - Returns: cell's indexPath public func indexPathForItemSubview(_ subview: UIView) -> IndexPath? { let point = subview.convert(subview.frame, to: self) return self.indexPathForItem(at: point.origin) } /// Use with UIScrollViewDelegate /// [Source](https://stackoverflow.com/questions/33855945/uicollectionview-snap-onto-cell-when-scrolling-horizontally) /// ```` /// func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { /// self.collectionView.scrollToNearestVisibleCollectionViewCell() /// } /// func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { /// if !decelerate { /// self.collectionView.scrollToNearestVisibleCollectionViewCell() /// } /// } /// ```` public func scrollToNearestVisibleCollectionViewCell() { self.decelerationRate = .fast let visibleCenterPositionOfScrollView = Float(self.contentOffset.x + (self.bounds.size.width / 2)) var closestCellIndex = -1 var closestDistance: Float = .greatestFiniteMagnitude for i in 0..<self.visibleCells.count { let cell = self.visibleCells[i] let cellWidth = cell.bounds.size.width let cellCenter = Float(cell.frame.origin.x + cellWidth / 2) // Now calculate closest cell let distance: Float = fabsf(visibleCenterPositionOfScrollView - cellCenter) if distance < closestDistance { closestDistance = distance closestCellIndex = self.indexPath(for: cell)!.row } } if closestCellIndex != -1 { self.scrollToItem(at: IndexPath(row: closestCellIndex, section: 0), at: .centeredHorizontally, animated: true) } } }
mit
49987e735951d012288608d7f204187a
39.8
126
0.649321
4.892989
false
false
false
false
nohirap/ANActionSheet
ANActionSheet/Classes/ANAction.swift
1
3519
// // ANActionSheetAction.swift // Pods // // Created by nohirap on 2016/06/05. // Copyright © 2016 nohirap. All rights reserved. // import UIKit public enum ANActionStyle { case Default case Cancel var isDefault: Bool { if self == .Default { return true } return false } } protocol ANActionSheetOutPut { func dismiss() } final public class ANAction: UIButton { var output: ANActionSheetOutPut? var style: ANActionStyle = .Default { didSet { if style == .Cancel { self.layer.cornerRadius = 6.0 self.layer.masksToBounds = true } } } public var buttonColor = UIColor.whiteColor() { didSet { self.backgroundColor = buttonColor } } public var labelColor = UIColor.blackColor() { didSet { self.setTitleColor(labelColor, forState: .Normal) } } public var labelNumberOfLines = 0 { didSet { self.titleLabel?.numberOfLines = labelNumberOfLines } } private var handler: (() -> Void)? private let fontSize: CGFloat = 18 required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(title: String, style: ANActionStyle = .Default, handler: (() -> Void)? = nil) { super.init(frame: CGRectZero) setupAction(title, style: style, handler: handler) } private func setupAction(title: String, style: ANActionStyle, handler: (() -> Void)?) { self.setTitle(title, forState: .Normal) self.setTitleColor(labelColor, forState: .Normal) self.titleLabel?.font = UIFont.systemFontOfSize(fontSize) self.backgroundColor = buttonColor self.titleLabel?.lineBreakMode = .ByWordWrapping self.titleLabel?.sizeToFit() self.style = style self.handler = handler self.addTarget(self, action:#selector(ANAction.tappedButton(_:)), forControlEvents: .TouchUpInside) } private func lineNumber(label: UILabel, text: String) -> Int { let oneLineRect = "a".boundingRectWithSize(label.bounds.size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil) let boundingRect = text.boundingRectWithSize(label.bounds.size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil) return Int(boundingRect.height / oneLineRect.height) } private func calcButtonHeight(numberOflines: Int) -> CGFloat { if numberOflines == 1 { return UIScreen.buttonHeight() } else { return (UIScreen.buttonHeight() / 2) * CGFloat(numberOflines) } } func setupFrame(y: CGFloat) -> CGFloat { guard let titleLabel = self.titleLabel, text = titleLabel.text else { return y } let buttonHeight: CGFloat if labelNumberOfLines == 0 { buttonHeight = calcButtonHeight(lineNumber(titleLabel, text: text)) } else { buttonHeight = calcButtonHeight(labelNumberOfLines) } self.frame = CGRectMake(0, y, UIScreen.buttonWidth(), buttonHeight) return buttonHeight } func tappedButton(button: UIButton) { if let handler = handler { handler() } output?.dismiss() } }
mit
b9bf717694d3834c7421a73dfd4be9e2
28.813559
166
0.606026
4.786395
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Cartography/CartographyTests/EdgesSpec.swift
15
2746
import Cartography import Nimble import Quick class EdgesSpec: QuickSpec { override func spec() { var window: TestWindow! var view: TestView! beforeEach { window = TestWindow(frame: CGRectMake(0, 0, 400, 400)) view = TestView(frame: CGRectZero) window.addSubview(view) } describe("LayoutProxy.edges") { it("should support relative equalities") { constrain(view) { view in view.edges == view.superview!.edges } window.layoutIfNeeded() expect(view.frame).to(equal(view.superview?.frame)) } } describe("LayoutProxy.edges") { it("should support relative inequalities") { constrain(view) { view in view.edges <= view.superview!.edges view.edges >= view.superview!.edges } window.layoutIfNeeded() expect(view.frame).to(equal(view.superview?.frame)) } } describe("inset") { it("should inset all edges with the same amount") { constrain(view) { view in view.edges == inset(view.superview!.edges, 20) } window.layoutIfNeeded() expect(view.frame).to(equal(CGRectMake(20, 20, 360, 360))) } it("should inset the horizontal and vertical edge individually") { constrain(view) { view in view.edges == inset(view.superview!.edges, 20, 30) } window.layoutIfNeeded() expect(view.frame).to(equal(CGRectMake(20, 30, 360, 340))) } it("should inset all edges individually") { constrain(view) { view in view.edges == inset(view.superview!.edges, 10, 20, 30, 40) } window.layoutIfNeeded() expect(view.frame).to(equal(CGRectMake(20, 10, 340, 360))) } } #if os(iOS) describe("on iOS only") { beforeEach { window.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40) } describe("LayoutProxy.edgesWithinMargins") { it("should support relative equalities") { constrain(view) { view in view.edges == view.superview!.edgesWithinMargins } window.layoutIfNeeded() expect(view.frame).to(equal(CGRectMake(20, 10, 340, 360))) } } } #endif } }
mit
796c0b9c14cf1f381ed372fee40da8c1
27.905263
93
0.488347
5.02011
false
false
false
false
ypopovych/ExpressCommandLine
Sources/swift-express/Commands/Init/Steps/CloneGitRepository.swift
1
2885
//===--- CloneGitRepository.swift -------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express Command Line is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===------------------------------------------------------------------===// import Foundation // Clones repository to folder. // Input: // repositoryURL : String // outputFolder : String // Output: // clonedFolder: String struct CloneGitRepository : RunSubtaskStep { let dependsOn = [Step]() let folderExistsMessage = "CloneGitRepository: Output Folder already exists" func run(_ params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] { guard let repositoryURL = params["repositoryURL"] as? String else { throw SwiftExpressError.badOptions(message: "CloneGitRepository: No repositoryURL option.") } guard let outputFolder = params["outputFolder"] as? URL else { throw SwiftExpressError.badOptions(message: "CloneGitRepository: No outputFolder option.") } let result = try executeSubtaskAndWait(Process(task: "/usr/bin/env", arguments: ["git", "clone", repositoryURL, outputFolder.path], useAppOutput: true)) if result != 0 { throw SwiftExpressError.subtaskError(message: "git clone failed") } return ["clonedFolder": outputFolder] } func cleanup(_ params:[String: Any], output: StepResponse) throws { } func revert(params:[String: Any], output: [String: Any]?, error: SwiftExpressError?) { switch error { case .badOptions(let message)?: if message == folderExistsMessage { return } fallthrough default: if let outputFolder = params["outputFolder"] as? URL { if FileManager.default.directoryExists(at: outputFolder) { do { try FileManager.default.removeItem(at: outputFolder) } catch { print("CloneGitRepository: Can't remove output folder on revert. \(error)") } } } } } }
gpl-3.0
341d40a62aa01419e8fa0ad618436d78
39.069444
160
0.613865
5.034904
false
false
false
false
LiulietLee/Pick-Color
Pick Color/MenuTableViewController.swift
1
1889
// // MenuTableViewController.swift // Pick Color // // Created by Liuliet.Lee on 26/8/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit class MenuTableViewController: UITableViewController { fileprivate var menuList: [(title: String, id: String)] = [ ("Pick Color", "picker"), ("Favorite", "favorites"), ("Author", "author"), ("Rate PickColor", "rate"), ("Source Code", "code") ] override func viewDidLoad() { super.viewDidLoad() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: menuList[indexPath.row].id, for: indexPath) as! MenuCell cell.title?.text = menuList[indexPath.row].title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if #available(iOS 10.3, *) { return } if indexPath.row == 3 { guard let url = URL(string : "itms-apps://itunes.apple.com/app/id1205136568") else { print("wtf?!") return } guard #available(iOS 10, *) else { UIApplication.shared.openURL(url) return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } } override func viewWillAppear(_ animated: Bool) { if #available(iOS 10.3, *), menuList[3].id == "rate" { menuList.remove(at: 3) } } }
mit
6f7ac18f251df4849de0def256f75cf0
28.046154
121
0.574682
4.661728
false
false
false
false
haawa799/WaniKit2
Sources/WaniKit/Apple NSOperation/Conditions/ReachabilityCondition.swift
3
3250
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ import Foundation import SystemConfiguration /** This is a condition that performs a very high-level reachability check. It does *not* perform a long-running reachability check, nor does it respond to changes in reachability. Reachability is evaluated once when the operation to which this is attached is asked about its readiness. */ public struct ReachabilityCondition: OperationCondition { public static let hostKey = "Host" public static let name = "Reachability" public static let isMutuallyExclusive = false let host: NSURL init(host: NSURL) { self.host = host } public func dependencyForOperation(operation: Operation) -> NSOperation? { return nil } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { ReachabilityController.requestReachability(host) { reachable in if reachable { completion(.Satisfied) } else { let error = NSError(code: .ConditionFailed, userInfo: [ OperationConditionKey: self.dynamicType.name, self.dynamicType.hostKey: self.host ]) completion(.Failed(error)) } } } } /// A private singleton that maintains a basic cache of `SCNetworkReachability` objects. private class ReachabilityController { static var reachabilityRefs = [String: SCNetworkReachability]() static let reachabilityQueue = dispatch_queue_create("Operations.Reachability", DISPATCH_QUEUE_SERIAL) static func requestReachability(url: NSURL, completionHandler: (Bool) -> Void) { if let host = url.host { dispatch_async(reachabilityQueue) { var ref = self.reachabilityRefs[host] if ref == nil { let hostString = host as NSString ref = SCNetworkReachabilityCreateWithName(nil, hostString.UTF8String) } if let ref = ref { self.reachabilityRefs[host] = ref var reachable = false var flags: SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(ref, &flags) { /* Note that this is a very basic "is reachable" check. Your app may choose to allow for other considerations, such as whether or not the connection would require VPN, a cellular connection, etc. */ reachable = flags.contains(.Reachable) } completionHandler(reachable) } else { completionHandler(false) } } } else { completionHandler(false) } } }
mit
78c6eda96654ddbaa3185c0dc9badd4e
34.304348
109
0.572968
5.927007
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ChartAnnotations/AnnotationsChartView.swift
1
11323
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // AnnotationsChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class AnnotationsChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) let yAxis = SCINumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) // Watermark let watermark = SCITextAnnotation() watermark.coordinateMode = .relative watermark.x1 = SCIGeneric(0.5) watermark.y1 = SCIGeneric(0.5) watermark.text = "Create \n Watermarks" watermark.horizontalAnchorPoint = .center watermark.verticalAnchorPoint = .center watermark.style.textColor = UIColor.fromARGBColorCode(0x22FFFFFF) watermark.style.textStyle.fontSize = 42 watermark.style.backgroundColor = UIColor.clear // Text annotations let textAnnotation1 = SCITextAnnotation() textAnnotation1.x1 = SCIGeneric(0.3) textAnnotation1.y1 = SCIGeneric(9.7) textAnnotation1.text = "Annotations are Easy!" textAnnotation1.style.textColor = UIColor.white textAnnotation1.style.textStyle.fontSize = 24 textAnnotation1.style.backgroundColor = UIColor.clear let textAnnotation2 = SCITextAnnotation() textAnnotation2.x1 = SCIGeneric(1.0) textAnnotation2.y1 = SCIGeneric(9.0) textAnnotation2.text = "You can create text" textAnnotation2.style.textColor = UIColor.white textAnnotation2.style.textStyle.fontSize = 10 textAnnotation2.style.backgroundColor = UIColor.clear // Text with Anchor Points let textAnnotation3 = SCITextAnnotation() textAnnotation3.x1 = SCIGeneric(5.0) textAnnotation3.y1 = SCIGeneric(8.0) textAnnotation3.text = "Anchor Center (x1, y1)" textAnnotation3.horizontalAnchorPoint = .center textAnnotation3.verticalAnchorPoint = .bottom textAnnotation3.style.textColor = UIColor.white textAnnotation3.style.textStyle.fontSize = 12 let textAnnotation4 = SCITextAnnotation() textAnnotation4.x1 = SCIGeneric(5.0) textAnnotation4.y1 = SCIGeneric(8.0) textAnnotation4.text = "Anchor Right" textAnnotation4.horizontalAnchorPoint = .right textAnnotation4.verticalAnchorPoint = .top textAnnotation4.style.textColor = UIColor.white textAnnotation4.style.textStyle.fontSize = 12 let textAnnotation5 = SCITextAnnotation() textAnnotation5.x1 = SCIGeneric(5.0) textAnnotation5.y1 = SCIGeneric(8.0) textAnnotation5.text = "or Anchor Left"; textAnnotation5.horizontalAnchorPoint = .left textAnnotation5.verticalAnchorPoint = .top textAnnotation5.style.textColor = UIColor.white textAnnotation5.style.textStyle.fontSize = 12 // Line and line arrow annotations let textAnnotation6 = SCITextAnnotation() textAnnotation6.x1 = SCIGeneric(0.3) textAnnotation6.y1 = SCIGeneric(6.1) textAnnotation6.text = "Draw Lines with \nor without Arrows" textAnnotation6.verticalAnchorPoint = .bottom textAnnotation6.style.textColor = UIColor.white textAnnotation6.style.textStyle.fontSize = 12 let lineAnnotation = SCILineAnnotation() lineAnnotation.x1 = SCIGeneric(1.0) lineAnnotation.y1 = SCIGeneric(4.0) lineAnnotation.x2 = SCIGeneric(2.0) lineAnnotation.y2 = SCIGeneric(6.0) lineAnnotation.style.linePen = SCISolidPenStyle(colorCode: 0xFF555555, withThickness: 2) // Should be line annotation with arrow here // Box annotations let textAnnotation7 = SCITextAnnotation() textAnnotation7.x1 = SCIGeneric(3.5) textAnnotation7.y1 = SCIGeneric(6.1) textAnnotation7.text = "Draw Boxes" textAnnotation7.verticalAnchorPoint = .bottom textAnnotation7.style.textColor = UIColor.white textAnnotation7.style.textStyle.fontSize = 12 let boxAnnotation1 = SCIBoxAnnotation() boxAnnotation1.x1 = SCIGeneric(3.5) boxAnnotation1.y1 = SCIGeneric(4.0) boxAnnotation1.x2 = SCIGeneric(5.0) boxAnnotation1.y2 = SCIGeneric(5.0) boxAnnotation1.style.fillBrush = SCILinearGradientBrushStyle(colorCodeStart: 0x550000FF, finish: 0x55FFFF00, direction: .vertical) boxAnnotation1.style.borderPen = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 1.0) let boxAnnotation2 = SCIBoxAnnotation() boxAnnotation2.x1 = SCIGeneric(4.0) boxAnnotation2.y1 = SCIGeneric(4.5) boxAnnotation2.x2 = SCIGeneric(5.5) boxAnnotation2.y2 = SCIGeneric(5.5) boxAnnotation2.style.fillBrush = SCISolidBrushStyle(colorCode: 0x55FF1919) boxAnnotation2.style.borderPen = SCISolidPenStyle(colorCode: 0xFFFF1919, withThickness: 1.0) let boxAnnotation3 = SCIBoxAnnotation() boxAnnotation3.x1 = SCIGeneric(4.5) boxAnnotation3.y1 = SCIGeneric(5.0) boxAnnotation3.x2 = SCIGeneric(6.0) boxAnnotation3.y2 = SCIGeneric(6.0) boxAnnotation3.style.fillBrush = SCISolidBrushStyle(colorCode: 0x55279B27) boxAnnotation3.style.borderPen = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 1.0) // Custom shapes let textAnnotation8 = SCITextAnnotation() textAnnotation8.x1 = SCIGeneric(7.0) textAnnotation8.y1 = SCIGeneric(6.1) textAnnotation8.text = "Or Custom Shapes" textAnnotation8.verticalAnchorPoint = .bottom textAnnotation8.style.textColor = UIColor.white textAnnotation8.style.textStyle.fontSize = 12 let customAnnotationGreen = SCICustomAnnotation() customAnnotationGreen.customView = UIImageView(image: UIImage(named: "GreenArrow")) customAnnotationGreen.x1 = SCIGeneric(8) customAnnotationGreen.y1 = SCIGeneric(5.5) let customAnnotationRed = SCICustomAnnotation() customAnnotationRed.customView = UIImageView(image: UIImage(named: "RedArrow")) customAnnotationRed.x1 = SCIGeneric(7.5) customAnnotationRed.y1 = SCIGeneric(5) // Horizontal Line Annotations let horizontalLine = SCIHorizontalLineAnnotation() horizontalLine.x1 = SCIGeneric(5.0) horizontalLine.y1 = SCIGeneric(3.2) horizontalLine.horizontalAlignment = .right horizontalLine.style.linePen = SCISolidPenStyle(color: UIColor.orange, withThickness: 2) horizontalLine.add(self.createLabelWith(text: "Right Aligned, with text on left", labelPlacement: .topLeft, color: UIColor.orange, backColor: UIColor.clear)) let horizontalLine1 = SCIHorizontalLineAnnotation() horizontalLine1.y1 = SCIGeneric(7.5) horizontalLine1.y1 = SCIGeneric(2.8) horizontalLine1.style.linePen = SCISolidPenStyle(color: UIColor.orange, withThickness: 2) horizontalLine1.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.orange)) // Vertical Line annotations let verticalLine = SCIVerticalLineAnnotation() verticalLine.x1 = SCIGeneric(9.0) verticalLine.y1 = SCIGeneric(4.0) verticalLine.verticalAlignment = .bottom; verticalLine.style.linePen = SCISolidPenStyle(colorCode: 0xFFA52A2A, withThickness: 2) verticalLine.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.fromARGBColorCode(0xFFA52A2A))) let verticalLine1 = SCIVerticalLineAnnotation() verticalLine1.x1 = SCIGeneric(9.5) verticalLine1.y1 = SCIGeneric(10.0) verticalLine1.style.linePen = SCISolidPenStyle(colorCode: 0xFFA52A2A, withThickness: 2) verticalLine.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.fromARGBColorCode(0xFFA52A2A))) verticalLine.add(self.createLabelWith(text: "Bottom-aligned", labelPlacement: .topRight, color: UIColor.fromARGBColorCode(0xFFA52A2A), backColor: UIColor.clear)) self.surface.annotations = SCIAnnotationCollection(childAnnotations: [watermark, textAnnotation1, textAnnotation2, textAnnotation3, textAnnotation4, textAnnotation5, textAnnotation6, lineAnnotation, textAnnotation7, boxAnnotation1, boxAnnotation2, boxAnnotation3, textAnnotation8, customAnnotationGreen, customAnnotationRed, horizontalLine, horizontalLine1, verticalLine, verticalLine1]) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCIZoomPanModifier()]) } } fileprivate func createLabelWith(text: String, labelPlacement: SCILabelPlacement, color: UIColor, backColor: UIColor) -> SCILineAnnotationLabel { let lineAnnotationLabel = SCILineAnnotationLabel() lineAnnotationLabel.text = text lineAnnotationLabel.style.backgroundColor = backColor lineAnnotationLabel.style.labelPlacement = labelPlacement lineAnnotationLabel.style.textStyle.color = color return lineAnnotationLabel } }
mit
391a7f6bec24cc23a81201b9e492408e
53.951456
173
0.623233
4.782425
false
false
false
false
silence0201/Swift-Study
Learn/19.Foundation/NSSet/NSSet类.playground/section-1.swift
1
378
import Foundation var weeksArray: NSSet = ["星期一","星期二", "星期三", "星期四"] weeksArray = weeksArray.adding("星期五") as NSSet weeksArray = weeksArray.addingObjects(from: ["星期六","星期日"]) as NSSet var weeksNames = NSSet(set: weeksArray) for day in weeksArray { print(day) } print("============") for day in weeksNames { print(day) }
mit
5071fa181cdb8baf1f1379cd5f0a58d3
16.684211
67
0.654762
2.973451
false
false
false
false
oneCup/MyWeiBo
MyWeiBoo/MyWeiBoo/Class/Module/Home/YFRefreshControl.swift
1
3932
// // YFRefreshControl.swift // MyWeiBoo // // Created by 李永方 on 15/10/17. // Copyright © 2015年 李永方. All rights reserved. // import UIKit /// frame的Y的临界值 let krefreshPullOffset: CGFloat = -60 class YFRefreshControl: UIRefreshControl { override init() { super.init() setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 重写结束刷新的方法在结束刷新的时候,结束动画 override func endRefreshing() { super.endRefreshing() refreshView.endAnimate() } /// 加入了KVO必须将KVO进行移除 deinit { //KVO监听frame 的属性变化 self.removeObserver(self, forKeyPath: "frame") } //打印方法 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { print(frame) if refreshing { //开始刷新 refreshView.startLoading() } if frame.origin.y < krefreshPullOffset && !refreshView.Refreshflag { //设置属性的标记 refreshView.Refreshflag = true }else if frame.origin.y > krefreshPullOffset && refreshView.Refreshflag{ refreshView.Refreshflag = false } } private func setUpUI() { //监听属性值的变化kvo frame的变化 self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) tintColor = UIColor.clearColor() //加载控件 addSubview(refreshView) //设置布局 refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size) } //懒加载控件 private lazy var refreshView : YFRereshView = YFRereshView.LoadrefreshView() } /// 下拉刷新视图 - 负责显示动画 class YFRereshView: UIView { //连线属性 @IBOutlet weak var TipIcon: UIImageView! @IBOutlet weak var RefreshIcon: UILabel! @IBOutlet weak var LoadingIcon: UIImageView! @IBOutlet weak var TipView: UIView! //定义旋转标记 var Refreshflag = false { didSet { //每次监听到属性值变化,就会旋转 rotateTip() } } //加载XIB class func LoadrefreshView() ->YFRereshView { return NSBundle.mainBundle().loadNibNamed("YFrefresh", owner: nil, options: nil).last as! YFRereshView } /// 旋转图片 private func rotateTip() { let angle = Refreshflag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01) UIView.animateWithDuration(0.25) { () -> Void in //判断旋转标记 self.TipIcon.transform = CGAffineTransformRotate(self.TipIcon.transform, angle) } } /// 开始动画加载 private func startLoading() { //判断动画是否已经被添加 // animationForKey 可以获得添加到图层上的动画 if LoadingIcon.layer.animationForKey("transform.rotation") != nil { return } //1.隐藏提示框 TipView.hidden = true //2.定义动画(旋转动画) let animi = CABasicAnimation(keyPath: "transform.rotation") animi.toValue = 2 * M_PI animi.repeatCount = MAXFLOAT animi.duration = 1.0 //3.添加动画 LoadingIcon.layer.addAnimation(animi, forKey: "loadAnimate") } /// 停止动画 private func endAnimate() { //将动画移除 TipView.hidden = false LoadingIcon.layer.removeAllAnimations() } }
mit
b1883749a00372920f9f361d4e8928b9
24.510791
157
0.57433
4.302184
false
false
false
false
tndatacommons/Compass-iOS
Compass/src/Controller/GoalViewController.swift
1
9108
// // GoalViewController.swift // Compass // // Created by Ismael Alonso on 5/23/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit import Nuke import Just import ObjectMapper import Instructions class GoalViewController: UIViewController, UIScrollViewDelegate, CoachMarksControllerDataSource, CoachMarksControllerDelegate{ //Delegate var delegate: GoalAddedDelegate!; //Data var category: CategoryContent!; var goal: GoalContent!; var userGoal: UserGoal? = nil; var fromFeed = false; // Are we launching this from the feed? var imageViewProcessed = false; //UI components @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var header: UIView! @IBOutlet weak var headerImage: UIImageView! @IBOutlet weak var goalTitle: UILabel! @IBOutlet weak var goalDescription: UILabel! @IBOutlet weak var signMeUpButton: UIButton! @IBOutlet weak var contentContainer: UIView! @IBOutlet var rewardHeader: UILabel! @IBOutlet var reward: UILabel! @IBOutlet var author: UILabel! @IBOutlet weak var buttonContainer: UIView! @IBOutlet weak var removeButton: UIButton! private var rewardHeaderConstraints: [NSLayoutConstraint] = [NSLayoutConstraint](); private var rewardConstraints: [NSLayoutConstraint] = [NSLayoutConstraint](); private var authorConstraints: [NSLayoutConstraint] = [NSLayoutConstraint](); private let coachMarksController = CoachMarksController(); override func viewDidLoad(){ if (TourManager.getGoalMarkerCount() != 0){ UIApplication.sharedApplication().beginIgnoringInteractionEvents(); } //Background color of the header header.layer.backgroundColor = category.getParsedColor().CGColor; //Header image if (category.getIconUrl().characters.count != 0){ Nuke.taskWith(NSURL(string: category.getIconUrl())!){ //For some reason, in the second run, the frame object reports a wrong height, // to fix that, header image is forced to layout to calculate the actual // height respecting its constraints, and only then we set the corner radius self.headerImage.setNeedsLayout(); self.headerImage.layoutIfNeeded(); self.headerImage.layer.cornerRadius = self.headerImage.frame.height/2; self.headerImage.clipsToBounds = true; self.headerImage.image = $0.image; }.resume(); } //Goal information goalTitle.text = goal.getTitle(); goalDescription.text = goal.getDescription(); // If we're showing this goal from the feed, the user has already // selected the goal, so we don't need to display these buttons if (fromFeed){ buttonContainer.hidden = true; removeButton.hidden = false; } //Reward content //Extract the relevant constraints before they get removed for constraint in contentContainer.constraints{ //Author constraints need to go all in the author array, because author may not be // added back to the container if (constraint.firstItem === author || constraint.secondItem === author){ authorConstraints.append(constraint); continue; } if (constraint.firstItem === rewardHeader || constraint.secondItem === rewardHeader){ rewardHeaderConstraints.append(constraint); continue; } if (constraint.firstItem === reward || constraint.secondItem === reward){ rewardConstraints.append(constraint); } } //Remove the reward related views and fetch the reward rewardHeader.removeFromSuperview(); reward.removeFromSuperview(); author.removeFromSuperview(); Just.get(API.getRandomRewardUrl()){ (response) in if (response.ok){ print("Reward retrieved"); let result = String(data: response.content!, encoding:NSUTF8StringEncoding); let rewardContent = (Mapper<ParserModels.RewardArray>().map(result)?.rewards![0])!; dispatch_async(dispatch_get_main_queue(), { self.contentContainer.addSubview(self.rewardHeader); self.contentContainer.addSubview(self.reward); self.contentContainer.addConstraints(self.rewardHeaderConstraints); self.contentContainer.addConstraints(self.rewardConstraints); self.rewardHeader.text = rewardContent.getHeaderTitle(); self.reward.text = rewardContent.getMessage(); if (rewardContent.isQuote()){ self.contentContainer.addSubview(self.author); self.contentContainer.addConstraints(self.authorConstraints); self.author.text = rewardContent.getAuthor(); } self.contentContainer.setNeedsLayout(); self.contentContainer.layoutIfNeeded(); self.scrollView.contentSize = self.contentContainer.frame.size; }); } } //Tour coachMarksController.dataSource = self; coachMarksController.delegate = self; coachMarksController.overlay.color = UIColor.clearColor(); } override func viewDidAppear(animated: Bool){ super.viewDidAppear(animated); let container = CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, scrollView.frame.size.width, scrollView.frame.size.height); if (CGRectIntersectsRect(signMeUpButton.frame, container)){ self.coachMarksController.startOn(self); } else{ scrollView.scrollRectToVisible(signMeUpButton.frame, animated: true); } } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView){ self.coachMarksController.startOn(self); } func scrollViewDidEndDragging(scrollView: UIScrollView, decelerate: Bool){ self.scrollView.contentSize = self.contentContainer.frame.size; } @IBAction func notNow(){ navigationController!.popViewControllerAnimated(true); } @IBAction func yesImIn(){ delegate.goalAdded(); navigationController!.popViewControllerAnimated(true); } @IBAction func remove(){ if (userGoal != nil){ Just.delete(API.URL.deleteGoal(userGoal!), headers: SharedData.user.getHeaderMap()){ (response) in }; SharedData.feedData.removeGoal(userGoal!); navigationController!.popViewControllerAnimated(true); } } func numberOfCoachMarksForCoachMarksController(coachMarkController: CoachMarksController) -> Int{ if (fromFeed){ return 0; } return TourManager.getGoalMarkerCount(); } func coachMarksController(coachMarksController: CoachMarksController, coachMarkForIndex coachMarksForIndex: Int) -> CoachMark{ switch (TourManager.getFirstUnseenGoalMarker()){ case .Add: var mark = coachMarksController.helper.coachMarkForView(signMeUpButton); mark.maxWidth = UIScreen.mainScreen().bounds.width*0.8; coachMarksController.overlay.color = UIColor.init(hexString: "#2196F3").colorWithAlphaComponent(0.5); return mark; default: break; } return coachMarksController.helper.coachMarkForView(); } func coachMarksController(coachMarksController: CoachMarksController, coachMarkViewsForIndex: Int, coachMark: CoachMark) -> (bodyView: CoachMarkBodyView, arrowView: CoachMarkArrowView?){ let coachViews = coachMarksController.helper.defaultCoachViewsWithArrow(true, arrowOrientation: coachMark.arrowOrientation); switch (TourManager.getFirstUnseenGoalMarker()){ case .Add: coachViews.bodyView.hintLabel.text = "Tap \"SIGN ME UP\" to begin receiving Compass tips."; coachViews.bodyView.nextLabel.text = "OK"; default: break; } let triggerTime = (Int64(NSEC_PER_SEC) * 1); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in UIApplication.sharedApplication().endIgnoringInteractionEvents(); }); return (bodyView: coachViews.bodyView, arrowView: coachViews.arrowView); } func coachMarksController(coachMarksController: CoachMarksController, coachMarkWillDisappear: CoachMark, forIndex: Int){ TourManager.markFirstUnseenGoalMarker(); } } protocol GoalAddedDelegate{ func goalAdded(); }
mit
734b38ec39d3cfd9fcdbb5cad7a62efb
39.118943
190
0.635775
5.509377
false
false
false
false
manavgabhawala/swift
test/SILGen/generic_property_base_lifetime.swift
1
6623
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s protocol ProtocolA: class { var intProp: Int { get set } } protocol ProtocolB { var intProp: Int { get } } @objc protocol ProtocolO: class { var intProp: Int { get set } } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int { // CHECK: bb0([[ARG:%.*]] : $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!getter.1 : {{.*}}, [[PROJECTION]] // CHECK: [[RESULT:%.*]] = apply [[WITNESS_METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF' func getIntPropExistential(_ a: ProtocolA) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () { // CHECK: bb0([[ARG:%.*]] : $ProtocolA): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $@opened({{.*}}) ProtocolA, #ProtocolA.intProp!setter.1 : {{.*}}, [[PROJECTION]] // CHECK: apply [[WITNESS_METHOD]]<@opened{{.*}}>({{%.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF' func setIntPropExistential(_ a: ProtocolA) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolA>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolA>(_ a: T) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolB_pF // CHECK: [[PROJECTION:%.*]] = open_existential_addr immutable_access %0 // CHECK: [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB // CHECK: copy_addr [[PROJECTION]] to [initialization] [[STACK]] // CHECK: apply {{%.*}}([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropExistential(_ a: ProtocolB) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: apply {{%.*}}<T>([[STACK]]) // CHECK: destroy_addr [[STACK]] // CHECK: dealloc_stack [[STACK]] // CHECK: destroy_addr %0 func getIntPropGeneric<T: ProtocolB>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int { // CHECK: bb0([[ARG:%.*]] : $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!getter.1.foreign : {{.*}}, [[PROJECTION]] // CHECK: apply [[METHOD]]<@opened{{.*}}>([[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF' func getIntPropExistential(_ a: ProtocolO) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () { // CHECK: bb0([[ARG:%.*]] : $ProtocolO): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]] // CHECK: [[PROJECTION_COPY:%.*]] = copy_value [[PROJECTION]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $@opened({{.*}}) ProtocolO, #ProtocolO.intProp!setter.1.foreign : {{.*}}, [[PROJECTION]] // CHECK: apply [[METHOD]]<@opened{{.*}}>({{.*}}, [[PROJECTION_COPY]]) // CHECK: destroy_value [[PROJECTION_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF' func setIntPropExistential(_ a: ProtocolO) { a.intProp = 0 } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17getIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func getIntPropGeneric<T: ProtocolO>(_ a: T) -> Int { return a.intProp } // CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime17setIntPropGeneric{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: apply {{%.*}}<T>({{%.*}}, [[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] func setIntPropGeneric<T: ProtocolO>(_ a: T) { a.intProp = 0 }
apache-2.0
6d73170ecf8d37c38a1cf8ac75c31931
46.992754
152
0.630379
3.329814
false
false
false
false
cuappdev/tempo
Tempo/Utilities/UIViewController+Utilities.swift
1
1619
// // UIViewController+Utilities.swift // Tempo // // Created by Alexander Zielenski on 5/5/15. // Copyright (c) 2015 Alexander Zielenski. All rights reserved. // import Foundation import SWRevealViewController extension UIViewController { func addHamburgerMenu() { let hamburgerIconView = HamburgerIconView(frame: CGRectMake(0, 0, 30, 30), color: UIColor.whiteColor().colorWithAlphaComponent(0.85), lineWidth: 2, iconWidthRatio: 0.50) hamburgerIconView.addTarget(self, action: #selector(UIViewController.toggleHamburger(_:)), forControlEvents: .TouchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: hamburgerIconView) } func toggleHamburger(hamburgerIconView: HamburgerIconView) { revealViewController().revealToggle(hamburgerIconView) } func addRevealGesture() { if revealViewController() != nil { view.addGestureRecognizer(revealViewController().panGestureRecognizer()) } } func removeRevealGesture() { if revealViewController() != nil { view.removeGestureRecognizer(revealViewController().panGestureRecognizer()) } } func notConnected() { if !API.sharedAPI.isConnected { Banner.notConnected(self) } else if !API.sharedAPI.isAPIConnected { Banner.APINotConnected(self) } } func dismissVCWithFadeAnimation() { let transition = CATransition() transition.duration = 0.3 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionFade view.window!.layer.addAnimation(transition, forKey: nil) dismissViewControllerAnimated(false, completion: nil) } }
mit
ec98b83e2626f908827a21cf0ff3b815
29
171
0.768993
4.317333
false
false
false
false
kaojohnny/CoreStore
Sources/ObjectiveC/CSListMonitor.swift
1
21993
// // CSListMonitor.swift // CoreStore // // Copyright © 2016 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData #if os(iOS) || os(watchOS) || os(tvOS) // MARK: - CSListMonitor /** The `CSListMonitor` serves as the Objective-C bridging type for `ListMonitor<T>`. - SeeAlso: `ListMonitor` */ @objc public final class CSListMonitor: NSObject, CoreStoreObjectiveCType { // MARK: Public (Accessors) /** Returns the object at the given index within the first section. This subscript indexer is typically used for `CSListMonitor`s created without section groupings. - parameter index: the index of the object. Using an index above the valid range will raise an exception. - returns: the `NSManagedObject` at the specified index */ @objc public subscript(index: Int) -> AnyObject { return self.bridgeToSwift[index] } /** Returns the object at the given index, or `nil` if out of bounds. This indexer is typically used for `CSListMonitor`s created without section groupings. - parameter index: the index for the object. Using an index above the valid range will return `nil`. - returns: the `NSManagedObject` at the specified index, or `nil` if out of bounds */ @objc public func objectAtSafeIndex(index: Int) -> AnyObject? { return self.bridgeToSwift[safeIndex: index] } /** Returns the object at the given `sectionIndex` and `itemIndex`. This indexer is typically used for `CSListMonitor`s created as sectioned lists. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will raise an exception. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will raise an exception. - returns: the `NSManagedObject` at the specified section and item index */ @objc public func objectAtSectionIndex(sectionIndex: Int, itemIndex: Int) -> AnyObject { return self.bridgeToSwift[sectionIndex, itemIndex] } /** Returns the object at the given section and item index, or `nil` if out of bounds. This indexer is typically used for `CSListMonitor`s created as sectioned lists. - parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`. - parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`. - returns: the `NSManagedObject` at the specified section and item index, or `nil` if out of bounds */ @objc public func objectAtSafeSectionIndex(sectionIndex: Int, safeItemIndex itemIndex: Int) -> AnyObject? { return self.bridgeToSwift[safeSectionIndex: sectionIndex, safeItemIndex: itemIndex] } /** Returns the object at the given `NSIndexPath`. This subscript indexer is typically used for `CSListMonitor`s created as sectioned lists. - parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will raise an exception. - returns: the `NSManagedObject` at the specified index path */ @objc public func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject { return self.bridgeToSwift[indexPath] } /** Returns the object at the given `NSIndexPath`, or `nil` if out of bounds. This subscript indexer is typically used for `CSListMonitor`s created as sectioned lists. - parameter indexPath: the `NSIndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`. - returns: the `NSManagedObject` at the specified index path, or `nil` if out of bounds */ @objc public func objectAtSafeIndexPath(indexPath: NSIndexPath) -> AnyObject? { return self.bridgeToSwift[safeIndexPath: indexPath] } /** Checks if the `CSListMonitor` has at least one object in any section. - returns: `YES` if at least one object in any section exists, `NO` otherwise */ @objc @warn_unused_result public func hasObjects() -> Bool { return self.bridgeToSwift.hasObjects() } /** Checks if the `CSListMonitor` has at least one object the specified section. - parameter section: the section index. Using an index outside the valid range will return `NO`. - returns: `YES` if at least one object in the specified section exists, `NO` otherwise */ @objc @warn_unused_result public func hasObjectsInSection(section: Int) -> Bool { return self.bridgeToSwift.hasObjectsInSection(section) } /** Returns all objects in all sections - returns: all objects in all sections */ @objc @warn_unused_result public func objectsInAllSections() -> [NSManagedObject] { return self.bridgeToSwift.objectsInAllSections() } /** Returns all objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: all objects in the specified section */ @objc @warn_unused_result public func objectsInSection(section: Int) -> [NSManagedObject] { return self.bridgeToSwift.objectsInSection(section) } /** Returns all objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: all objects in the specified section, or `nil` if out of bounds */ @objc @warn_unused_result public func objectsInSafeSection(safeSectionIndex section: Int) -> [NSManagedObject]? { return self.bridgeToSwift.objectsInSection(safeSectionIndex: section) } /** Returns the number of sections - returns: the number of sections */ @objc @warn_unused_result public func numberOfSections() -> Int { return self.bridgeToSwift.numberOfSections() } /** Returns the number of objects in all sections - returns: the number of objects in all sections */ @objc @warn_unused_result public func numberOfObjects() -> Int { return self.bridgeToSwift.numberOfObjects() } /** Returns the number of objects in the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the number of objects in the specified section */ @objc @warn_unused_result public func numberOfObjectsInSection(section: Int) -> Int { return self.bridgeToSwift.numberOfObjectsInSection(section) } /** Returns the number of objects in the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the number of objects in the specified section, or `nil` if out of bounds */ @objc @warn_unused_result public func numberOfObjectsInSafeSection(safeSectionIndex section: Int) -> NSNumber? { return self.bridgeToSwift.numberOfObjectsInSection(safeSectionIndex: section) } /** Returns the `NSFetchedResultsSectionInfo` for the specified section - parameter section: the section index. Using an index outside the valid range will raise an exception. - returns: the `NSFetchedResultsSectionInfo` for the specified section */ @objc @warn_unused_result public func sectionInfoAtIndex(section: Int) -> NSFetchedResultsSectionInfo { return self.bridgeToSwift.sectionInfoAtIndex(section) } /** Returns the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if out of bounds. - parameter section: the section index. Using an index outside the valid range will return `nil`. - returns: the `NSFetchedResultsSectionInfo` for the specified section, or `nil` if the section index is out of bounds. */ @objc @warn_unused_result public func sectionInfoAtSafeSectionIndex(safeSectionIndex section: Int) -> NSFetchedResultsSectionInfo? { return self.bridgeToSwift.sectionInfoAtIndex(safeSectionIndex: section) } /** Returns the `NSFetchedResultsSectionInfo`s for all sections - returns: the `NSFetchedResultsSectionInfo`s for all sections */ @objc @warn_unused_result public func sections() -> [NSFetchedResultsSectionInfo] { return self.bridgeToSwift.sections() } /** Returns the target section for a specified "Section Index" title and index. - parameter title: the title of the Section Index - parameter index: the index of the Section Index - returns: the target section for the specified "Section Index" title and index. */ @objc @warn_unused_result public func targetSectionForSectionIndexTitle(title title: String, index: Int) -> Int { return self.bridgeToSwift.targetSectionForSectionIndex(title: title, index: index) } /** Returns the section index titles for all sections - returns: the section index titles for all sections */ @objc @warn_unused_result public func sectionIndexTitles() -> [String] { return self.bridgeToSwift.sectionIndexTitles() } /** Returns the index of the `NSManagedObject` if it exists in the `CSListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `NSManagedObject` to search the index of - returns: the index of the `NSManagedObject` if it exists in the `CSListMonitor`'s fetched objects, or `nil` if not found. */ @objc @warn_unused_result public func indexOf(object: NSManagedObject) -> NSNumber? { return self.bridgeToSwift.indexOf(object) } /** Returns the `NSIndexPath` of the `NSManagedObject` if it exists in the `CSListMonitor`'s fetched objects, or `nil` if not found. - parameter object: the `NSManagedObject` to search the index of - returns: the `NSIndexPath` of the `NSManagedObject` if it exists in the `ListMonitor`'s fetched objects, or `nil` if not found. */ @objc @warn_unused_result public func indexPathOf(object: NSManagedObject) -> NSIndexPath? { return self.bridgeToSwift.indexPathOf(object) } // MARK: Public (Observers) /** Registers a `CSListObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `CSListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `-addListObserver:` multiple times on the same observer is safe, as `CSListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `CSListObserver` to send change notifications to */ @objc public func addListObserver(observer: CSListObserver) { let swift = self.bridgeToSwift swift.unregisterObserver(observer) swift.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange?(monitor.bridgeToObjectiveC) }, didChange: { (observer, monitor) in observer.listMonitorDidChange?(monitor.bridgeToObjectiveC) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch?(monitor.bridgeToObjectiveC) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch?(monitor.bridgeToObjectiveC) } ) } /** Registers a `CSListObjectObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `CSListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `-addListObjectObserver:` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `CSListObjectObserver` to send change notifications to */ public func addListObjectObserver(observer: CSListObjectObserver) { let swift = self.bridgeToSwift swift.unregisterObserver(observer) swift.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange?(monitor.bridgeToObjectiveC) }, didChange: { (observer, monitor) in observer.listMonitorDidChange?(monitor.bridgeToObjectiveC) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch?(monitor.bridgeToObjectiveC) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch?(monitor.bridgeToObjectiveC) } ) swift.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didInsertObject: object, toIndexPath: toIndexPath) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didDeleteObject: object, fromIndexPath: fromIndexPath) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didUpdateObject: object, atIndexPath: atIndexPath) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) } ) } /** Registers a `CSListSectionObserver` to be notified when changes to the receiver's list occur. To prevent retain-cycles, `CSListMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `-addListSectionObserver:` multiple times on the same observer is safe, as `ListMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: a `CSListSectionObserver` to send change notifications to */ @objc public func addListSectionObserver(observer: CSListSectionObserver) { let swift = self.bridgeToSwift swift.unregisterObserver(observer) swift.registerObserver( observer, willChange: { (observer, monitor) in observer.listMonitorWillChange?(monitor.bridgeToObjectiveC) }, didChange: { (observer, monitor) in observer.listMonitorDidChange?(monitor.bridgeToObjectiveC) }, willRefetch: { (observer, monitor) in observer.listMonitorWillRefetch?(monitor.bridgeToObjectiveC) }, didRefetch: { (observer, monitor) in observer.listMonitorDidRefetch?(monitor.bridgeToObjectiveC) } ) swift.registerObserver( observer, didInsertObject: { (observer, monitor, object, toIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didInsertObject: object, toIndexPath: toIndexPath) }, didDeleteObject: { (observer, monitor, object, fromIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didDeleteObject: object, fromIndexPath: fromIndexPath) }, didUpdateObject: { (observer, monitor, object, atIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didUpdateObject: object, atIndexPath: atIndexPath) }, didMoveObject: { (observer, monitor, object, fromIndexPath, toIndexPath) in observer.listMonitor?(monitor.bridgeToObjectiveC, didMoveObject: object, fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) } ) swift.registerObserver( observer, didInsertSection: { (observer, monitor, sectionInfo, toIndex) in observer.listMonitor?(monitor.bridgeToObjectiveC, didInsertSection: sectionInfo, toSectionIndex: toIndex) }, didDeleteSection: { (observer, monitor, sectionInfo, fromIndex) in observer.listMonitor?(monitor.bridgeToObjectiveC, didDeleteSection: sectionInfo, fromSectionIndex: fromIndex) } ) } /** Unregisters a `CSListObserver` from receiving notifications for changes to the receiver's list. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. - parameter observer: a `CSListObserver` to unregister notifications to */ @objc public func removeListObserver(observer: CSListObserver) { self.bridgeToSwift.unregisterObserver(observer) } // MARK: Public (Refetching) /** Returns `YES` if a call to `-refetch:` was made to the `CSListMonitor` and is currently waiting for the fetching to complete. Returns `NO` otherwise. */ @objc public var isPendingRefetch: Bool { return self.bridgeToSwift.isPendingRefetch } /** Asks the `CSListMonitor` to refetch its objects using the specified series of `CSFetchClause`s. Note that this method does not execute the fetch immediately; the actual fetching will happen after the `NSFetchedResultsController`'s last `controllerDidChangeContent(_:)` notification completes. `refetch(...)` broadcasts `listMonitorWillRefetch(...)` to its observers immediately, and then `listMonitorDidRefetch(...)` after the new fetch request completes. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. Note that only specified clauses will be changed; unspecified clauses will use previous values. */ @objc public func refetch(fetchClauses: [CSFetchClause]) { self.bridgeToSwift.refetch { (fetchRequest) in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } } } // MARK: NSObject public override var hash: Int { return self.bridgeToSwift.hashValue } public override func isEqual(object: AnyObject?) -> Bool { guard let object = object as? CSListMonitor else { return false } return self.bridgeToSwift == object.bridgeToSwift } public override var description: String { return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)" } // MARK: CoreStoreObjectiveCType @nonobjc public let bridgeToSwift: ListMonitor<NSManagedObject> @nonobjc public required init<T: NSManagedObject>(_ swiftValue: ListMonitor<T>) { self.bridgeToSwift = swiftValue.upcast() super.init() } } // MARK: - ListMonitor extension ListMonitor: CoreStoreSwiftType { // MARK: CoreStoreSwiftType public var bridgeToObjectiveC: CSListMonitor { return CSListMonitor(self) } } #endif
mit
afaa36bc7c33e8a7c9b8720c10b942e2
37.380454
297
0.65592
5.24994
false
false
false
false
kreactive/FunctionalJSON
FunctionalJSONTests/PerformancesTests.swift
1
2428
// // PerformancesTests.swift // FunctionalJSON // // Created by Antoine Palazzolo on 06/11/15. // Copyright © 2015 Kreactive. All rights reserved. // import Foundation import XCTest import FunctionalJSON import FunctionalBuilder class PerformanceTests : XCTestCase { struct Foo : JSONReadable { let prop1 : String let prop2 : Int let prop3 : Int? let prop4 : Bool static let jsonRead = JSONRead(JSONPath("prop1").read(String.self) <&> JSONPath("prop2").read(Int.self) <&> JSONPath("prop3").read((Int?).self) <&> JSONPath("prop4").read(Bool.self)).map(Foo.init) } let source : [Any] = { let source : [Any] = [ [ "prop1" : "coucou", "prop2" : 2, "prop3" : 4, "prop4" : true ], [ "prop1" : "coucou", "prop2" : 2, "prop3" : NSNull(), "prop4" : true ] ] var final = [Any]() for _ in 0...200 { final.append(contentsOf: source) } return final }() func testReadPerf() { let json = try! jsonFromAny(self.source) self.measure { let _ = try! json.validate([Foo].jsonRead()) } } func testReadPerfManual() { let jsonData = try! JSONSerialization.data(withJSONObject: self.source, options: []) let json = try! JSONSerialization.jsonObject(with: jsonData, options: []) self.measure { let _ = try! self.manualParse(json) } } private enum MyError : Error { case err } func manualParse(_ json : Any) throws -> [Foo] { guard let array = json as? Array<Dictionary<String,AnyObject>> else { throw MyError.err } var foos = [Foo]() for object in array { let p1 = object["prop1"] as? String let p2 = object["prop2"] as? NSNumber let p3 = object["prop2"] as? NSNumber let p4 = object["prop2"] as? NSNumber if let p1 = p1, let p2 = p2, let p4 = p4 { let foo = Foo(prop1: p1, prop2: p2.intValue, prop3: p3?.intValue, prop4: p4.boolValue) foos.append(foo) } else { throw MyError.err } } return foos } }
mit
a04d6d13cdb7038e83276f699e3702e2
26.269663
204
0.50103
4.018212
false
true
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Highlight/CombinedHighlighter.swift
50
2549
// // CombinedHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(CombinedChartHighlighter) open class CombinedHighlighter: ChartHighlighter { /// bar highlighter for supporting stacked highlighting fileprivate var barHighlighter: BarHighlighter? public init(chart: CombinedChartDataProvider, barDataProvider: BarChartDataProvider) { super.init(chart: chart) // if there is BarData, create a BarHighlighter self.barHighlighter = barDataProvider.barData == nil ? nil : BarHighlighter(chart: barDataProvider) } open override func getHighlights(xValue: Double, x: CGFloat, y: CGFloat) -> [Highlight] { var vals = [Highlight]() guard let chart = self.chart as? CombinedChartDataProvider else { return vals } if let dataObjects = chart.combinedData?.allData { for i in 0..<dataObjects.count { let dataObject = dataObjects[i] // in case of BarData, let the BarHighlighter take over if barHighlighter != nil && dataObject is BarChartData { if let high = barHighlighter?.getHighlight(x: x, y: y) { high.dataIndex = i vals.append(high) } } else { for j in 0..<dataObject.dataSetCount { guard let dataSet = dataObjects[i].getDataSetByIndex(j) else { continue } // don't include datasets that cannot be highlighted if !dataSet.isHighlightEnabled { continue } let highs = buildHighlights(dataSet: dataSet, dataSetIndex: j, xValue: xValue, rounding: .closest) for high in highs { high.dataIndex = i vals.append(high) } } } } } return vals } }
mit
50e459e13b447810b1118a393a2bfaba
31.679487
122
0.488427
5.914153
false
false
false
false
tardieu/swift
test/SILGen/errors.swift
1
45585
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s import Swift class Cat {} enum HomeworkError : Error { case TooHard case TooMuch case CatAteIt(Cat) } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]] func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@in T) -> (@out T, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]] func dont_return<T>(_ argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} : // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]] // CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: dealloc_stack [[ARG_TEMP]] // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) func all_together_now(_ flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit // CHECK-NEXT: assign %0 to [[T1]] : $*Int // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] enum ColorError : Error { case Red, Green, Blue } //CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32 //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32 //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { _ = try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error { // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] : $HappyClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(_ fn: () throws -> T) throws -> T { return try fn() } func testThunk(_ fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs5Error__XFo__iSizoPS___ : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error) // CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to [trivial] %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: throw [[T0]] : $Error func createInt(_ fn: () -> Int) throws {} func testForceTry(_ fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> () // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int): // CHECK: [[FUNC:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: try_apply [[FUNC]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors20testForceTryMultipleFT_T_' // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error Error) // CHECK: debug_value undef : $Error, var, name "$error", argno 1 // CHECK: %1 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error Error) // CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : $Error) // CHECK: throw [[ERROR]] : $Error // Throwing statements inside cases. func getHungryCat(_ food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error Error) // CHECK: bb0(%0 : $CatFood): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR:%.*]] : $Error) // CHECK: bb7([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR]] : $Error) // CHECK: bb8([[ERROR:%.*]] : $Error): // CHECK: throw [[ERROR]] : $Error func take_many_cats(_ cats: Cat...) throws {} func test_variadic(_ cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ : $@convention(thin) (@owned Cat) -> @error Error { // CHECK: bb0([[ARG:%.*]] : $Cat): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error Error // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]] // CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]] // CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: end_borrow [[BORROWED_T1]] from [[T1]] // CHECK: destroy_value [[T1]] // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat): // CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat): // CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat): // CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]] // Complete the call and return. // CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: destroy_value %0 : $Cat // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value %0 : $Cat // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors13test_variadicFzCS_3CatT_' // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error) // CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit } // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]] // Initialize subField. // CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: assign %1 to [[T1]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load_borrow [[MARKED_BOX]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK: [[T3:%[0-9]+]] = function_ref @_TFC6errors15HasThrowingInitcfzT5valueSi_S0_ : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { associatedtype Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(_ b: inout B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error { // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] func supportStructure<B: Buildable>(_ b: inout B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @_TF6errors16supportStructure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX:%1]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: throw [[ERROR]] struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(_ b: inout Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : $@convention(thin) (@inout Bridge, @owned String) -> @error Error { // CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load [copy] [[ARG1]] : $*Bridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]]) // CHECK-NEXT: destroy_value [[BASE]] // CHECK-NEXT: store [[T0]] to [init] [[TEMP]] // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[ARG1]]) // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[ARG1]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY // CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_' struct OwnedBridge { var owner : Builtin.UnknownObject subscript(name: String) -> Pylon { addressWithOwner { return (someValidPointer(), owner) } mutableAddressWithOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ : // CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]]) // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_' struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (someValidPointer(), owner) } mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ : // CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]]) // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[OWNER]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_' // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(_ f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors15testOptionalTryFT_T_' func testOptionalTry() { _ = try? make_a_cat() } // CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_ // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors18testOptionalTryVarFT_T_' func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors26testOptionalTryAddressOnlyurFxT_' func testOptionalTryAddressOnly<T>(_ obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors29testOptionalTryAddressOnlyVarurFxT_' func testOptionalTryAddressOnlyVar<T>(_ obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_ // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors23testOptionalTryMultipleFT_T_' func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_ // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_TF6errors25testOptionalTryNeverFailsFT_T_' func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_ // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_TF6errors28testOptionalTryNeverFailsVarFT_T_' func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_TF6errors36testOptionalTryNeverFailsAddressOnlyurFxT_' func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_TFC6errors13OtherErrorSubCfT_S0_' func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } class SomeErrorClass : Error { } // CHECK-LABEL: sil_vtable SomeErrorClass // CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _TFC6errors14SomeErrorClassD // CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : _TFC6errors14SomeErrorClasscfT_S0_ // CHECK-NEXT: } class OtherErrorSub : OtherError { } // CHECK-LABEL: sil_vtable OtherErrorSub { // CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : _TFC6errors13OtherErrorSubcfT_S0_ // OtherErrorSub.init() -> OtherErrorSub // CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _TFC6errors13OtherErrorSubD // OtherErrorSub.__deallocating_deinit // CHECK-NEXT:}
apache-2.0
f318a733a67985c4cb2918eece11e25f
48.262703
234
0.602199
3.189027
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/PresentationLayer/Wallet/Settings/View/SettingsViewController.swift
1
4287
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class SettingsViewController: UIViewController { @IBOutlet var scrollView: UIScrollView! @IBOutlet var currencyImageView: UIImageView! @IBOutlet var currencyIsoLabel: UILabel! @IBOutlet var currencyButton: UIButton! @IBOutlet var changePasscodeButton: UIButton! @IBOutlet var touchIdImageView: UIImageView! @IBOutlet var touchIdButton: UIButton! @IBOutlet var touchIdSwitch: UISwitch! @IBOutlet var pushButton: UIButton! @IBOutlet var pushSwitch: UISwitch! @IBOutlet var rateButton: UIButton! @IBOutlet var twitterButton: UIButton! @IBOutlet var githubButton: UIButton! @IBOutlet var backupButton: UIButton! @IBOutlet var logoutButton: UIButton! @IBOutlet var versionLabel: UILabel! var output: SettingsViewOutput! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = Localized.settingsTitle() scrollView.setupBorder() localize() output.viewIsReady() } // MARK: Privates private func localize() { currencyButton.setTitle(Localized.settingsCurrency(), for: .normal) changePasscodeButton.setTitle(Localized.settingsChangePasscode(), for: .normal) pushButton.setTitle(Localized.settingsPush(), for: .normal) rateButton.setTitle(Localized.settingsRate(), for: .normal) twitterButton.setTitle(Localized.settingsTwitterTitle(), for: .normal) githubButton.setTitle(Localized.settingsGithubTitle(), for: .normal) backupButton.setTitle(Localized.settingsBackup(), for: .normal) logoutButton.setTitle(Localized.settingsLogout(), for: .normal) versionLabel.text = Localized.settingsVersion(Bundle.main.version) } // MARK: Actions @IBAction func currencyPressed(_ sender: UIButton) { output.didCurrencyPressed() } @IBAction func changePasscodePressed(_ sender: UIButton) { showAlert(title: Localized.settingsChangeAlertTitle(), message: Localized.settingsChangeAlertMsg(), cancelable: true) { _ in self.output.didChangePasscodePressed() } } @IBAction func touchIdPressed(_ sender: UIButton) { let isOn = !touchIdSwitch.isOn touchIdSwitch.setOn(isOn, animated: true) output.didTouchIdValueChanged(isOn) } @IBAction func pushPressed(_ sender: UIButton) { let isOn = !pushSwitch.isOn pushSwitch.setOn(isOn, animated: true) output.didPushValueChanged(isOn) } @IBAction func backupPressed(_ sender: UIButton) { output.didBackupPressed() } @IBAction func touchIdValueChanged(_ sender: UISwitch) { output.didTouchIdValueChanged(sender.isOn) } @IBAction func pushValueChanged(_ sender: UISwitch) { output.didPushValueChanged(sender.isOn) } @IBAction func ratePressed(_ sender: UIButton) { output.didRateAppPressed() } @IBAction func twitterPressed(_ sender: UIButton) { UIApplication.shared.openURL(URL(string: Constants.Conicoin.twitter)!) } @IBAction func githubPressed(_ sender: UIButton) { UIApplication.shared.openURL(URL(string: Constants.Conicoin.github)!) } @IBAction func logoutPressed(_ sender: UIButton) { showAlert(title: Localized.settingsExitAlertTitle(), message: Localized.settingsExitAlertMsg(), cancelable: true) { _ in self.output.didLogoutPressed() } } } // MARK: - SettingsViewInput extension SettingsViewController: SettingsViewInput { func setupInitialState() { } func setIsTouchIdEnabled(_ isTouchIdEnabled: Bool) { touchIdSwitch.isOn = isTouchIdEnabled } func setTouchId(title: String, image: String) { touchIdButton.setTitle(title, for: .normal) touchIdImageView.image = UIImage(named: image) } func setCurrency(_ currency: FiatCurrency) { currencyImageView.image = currency.icon currencyIsoLabel.text = currency.iso } func shareFileAtUrl(_ url: URL) { let objectsToShare = [url] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) present(activityVC, animated: true, completion: nil) } func setPushSwitch(_ iOn: Bool) { pushSwitch.setOn(iOn, animated: true) } }
gpl-3.0
c2b8935baf3477521dececdaf59ac808
28.558621
104
0.718852
4.418557
false
false
false
false
valentinknabel/QueuedNet
Sources/QueuedNet/NetBuilder.swift
1
2796
// // NetBuilder.swift // QueuedNet // // Created by Valentin Knabel on 02.03.15. // Copyright (c) 2015 Valentin Knabel. All rights reserved. // import Foundation /// A Net Builder is used for configuring multiple Nets. public class NetBuilder<T: NetNodeRawType> { public typealias TransitionHandler = NetTransition<T>.TransitionHandler public typealias ErrorHandler = NetTransition<T>.ErrorHandler /// A closure to configure the Builder. public typealias BuildClosure = (NetBuilder<T>) -> () internal var rawNodes: [T] = [] internal var rawTransitions: [NetRawTransition<T>] = [] internal var rawInitials: [T] /** Initializes a net builder. - Parameter initials The raw values for all initial states. - Parameter buildClosure The closure to configure the net builder. */ public init(initials: [T], buildClosure: BuildClosure) { assert(initials.count > 0, "A net must always have at least one initial node.") self.rawInitials = initials buildClosure(self) let inits = generateNodes().values.filter { initials.contains($0.rawValue) } assert(inits.reduce(true, { (b: Bool, i: NetNode<T>) -> Bool in b && i.outgoingTransition != nil }), "All initial nodes must have outgoing transitions.") } /** Adds a transition and implicitly missing Nodes. - Parameter from The transition's input nodes' raw values. If all nodes' state is Triggered, the transition will be performed. - Parameter to The transition's output nodes' raw values. All nodes' states will be set to Running once the transition has finished. - Parameter perform The transition handler to perform the transition. Will be executed in the transition's own thread. - Parameter error The error handler to resolve input nodes errors. Will be executed in the transition's own thread. */ public func addTransition(from: [T], to: [T], perform: TransitionHandler? = nil, error: ErrorHandler? = nil) { self.rawNodes.append(contentsOf: from) self.rawNodes.append(contentsOf: to) let transition = NetRawTransition<T>(inputNodes: from, outputNodes: to, transitionHandler: perform, errorHandler: error) rawTransitions.append(transition) } /** Generates new node objects. - Returns Instances for all raw nodes. */ internal func generateNodes() -> [T: NetNode<T>] { let nodes = rawNodes.map { NetNode<T>(rawValue: $0)! } var nodeHash = [T: NetNode<T>]() for n in nodes { nodeHash[n.rawValue] = n } rawTransitions.forEach { (rt: NetRawTransition<T>) in rt.transtition(nodes: nodeHash) } return nodeHash } }
mit
8fb2ce36f4b8ea6a2e874c59e6be7ac3
37.833333
136
0.66166
4.334884
false
false
false
false