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
AlicJ/CPUSimulator
CPUSimulator/BinaryUtils.swift
1
1559
// // Binary.swift // CPUSimulator // // Created by Alic on 2017-06-29. // Copyright © 2017 4ZC3. All rights reserved. // http://sketchytech.blogspot.ca/2015/11/bytes-for-beginners-representation-of.html import Foundation class BinaryUtils { static func toBinary(num:Int8) -> String { var numm:UInt8 = 0 if num < 0 { let a = Int(UInt8.max) + Int(num) + 1 numm = UInt8(a) } else { return String(num, radix:2).leftPad(toLength: 8, withPad: "0") } return String(numm, radix:2).leftPad(toLength: 8, withPad: "0") } static func toBinary(num:Int16) -> String { var numm:UInt16 = 0 if num < 0 { let a = Int(UInt16.max) + Int(num) + 1 numm = UInt16(a) } else { return String(num, radix:2).leftPad(toLength: 16, withPad: "0") } return String(numm, radix:2).leftPad(toLength: 16, withPad: "0") } static func toBinary(num:Int32) -> String { var numm:UInt32 = 0 if num < 0 { let a = Int64(UInt32.max) + Int(num) + 1 numm = UInt32(a) } else { return String(num, radix:2).leftPad(toLength: 32, withPad: "0") } return String(numm, radix:2).leftPad(toLength: 32, withPad: "0") } static func toBinary(str: String) -> Int8 { return Int8(str)! } static func toBinary(str: String) -> Int16 { return Int16(str)! } static func toBinary(str: String) -> Int32 { return Int32(str)! } }
mit
98fd34125bc14d5228a415ec430675ef
27.851852
85
0.552632
3.25261
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/String+FullwidthTransform.swift
2
2005
// // String+FullwidthTransform.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-07-31. // // --------------------------------------------------------------------------- // // © 2014-2020 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // extension StringProtocol { // MARK: Public Properties /// Transform half-width roman characters to full-width forms, or vice versa. /// /// - Parameter reverse: `True` to transform from full-width to half-width. /// - Returns: A transformed string. func fullwidthRoman(reverse: Bool = false) -> String { return self.unicodeScalars .map { $0.convertedToFullwidthRoman(reverse: reverse) ?? $0 } .reduce(into: "") { $0.unicodeScalars.append($1) } } } // MARK: - Private Extensions private extension Unicode.Scalar { private static let fullwidthRomanRange: ClosedRange<UTF32.CodeUnit> = 0xFF01...0xFF5E private static let widthShifter: UTF32.CodeUnit = 0xFEE0 func convertedToFullwidthRoman(reverse: Bool = false) -> Self? { let fullwidthValue = reverse ? self.value : self.value + Self.widthShifter guard Self.fullwidthRomanRange.contains(fullwidthValue) else { return nil } let newScalar = reverse ? self.value - Self.widthShifter : self.value + Self.widthShifter return Self(newScalar) } }
apache-2.0
91446e64f3b931566d517962349f5805
29.363636
89
0.628743
4.183716
false
false
false
false
victor-pavlychko/Encoder
Encoder/EncodableAsDictionary.swift
1
1023
// // EncodableAsDictionary.swift // Encoder // // Created by Victor Pavlychko on 12/8/16. // Copyright © 2016 address.wtf. All rights reserved. // import Foundation public protocol EncodableAsDictionary: Encodable, FailableEncodable { associatedtype Key associatedtype Value } public extension EncodableAsDictionary where Self: Sequence, Self.Iterator.Element == (key: Self.Key, value: Self.Value) { public func failableEncode() throws -> Any { var encoded: [String: Any] = [:] for (possibleKey, possibleValue) in self { guard let key = possibleKey as? String else { throw EncodableError.invalidKey(key: possibleKey) } guard let value = possibleValue as? Encodable else { throw EncodableError.invalidValue(value: possibleValue) } encoded[key] = value } return encoded } } extension Dictionary: EncodableAsDictionary { } extension NSDictionary: EncodableAsDictionary { }
mit
4b5fe56a6ccf5d23a6fe9d24222a8c5b
27.388889
122
0.66047
4.709677
false
false
false
false
toshiapp/toshi-ios-client
Toshi/MessagesUI/Cells/MessagesTextCell.swift
1
3593
import Foundation import UIKit import TinyConstraints class MessagesTextCell: MessagesBasicCell { static let reuseIdentifier = "MessagesTextCell" var messageText: String? { didSet { if let messageText = messageText, messageText.hasEmojiOnly, messageText.emojiVisibleLength <= 3 { textView.text = messageText bubbleView.backgroundColor = nil textView.font = Theme.emoji() } else { let usernameLinkColor = isOutGoing ? Theme.lightTextColor : Theme.tintColor textView.attributedText = TextTransformer.attributedUsernameString(to: messageText, textColor: messageColor, linkColor: usernameLinkColor, font: Theme.preferredRegularText()) } } } private var messageColor: UIColor { return isOutGoing ? .white : .black } private lazy var textView: UITextView = { let view = UITextView() view.font = Theme.preferredRegularText() view.adjustsFontForContentSizeCategory = true view.dataDetectorTypes = [.link] view.isUserInteractionEnabled = true view.isScrollEnabled = false view.isEditable = false view.backgroundColor = .clear view.contentMode = .topLeft view.textContainerInset = .zero view.textContainer.lineFragmentPadding = 0 view.textContainer.maximumNumberOfLines = 0 view.delegate = self view.linkTextAttributes = [NSAttributedStringKey.underlineStyle.rawValue: NSUnderlineStyle.styleSingle.rawValue] return view }() override var isOutGoing: Bool { didSet { super.isOutGoing = isOutGoing textView.textColor = isOutGoing ? .white : .black bubbleView.backgroundColor = isOutGoing ? Theme.tintColor : Theme.incomingMessageBackgroundColor } } override func showSentError(_ show: Bool, animated: Bool) { super.showSentError(show, animated: animated) textView.isUserInteractionEnabled = !show } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) bubbleView.addSubview(textView) textView.edges(to: bubbleView, insets: UIEdgeInsets(top: 8, left: 12, bottom: -8, right: -12)) } override func prepareForReuse() { super.prepareForReuse() if let text = textView.attributedText?.mutableCopy() as? NSMutableAttributedString { let range = NSRange(location: 0, length: text.string.count) text.removeAttribute(.link, range: range) text.removeAttribute(.foregroundColor, range: range) text.removeAttribute(.underlineStyle, range: range) textView.attributedText = text } textView.font = Theme.preferredRegularText() textView.adjustsFontForContentSizeCategory = true textView.text = nil } } extension MessagesTextCell: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { guard URL.scheme != "toshi" else { return true } guard URL.absoluteString.asPossibleURLString != nil else { return false } let controller = SOFAWebController() controller.load(url: URL) Navigator.presentModally(controller) return false } }
gpl-3.0
5a3fb115c45f1b6b3ed88ad60fed1561
33.883495
190
0.662677
5.386807
false
false
false
false
Jnosh/swift
stdlib/public/core/DebuggerSupport.swift
21
8808
//===--- DebuggerSupport.swift --------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// public enum _DebuggerSupport { internal enum CollectionStatus { case NotACollection case CollectionOfElements case CollectionOfPairs case Element case Pair case ElementOfPair internal var isCollection: Bool { return self != .NotACollection } internal func getChildStatus(child: Mirror) -> CollectionStatus { let disposition = child.displayStyle ?? .struct if disposition == .collection { return .CollectionOfElements } if disposition == .dictionary { return .CollectionOfPairs } if disposition == .set { return .CollectionOfElements } if self == .CollectionOfElements { return .Element } if self == .CollectionOfPairs { return .Pair } if self == .Pair { return .ElementOfPair } return .NotACollection } } internal static func isClass(_ value: Any) -> Bool { if let _ = type(of: value) as? AnyClass { return true } return false } internal static func checkValue<T>( _ value: Any, ifClass: (AnyObject) -> T, otherwise: () -> T ) -> T { if isClass(value) { return ifClass(_unsafeDowncastToAnyObject(fromAny: value)) } return otherwise() } internal static func asObjectIdentifier(_ value: Any) -> ObjectIdentifier? { return checkValue(value, ifClass: { return ObjectIdentifier($0) }, otherwise: { return nil }) } internal static func asNumericValue(_ value: Any) -> Int { return checkValue(value, ifClass: { return unsafeBitCast($0, to: Int.self) }, otherwise: { return 0 }) } internal static func asStringRepresentation( value: Any?, mirror: Mirror, count: Int ) -> String? { let ds = mirror.displayStyle ?? .`struct` switch ds { case .optional: if count > 0 { return "\(mirror.subjectType)" } else { if let x = value { return String(reflecting: x) } } case .collection: fallthrough case .dictionary: fallthrough case .set: fallthrough case .tuple: if count == 1 { return "1 element" } else { return "\(count) elements" } case .`struct`: fallthrough case .`enum`: if let x = value { if let cdsc = (x as? CustomDebugStringConvertible) { return cdsc.debugDescription } if let csc = (x as? CustomStringConvertible) { return csc.description } } if count > 0 { return "\(mirror.subjectType)" } case .`class`: if let x = value { if let cdsc = (x as? CustomDebugStringConvertible) { return cdsc.debugDescription } if let csc = (x as? CustomStringConvertible) { return csc.description } // for a Class with no custom summary, mimic the Foundation default return "<\(type(of: x)): 0x\(String(asNumericValue(x), radix: 16, uppercase: false))>" } else { // but if I can't provide a value, just use the type anyway return "\(mirror.subjectType)" } } if let x = value { return String(reflecting: x) } return nil } internal static func ivarCount(mirror: Mirror) -> Int { let count = Int(mirror.children.count) if let sc = mirror.superclassMirror { return ivarCount(mirror: sc) + count } else { return count } } internal static func shouldExpand( mirror: Mirror, collectionStatus: CollectionStatus, isRoot: Bool ) -> Bool { if isRoot || collectionStatus.isCollection { return true } let count = Int(mirror.children.count) if count > 0 { return true } if let sc = mirror.superclassMirror { return ivarCount(mirror: sc) > 0 } else { return true } } internal static func printForDebuggerImpl<StreamType : TextOutputStream>( value: Any?, mirror: Mirror, name: String?, indent: Int, maxDepth: Int, isRoot: Bool, parentCollectionStatus: CollectionStatus, refsAlreadySeen: inout Set<ObjectIdentifier>, maxItemCounter: inout Int, targetStream: inout StreamType ) { if maxItemCounter <= 0 { return } if !shouldExpand(mirror: mirror, collectionStatus: parentCollectionStatus, isRoot: isRoot) { return } maxItemCounter -= 1 for _ in 0..<indent { print(" ", terminator: "", to: &targetStream) } // do not expand classes with no custom Mirror // yes, a type can lie and say it's a class when it's not since we only // check the displayStyle - but then the type would have a custom Mirror // anyway, so there's that... var willExpand = true if let ds = mirror.displayStyle { if ds == .`class` { if let x = value { if !(x is CustomReflectable) { willExpand = false } } } } let count = Int(mirror.children.count) let bullet = isRoot && (count == 0 || !willExpand) ? "" : count == 0 ? "- " : maxDepth <= 0 ? "▹ " : "▿ " print("\(bullet)", terminator: "", to: &targetStream) let collectionStatus = parentCollectionStatus.getChildStatus(child: mirror) if let nam = name { print("\(nam) : ", terminator: "", to: &targetStream) } if let str = asStringRepresentation(value: value, mirror: mirror, count: count) { print("\(str)", terminator: "", to: &targetStream) } if (maxDepth <= 0) || !willExpand { print("", to: &targetStream) return } if let x = value { if let valueIdentifier = asObjectIdentifier(x) { if refsAlreadySeen.contains(valueIdentifier) { print(" { ... }", to: &targetStream) return } else { refsAlreadySeen.insert(valueIdentifier) } } } print("", to: &targetStream) var printedElements = 0 if let sc = mirror.superclassMirror { printForDebuggerImpl( value: nil, mirror: sc, name: "super", indent: indent + 2, maxDepth: maxDepth - 1, isRoot: false, parentCollectionStatus: .NotACollection, refsAlreadySeen: &refsAlreadySeen, maxItemCounter: &maxItemCounter, targetStream: &targetStream) } for (optionalName,child) in mirror.children { let childName = optionalName ?? "\(printedElements)" if maxItemCounter <= 0 { for _ in 0..<(indent+4) { print(" ", terminator: "", to: &targetStream) } let remainder = count - printedElements print("(\(remainder)", terminator: "", to: &targetStream) if printedElements > 0 { print(" more", terminator: "", to: &targetStream) } if remainder == 1 { print(" child)", to: &targetStream) } else { print(" children)", to: &targetStream) } return } printForDebuggerImpl( value: child, mirror: Mirror(reflecting: child), name: childName, indent: indent + 2, maxDepth: maxDepth - 1, isRoot: false, parentCollectionStatus: collectionStatus, refsAlreadySeen: &refsAlreadySeen, maxItemCounter: &maxItemCounter, targetStream: &targetStream) printedElements += 1 } } // LLDB uses this function in expressions, and if it is inlined the resulting // LLVM IR is enormous. As a result, to improve LLDB performance we have made // this stdlib_binary_only, which prevents inlining. @_semantics("stdlib_binary_only") public static func stringForPrintObject(_ value: Any) -> String { var maxItemCounter = Int.max var refs = Set<ObjectIdentifier>() var targetStream = "" printForDebuggerImpl( value: value, mirror: Mirror(reflecting: value), name: nil, indent: 0, maxDepth: maxItemCounter, isRoot: true, parentCollectionStatus: .NotACollection, refsAlreadySeen: &refs, maxItemCounter: &maxItemCounter, targetStream: &targetStream) return targetStream } }
apache-2.0
56cef95ffe367d168d65cdbefa0daa02
27.4
96
0.582803
4.535806
false
false
false
false
vscarpenter/Tipster
Tipster/Tipster/SettingsViewController.swift
1
1595
// // SettingsViewController.swift // Tipster // // Created by Vinny Carpenter on 12/26/14. // Copyright (c) 2014 Vinny Carpenter. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet var tipLabel: UILabel! @IBOutlet var tipControl: UISegmentedControl! let tips = [18, 20, 25] var userDefaults : NSUserDefaults? let defaultTip: Double? override func viewDidLoad() { super.viewDidLoad() selectCorrectSegment() tipControl.layer.cornerRadius = 5.0 tipControl.layer.masksToBounds = true tipControl.tintColor = UIColor(red: 92.0/255, green: 69.0/255, blue: 133.0/255, alpha: 0.8) } override func viewWillAppear(animated: Bool) { selectCorrectSegment() } func selectCorrectSegment() { userDefaults = NSUserDefaults.standardUserDefaults() let tipVal = userDefaults?.integerForKey("defaultTip") tipControl.selectedSegmentIndex = 0 for (index,tmp) in enumerate(tips) { if(tipVal == tmp){ tipControl.selectedSegmentIndex = index } } let currentTip = tips[tipControl.selectedSegmentIndex] self.tipLabel.text = "Default Tip is \(currentTip)%" } @IBAction func defaultTipChanged(sender: AnyObject) { let currentTip = tips[tipControl.selectedSegmentIndex] self.tipLabel.text = "Default Tip is \(currentTip)%" userDefaults?.setInteger(currentTip, forKey: "defaultTip") userDefaults?.synchronize() } }
mit
ddf5c5df15e75fde7fc0d0bdaa2a3062
30.27451
99
0.648276
4.583333
false
false
false
false
artyom-stv/TextInputKit
Example/Example/iOS/Code/BankCard/BankCardView.swift
1
931
// // BankCardView.swift // Example // // Created by Artem Starosvetskiy on 15/12/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import UIKit final class BankCardView: UIView { // MARK: - Override NSObject override func awakeFromNib() { super.awakeFromNib() layer.borderColor = type(of: self).borderColor.cgColor layer.cornerRadius = type(of: self).cornerRadius } // MARK: - Override UIView override func willMove(toWindow newWindow: UIWindow?) { super.willMove(toWindow: newWindow) if let window = newWindow { layer.borderWidth = type(of: self).borderWidth / window.screen.scale } } // MARK: - Constants private static let borderWidth: CGFloat = 1.0 private static let borderColor: UIColor = UIColor(white: CGFloat(0.0), alpha: CGFloat(0.2)) private static let cornerRadius: CGFloat = 10.0 }
mit
3d5b4922eee31a18ba7f85ebe43369e9
24.833333
95
0.66129
4.325581
false
false
false
false
valitovaza/NewsAP
NewsAP/NewsFeed/NewsStore.swift
1
2443
protocol ArticleDataStoreProtocol { func add(_ articles: [Article], for source: String) func clear() func sectionCount() -> Int func count(for section: Int) -> Int func count() -> Int func source(for section: Int) -> String func article(for index: Int, in section: Int) -> Article func lastChanges() -> NewsStoreChange } enum NewsStoreChange { case Reload case NewSource(Int) case AddNewsToSource(Int, Int) } class NewsStore: ArticleDataStoreProtocol { private var savedArticles: [String: [Article]] = [:] private var sections: [String] = [] func add(_ articles: [Article], for source: String) { addArticles(articles, for: source) addSource(source) } private func addArticles(_ articles: [Article], for source: String) { if let oldArticles = savedArticles[source] { var newArticles = oldArticles newArticles.append(contentsOf: articles) computeChange(for: source, count: articles.count) savedArticles[source] = newArticles }else{ computeChange(count: articles.count) savedArticles[source] = articles } } private func computeChange(for source: String, count articlesCount: Int) { let index = sections.index(of: source) ?? 0 changes = count() == 0 ? .Reload : .AddNewsToSource(index, articlesCount) } private func computeChange(count articlesCount: Int) { changes = count() == 0 ? .Reload : .NewSource(articlesCount) } private func addSource(_ source: String) { if !sections.contains(source) { sections.append(source) } } func clear() { sections.removeAll() savedArticles.removeAll() } func sectionCount() -> Int { return sections.count } func count() -> Int { return savedArticles.values.flatMap({$0.count}).reduce(0, +) } func count(for section: Int) -> Int { guard sections.count > section else {return 0} return savedArticles[sections[section]]?.count ?? 0 } func source(for section: Int) -> String { return sections[section] } func article(for index: Int, in section: Int) -> Article { return savedArticles[sections[section]]![index] } private var changes: NewsStoreChange = .Reload func lastChanges() -> NewsStoreChange { return changes } }
mit
93c1de6fffd8443f2d6c7307fd3e5854
32.930556
81
0.622186
4.278459
false
false
false
false
kesun421/firefox-ios
Account/FxAClient10.swift
1
23540
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Alamofire import Shared import Foundation import FxA import Deferred import SwiftyJSON public let FxAClientErrorDomain = "org.mozilla.fxa.error" public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) let KeyLength: Int = 32 public struct FxALoginResponse { public let remoteEmail: String public let uid: String public let verified: Bool public let sessionToken: Data public let keyFetchToken: Data } public struct FxAccountRemoteError { static let AttemptToOperateOnAnUnverifiedAccount: Int32 = 104 static let InvalidAuthenticationToken: Int32 = 110 static let EndpointIsNoLongerSupported: Int32 = 116 static let IncorrectLoginMethodForThisAccount: Int32 = 117 static let IncorrectKeyRetrievalMethodForThisAccount: Int32 = 118 static let IncorrectAPIVersionForThisAccount: Int32 = 119 static let UnknownDevice: Int32 = 123 static let DeviceSessionConflict: Int32 = 124 static let UnknownError: Int32 = 999 } public struct FxAKeysResponse { let kA: Data let wrapkB: Data } public struct FxASignResponse { let certificate: String } public struct FxAStatusResponse { let exists: Bool } public struct FxADevicesResponse { let devices: [FxADevice] } public struct FxANotifyResponse { let success: Bool } public struct FxAOAuthResponse { let accessToken: String } public struct FxAProfileResponse { let email: String let uid: String let avatarURL: String? let displayName: String? } public struct FxADeviceDestroyResponse { let success: Bool } // fxa-auth-server produces error details like: // { // "code": 400, // matches the HTTP status code // "errno": 107, // stable application-level error number // "error": "Bad Request", // string description of the error type // "message": "the value of salt is not allowed to be undefined", // "info": "https://docs.dev.lcip.og/errors/1234" // link to more info on the error // } public enum FxAClientError { case remote(RemoteError) case local(NSError) } // Be aware that string interpolation doesn't work: rdar://17318018, much good that it will do. extension FxAClientError: MaybeErrorType { public var description: String { switch self { case let .remote(error): let errorString = error.error ?? NSLocalizedString("Missing error", comment: "Error for a missing remote error number") let messageString = error.message ?? NSLocalizedString("Missing message", comment: "Error for a missing remote error message") return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>" case let .local(error): return "<FxAClientError.Local Error Domain=\(error.domain) Code=\(error.code) \"\(error.localizedDescription)\">" } } } public struct RemoteError { let code: Int32 let errno: Int32 let error: String? let message: String? let info: String? var isUpgradeRequired: Bool { return errno == FxAccountRemoteError.EndpointIsNoLongerSupported || errno == FxAccountRemoteError.IncorrectLoginMethodForThisAccount || errno == FxAccountRemoteError.IncorrectKeyRetrievalMethodForThisAccount || errno == FxAccountRemoteError.IncorrectAPIVersionForThisAccount } var isInvalidAuthentication: Bool { return code == 401 } var isUnverified: Bool { return errno == FxAccountRemoteError.AttemptToOperateOnAnUnverifiedAccount } } open class FxAClient10 { let authURL: URL let oauthURL: URL let profileURL: URL public init(authEndpoint: URL? = nil, oauthEndpoint: URL? = nil, profileEndpoint: URL? = nil) { self.authURL = authEndpoint ?? ProductionFirefoxAccountConfiguration().authEndpointURL as URL self.oauthURL = oauthEndpoint ?? ProductionFirefoxAccountConfiguration().oauthEndpointURL as URL self.profileURL = profileEndpoint ?? ProductionFirefoxAccountConfiguration().profileEndpointURL as URL } open class func KW(_ kw: String) -> Data { return ("identity.mozilla.com/picl/v1/" + kw).utf8EncodedData } /** * The token server accepts an X-Client-State header, which is the * lowercase-hex-encoded first 16 bytes of the SHA-256 hash of the * bytes of kB. */ open class func computeClientState(_ kB: Data) -> String? { if kB.count != 32 { return nil } return kB.sha256.subdata(in: 0..<16).hexEncodedString } open class func quickStretchPW(_ email: Data, password: Data) -> Data { var salt = KW("quickStretch") salt.append(":".utf8EncodedData) salt.append(email) return (password as NSData).derivePBKDF2HMACSHA256Key(withSalt: salt as Data!, iterations: 1000, length: 32) } open class func computeUnwrapKey(_ stretchedPW: Data) -> Data { let salt: Data = Data() let contextInfo: Data = KW("unwrapBkey") let bytes = (stretchedPW as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(KeyLength)) return bytes! } fileprivate class func remoteError(fromJSON json: JSON, statusCode: Int) -> RemoteError? { if json.error != nil || 200 <= statusCode && statusCode <= 299 { return nil } if let code = json["code"].int32 { if let errno = json["errno"].int32 { return RemoteError(code: code, errno: errno, error: json["error"].string, message: json["message"].string, info: json["info"].string) } } return nil } fileprivate class func loginResponse(fromJSON json: JSON) -> FxALoginResponse? { guard json.error == nil, let uid = json["uid"].string, let verified = json["verified"].bool, let sessionToken = json["sessionToken"].string, let keyFetchToken = json["keyFetchToken"].string else { return nil } return FxALoginResponse(remoteEmail: "", uid: uid, verified: verified, sessionToken: sessionToken.hexDecodedData, keyFetchToken: keyFetchToken.hexDecodedData) } fileprivate class func keysResponse(fromJSON keyRequestKey: Data, json: JSON) -> FxAKeysResponse? { guard json.error == nil, let bundle = json["bundle"].string else { return nil } let data = bundle.hexDecodedData guard data.count == 3 * KeyLength else { return nil } let ciphertext = data.subdata(in: 0..<(2 * KeyLength)) let MAC = data.subdata(in: (2 * KeyLength)..<(3 * KeyLength)) let salt: Data = Data() let contextInfo: Data = KW("account/keys") let bytes = (keyRequestKey as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength)) let respHMACKey = bytes?.subdata(in: 0..<KeyLength) let respXORKey = bytes?.subdata(in: KeyLength..<(3 * KeyLength)) guard let hmacKey = respHMACKey, ciphertext.hmacSha256WithKey(hmacKey) == MAC else { NSLog("Bad HMAC in /keys response!") return nil } guard let xorKey = respXORKey, let xoredBytes = ciphertext.xoredWith(xorKey) else { return nil } let kA = xoredBytes.subdata(in: 0..<KeyLength) let wrapkB = xoredBytes.subdata(in: KeyLength..<(2 * KeyLength)) return FxAKeysResponse(kA: kA, wrapkB: wrapkB) } fileprivate class func signResponse(fromJSON json: JSON) -> FxASignResponse? { guard json.error == nil, let cert = json["cert"].string else { return nil } return FxASignResponse(certificate: cert) } fileprivate class func statusResponse(fromJSON json: JSON) -> FxAStatusResponse? { guard json.error == nil, let exists = json["exists"].bool else { return nil } return FxAStatusResponse(exists: exists) } fileprivate class func devicesResponse(fromJSON json: JSON) -> FxADevicesResponse? { guard json.error == nil, let jsonDevices = json.array else { return nil } let devices = jsonDevices.flatMap { (jsonDevice) -> FxADevice? in return FxADevice.fromJSON(jsonDevice) } return FxADevicesResponse(devices: devices) } fileprivate class func notifyResponse(fromJSON json: JSON) -> FxANotifyResponse { return FxANotifyResponse(success: json.error == nil) } fileprivate class func deviceDestroyResponse(fromJSON json: JSON) -> FxADeviceDestroyResponse { return FxADeviceDestroyResponse(success: json.error == nil) } fileprivate class func oauthResponse(fromJSON json: JSON) -> FxAOAuthResponse? { guard json.error == nil, let accessToken = json["access_token"].string else { return nil } return FxAOAuthResponse(accessToken: accessToken) } fileprivate class func profileResponse(fromJSON json: JSON) -> FxAProfileResponse? { guard json.error == nil, let uid = json["uid"].string, let email = json["email"].string else { return nil } let avatarURL = json["avatar"].string let displayName = json["displayName"].string return FxAProfileResponse(email: email, uid: uid, avatarURL: avatarURL, displayName: displayName) } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.fxaUserAgent let configuration = URLSessionConfiguration.ephemeral var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:] defaultHeaders["User-Agent"] = ua configuration.httpAdditionalHeaders = defaultHeaders return SessionManager(configuration: configuration) }() open func login(_ emailUTF8: Data, quickStretchedPW: Data, getKeys: Bool) -> Deferred<Maybe<FxALoginResponse>> { let authPW = (quickStretchedPW as NSData).deriveHKDFSHA256Key(withSalt: Data(), contextInfo: FxAClient10.KW("authPW"), length: 32) as NSData let parameters = [ "email": NSString(data: emailUTF8, encoding: String.Encoding.utf8.rawValue)!, "authPW": authPW.base16EncodedString(options: NSDataBase16EncodingOptions.lowerCase) as NSString, ] var URL: URL = self.authURL.appendingPathComponent("/account/login") if getKeys { var components = URLComponents(url: URL, resolvingAgainstBaseURL: false)! components.query = "keys=true" URL = components.url! } var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = JSON(parameters).stringValue()?.utf8EncodedData return makeRequest(mutableURLRequest, responseHandler: FxAClient10.loginResponse) } open func status(forUID uid: String) -> Deferred<Maybe<FxAStatusResponse>> { let statusURL = self.authURL.appendingPathComponent("/account/status").withQueryParam("uid", value: uid) var mutableURLRequest = URLRequest(url: statusURL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") return makeRequest(mutableURLRequest, responseHandler: FxAClient10.statusResponse) } open func devices(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevicesResponse>> { let URL = self.authURL.appendingPathComponent("/account/devices") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.devicesResponse) } open func notify(deviceIDs: [GUID], collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> { let httpBody = JSON([ "to": deviceIDs, "payload": [ "version": 1, "command": "sync:collection_changed", "data": [ "collections": collections, "reason": reason ] ] ]) return self.notify(httpBody: httpBody, withSessionToken: sessionToken) } open func notifyAll(ownDeviceId: GUID, collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> { let httpBody = JSON([ "to": "all", "excluded": [ownDeviceId], "payload": [ "version": 1, "command": "sync:collection_changed", "data": [ "collections": collections, "reason": reason ] ] ]) return self.notify(httpBody: httpBody, withSessionToken: sessionToken) } fileprivate func notify(httpBody: JSON, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> { let URL = self.authURL.appendingPathComponent("/account/devices/notify") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.notifyResponse) } open func destroyDevice(ownDeviceId: GUID, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADeviceDestroyResponse>> { let URL = self.authURL.appendingPathComponent("/account/device/destroy") var mutableURLRequest = URLRequest(url: URL) let httpBody: JSON = JSON(["id": ownDeviceId]) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.deviceDestroyResponse) } open func registerOrUpdate(device: FxADevice, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevice>> { let URL = self.authURL.appendingPathComponent("/account/device") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = device.toJSON().stringValue()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxADevice.fromJSON) } open func oauthAuthorize(withSessionToken sessionToken: NSData, keyPair: RSAKeyPair, certificate: String) -> Deferred<Maybe<FxAOAuthResponse>> { let audience = self.getAudience(forURL: self.oauthURL) let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey, certificate: certificate, audience: audience) let oauthAuthorizationURL = self.oauthURL.appendingPathComponent("/authorization") var mutableURLRequest = URLRequest(url: oauthAuthorizationURL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let parameters = [ "assertion": assertion, "client_id": AppConstants.FxAiOSClientId, "response_type": "token", "scope": "profile", "ttl": "300" ] let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! guard let httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData else { return deferMaybe(FxAClientError.local(FxAClientUnknownError)) } mutableURLRequest.httpBody = httpBody mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.oauthResponse) } open func getProfile(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxAProfileResponse>> { let keyPair = RSAKeyPair.generate(withModulusSize: 1024)! return self.sign(sessionToken as Data, publicKey: keyPair.publicKey) >>== { signResult in return self.oauthAuthorize(withSessionToken: sessionToken, keyPair: keyPair, certificate: signResult.certificate) >>== { oauthResult in let profileURL = self.profileURL.appendingPathComponent("/profile") var mutableURLRequest = URLRequest(url: profileURL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.setValue("Bearer " + oauthResult.accessToken, forHTTPHeaderField: "Authorization") return self.makeRequest(mutableURLRequest, responseHandler: FxAClient10.profileResponse) } } } open func getAudience(forURL URL: URL) -> String { if let port = URL.port { return "\(URL.scheme!)://\(URL.host!):\(port)" } else { return "\(URL.scheme!)://\(URL.host!)" } } fileprivate func makeRequest<T>(_ request: URLRequest, responseHandler: @escaping (JSON) -> T?) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() alamofire.request(request) .validate(contentType: ["application/json"]) .responseJSON { response in withExtendedLifetime(self.alamofire) { if let error = response.result.error { deferred.fill(Maybe(failure: FxAClientError.local(error as NSError))) return } if let data = response.result.value { let json = JSON(data) if let remoteError = FxAClient10.remoteError(fromJSON: json, statusCode: response.response!.statusCode) { deferred.fill(Maybe(failure: FxAClientError.remote(remoteError))) return } if let response = responseHandler(json) { deferred.fill(Maybe(success: response)) return } } deferred.fill(Maybe(failure: FxAClientError.local(FxAClientUnknownError))) } } return deferred } } extension FxAClient10: FxALoginClient { func keyPair() -> Deferred<Maybe<KeyPair>> { let result = RSAKeyPair.generate(withModulusSize: 2048)! // TODO: debate key size and extract this constant. return Deferred(value: Maybe(success: result)) } open func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let URL = self.authURL.appendingPathComponent("/account/keys") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("keyFetchToken") let key = (keyFetchToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) let rangeStart = 2 * KeyLength let keyRequestKey = key.subdata(in: rangeStart..<(rangeStart + KeyLength)) return makeRequest(mutableURLRequest) { FxAClient10.keysResponse(fromJSON: keyRequestKey, json: $0) } } open func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let parameters = [ "publicKey": publicKey.jsonRepresentation() as NSDictionary, "duration": NSNumber(value: OneDayInMilliseconds), // The maximum the server will allow. ] let url = self.authURL.appendingPathComponent("/certificate/sign") var mutableURLRequest = URLRequest(url: url) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = (sessionToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.signResponse) } }
mpl-2.0
9a92321910ee7820367a873756a13d30
40.886121
179
0.646517
4.995756
false
false
false
false
vmachiel/swift
ObserversExample/ObserversExample/BaseScreen.swift
1
5082
// // ViewController.swift // DelegatesExample // // Created by Machiel van Dorst on 28-08-17. // Copyright © 2017 vmachiel. All rights reserved. // import UIKit // THIS IS THE OBSERVER, Which can listen to many different notification senders. // The keys for the different notification. The observer (Base) can react to each differently. // You declare these globally. Normally, create a constants file to declare global variables. This ex. is simple // They have to be unique, use your bundleID to achieve that (not necessary, good practice though) let lightNotificationKey = "com.vmachiel.lightSide" let darkNotificationKey = "com.vmachiel.darkSide" // Note that it's best practice to remove observers when they are no longer necessary. Do this in this case // when the BaseScreen is de-allocated. class BaseScreen: UIViewController { @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var chooseButton: UIButton! @IBOutlet weak var nameLabel: UILabel! // Create variables to reference each notification object. You also set these in the SelectionScreen to // be sent let light = Notification.Name(rawValue: lightNotificationKey) let dark = Notification.Name(rawValue: darkNotificationKey) // Remove the observer when the screen is deinited. This is best practice, otherwise you'll have // obserers all over the place in big projects, listening when it's not necessary. deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() chooseButton.layer.cornerRadius = chooseButton.frame.size.height / 2 // round corners createObservers() } // Create the observers in seperate function. This method sets them up, and is called from viewDidLoad() // Some are redundant, but their purpose here is to demo Observers func createObservers() { // light side observers // So add observers. So the init with 4 arguments: 1: what is the observer? In this case, this view is // so self. This is the object "registering as an observer" // 2: selector: what method is called when the notification is received. // 3: name: what obsever to respond to. This name is send from the SelectionScreen. // 4: What object to pass to the selector, nil in this case. // #selector is an obje style selector that selects another method to use. Read more about that. // I THINK: you simply select a method to use and // you pass it nothing, the name is passed via 3rd parameter.. it looks like. // So now you have three observers setup that listen for a notification to be posted with the name // com.vmachiel.lightSide (defined globally). And three for dark side. Each triggers a method that is // selected by the #selector, and passes the name or the posted notification, and passes no object (nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateCharacterImage(notification:)), name: light, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateNameLabel(notification:)), name: light, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateBackground(notification:)), name: light, object: nil) //Dark side observers. NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateCharacterImage(notification:)), name: dark, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateNameLabel(notification:)), name: dark, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateBackground(notification:)), name: dark, object: nil) } // The methods that get called when the observer (self) gets the messages (notifications) // Each one checks if the name is light, and sets the image/name/background to light side, OR dark // and sets everything func updateCharacterImage(notification: NSNotification) { let isLight = notification.name == light let image = isLight ? UIImage(named: "luke")! : UIImage(named: "vader")! mainImageView.image = image } func updateNameLabel(notification: NSNotification) { let isLight = notification.name == light let name = isLight ? "Luke Skywalker" : "Darth Vader" nameLabel.text = name } func updateBackground(notification: NSNotification) { let isLight = notification.name == light let color = isLight ? UIColor.cyan : UIColor.red view.backgroundColor = color } @IBAction func chooseButton(_ sender: UIButton) { let selectionVC = storyboard?.instantiateViewController(withIdentifier: "SelectionScreen") as! SelectionScreen present(selectionVC, animated: true, completion: nil) } }
mit
f7e0eddd5f7d29c3560703c14c4c4436
39.325397
147
0.701634
4.748598
false
false
false
false
Cleverdesk/cleverdesk-ios
Cleverdesk/User.swift
1
717
// // User.swift // Cleverdesk // // Created by Jonas Franz on 21.06.16. // Copyright © 2016 Cleverdesk. All rights reserved. // import Foundation import CoreData import KeychainSwift class User: NSManagedObject { let keychain = KeychainSwift() // Insert code here to add functionality to your managed object subclass var token: String? { get { if username == nil { return nil } return keychain.get(username!) } set(value) { if value == nil { return } keychain.set(value!, forKey: username!, withAccess: .AccessibleWhenUnlocked) } } }
gpl-3.0
08c4a289edb526ea643be41a8d2f2e11
18.351351
88
0.547486
4.649351
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionTreasury/PushTransition/TRNavgationTransitionDelegate.swift
1
5094
// // TRNavgationTransitionDelegate.swift // TransitionTreasury // // Created by DianQK on 12/20/15. // Copyright © 2016 TransitionTreasury. All rights reserved. // import UIKit /// Transition(Push & Pop) Animation Delegate Object public class TRNavgationTransitionDelegate: NSObject, UINavigationControllerDelegate { /// The transition animation object public var transition: TRViewControllerAnimatedTransitioning public var previousStatusBarStyle: TRStatusBarStyle? public var currentStatusBarStyle: TRStatusBarStyle? private var p_completion: (() -> Void)? /// Transition completion block var completion: (() -> Void)? { get { return self.transition.completion ?? p_completion } set { self.transition.completion = newValue if self.transition.completion == nil { p_completion = newValue } } } /// The edge gesture for pop lazy var edgePanGestureRecognizer: UIScreenEdgePanGestureRecognizer = { let edgePanGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(TRNavgationTransitionDelegate.tr_edgePan(_:))) edgePanGestureRecognizer.edges = .left return edgePanGestureRecognizer }() /** Init method - parameter method: the push method - parameter status: default is .Push - parameter viewController: for edge gesture - returns: Transition Animation Delegate Object */ public init(method: TransitionAnimationable, status: TransitionStatus = .push, gestureFor viewController: UIViewController?) { transition = method.transitionAnimation() super.init() if let transition = transition as? TransitionInteractiveable , transition.edgeSlidePop { viewController?.view.addGestureRecognizer(edgePanGestureRecognizer) } } public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .push : transition.transitionStatus = .push return transition case .pop : transition.transitionStatus = .pop return transition case .none : return nil } } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { guard let transition = transition as? TransitionInteractiveable else { return nil } return transition.interacting ? transition.percentTransition : nil } public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { switch transition.transitionStatus { case .push : currentStatusBarStyle?.updateStatusBarStyle() case .pop : previousStatusBarStyle?.updateStatusBarStyle() default : fatalError("No this transition status here.") } } public func tr_edgePan(_ recognizer: UIPanGestureRecognizer) { let fromVC = transition.transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from) let toVC = transition.transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.to) guard var transition = transition as? TransitionInteractiveable else { return } guard let view = fromVC?.view else { return } var percent = recognizer.translation(in: view).x / view.bounds.size.width percent = min(1.0, max(0, percent)) switch recognizer.state { case .began : transition.interacting = true transition.percentTransition = UIPercentDrivenInteractiveTransition() transition.percentTransition?.startInteractiveTransition((transition as! TRViewControllerAnimatedTransitioning).transitionContext!) toVC!.navigationController!.tr_popViewController() case .changed : transition.percentTransition?.update(percent) default : transition.interacting = false if percent > transition.interactivePrecent { transition.cancelPop = false transition.percentTransition?.completionSpeed = 1.0 - transition.percentTransition!.percentComplete transition.percentTransition?.finish() fromVC?.view.removeGestureRecognizer(edgePanGestureRecognizer) } else { transition.cancelPop = true transition.percentTransition?.cancel() } transition.percentTransition = nil } } }
mit
17a74f52b8ef87326995680287718146
39.102362
253
0.666209
6.303218
false
false
false
false
CoderSLZeng/SLWeiBo
SLWeiBo/SLWeiBo/Classes/Home/View/VisitorView.swift
1
2639
// // VisitorView.swift // SLWeiBo // // Created by Anthony on 17/3/7. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit class VisitorView: UIView { //========================================================================================================== // MARK: - 控件的属性 //========================================================================================================== /// 转盘 @IBOutlet weak var rotationView: UIImageView! /// 图标 @IBOutlet weak var iconView: UIImageView! /// 提示标签栏 @IBOutlet weak var tipLabel: UILabel! /// 注册按钮 @IBOutlet weak var registerBtn: UIButton! /// 登录按钮 @IBOutlet weak var loginBtn: UIButton! /** 提供快速通过xib创建的类方法 */ class func visitorView() -> VisitorView { return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)!.first as! VisitorView } } //========================================================================================================== // MARK: - 自定义函数 //========================================================================================================== extension VisitorView { /** 设置访客视图上的数据 - parameter iconName: 需要显示的图标 - parameter title: 需要显示提示标签栏 */ func setupVisitorViewInfo(_ iconName : String?, title : String) { // 1.设置标题 tipLabel.text = title // 2.判断是否是首页 guard let name = iconName else { // 没有设置图标, 首页 // 执行转盘动画 addRotationAnimation() return } // 3.设置其他数据 // 不是首页 rotationView.isHidden = true iconView.image = UIImage(named: name) } fileprivate func addRotationAnimation() { // 1.创建动画 let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") // 2.设置动画的属性 rotationAnim.fromValue = 0 rotationAnim.toValue = M_PI * 2 rotationAnim.repeatCount = MAXFLOAT rotationAnim.duration = 5 // 注意: 默认情况下只要视图消失, 系统就会自动移除动画 // 只要设置removedOnCompletion为false, 系统就不会移除动画 rotationAnim.isRemovedOnCompletion = false // 3.将动画添加到layer中 rotationView.layer.add(rotationAnim, forKey: nil) } }
mit
5842cf75b94942b8fafad10a11b335cd
26.046512
112
0.462597
5.191964
false
false
false
false
salutis/TextView-Padding
TextView+Padding.swift
1
1846
// The MIT License (MIT) // // Copyright (c) 2015 Rudolf Adamkovič // // 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 // TODO: Optional CGFloat @IBInspectable is not supported yet let UITextViewPaddingUndefined: CGFloat = -1 extension UITextView { @IBInspectable var padding: CGFloat { set { precondition(newValue != UITextViewPaddingUndefined) textContainerInset = UIEdgeInsets(top: newValue, left: newValue, bottom: newValue, right: newValue) } get { let insets: Set = [textContainerInset.top, textContainerInset.left, textContainerInset.bottom, textContainerInset.right] guard let padding = insets.first where insets.count == 1 else { return UITextViewPaddingUndefined } return padding } } }
mit
3c95ff3ad929916e978058eb61f86970
42.928571
132
0.727913
4.804688
false
false
false
false
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/connect/ConnectService.swift
1
9081
// // ConnectService.swift // Emby.ApiClient // // Created by Vedran Ozir on 07/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.apiinteraction.connect; // //import mediabrowser.apiinteraction.EmptyResponse; //import mediabrowser.apiinteraction.QueryStringDictionary; //import mediabrowser.apiinteraction.Response; //import mediabrowser.apiinteraction.SerializedResponse; //import mediabrowser.apiinteraction.cryptography.Md5; //import mediabrowser.apiinteraction.http.HttpRequest; //import mediabrowser.apiinteraction.http.IAsyncHttpClient; //import mediabrowser.model.connect.*; //import mediabrowser.model.logging.ILogger; //import mediabrowser.model.registration.RegistrationInfo; //import mediabrowser.model.serialization.IJsonSerializer; // //import java.io.UnsupportedEncodingException; //import java.security.NoSuchAlgorithmException; enum Error:ErrorType { case IllegalArgumentException(String) case LowBridge } class Md5 { static func getHash(from: String) -> String! { let str = from.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(from.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String( hash) } } public class ConnectService { public let JsonSerializer: IJsonSerializer let logger: ILogger let httpClient: IAsyncHttpClient private let appName: String private let appVersion: String public init(jsonSerializer: IJsonSerializer, logger: ILogger, httpClient: IAsyncHttpClient, appName: String, appVersion: String) { self.JsonSerializer = jsonSerializer; self.logger = logger; self.httpClient = httpClient; self.appName = appName; self.appVersion = appVersion; } public func Authenticate<T:ConnectAuthenticationResult>(username: String, password: String, /*final*/ response: EmbyApiClient.Response<T>) { // UnsupportedEncodingException, NoSuchAlgorithmException { let args = QueryStringDictionary() args.Add("nameOrEmail", value: username); args.Add("password", value: Md5.getHash(ConnectPassword.PerformPreHashFilter(password))); let url = GetConnectUrl("user/authenticate"); let request = HttpRequest(); request.setMethod("POST"); request.setUrl(url); request.setPostData(args); AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: ConnectAuthenticationResult.self)); } public func CreatePin<T:PinCreationResult>(deviceId: String, final response: EmbyApiClient.Response<T>) { let args = QueryStringDictionary() args.Add("deviceId", value: deviceId); let url = GetConnectUrl("pin") + "?" + args.GetQueryString(); let request = HttpRequest(); request.setMethod("POST"); request.setUrl(url); request.setPostData(args); AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: PinCreationResult.self)); } public func GetPinStatus<T:PinStatusResult>(pin: PinCreationResult, final response: EmbyApiClient.Response<T>) { let dict = QueryStringDictionary(); dict.Add("deviceId", value: pin.getDeviceId()); dict.Add("pin", value: pin.getPin()); let url = GetConnectUrl("pin") + "?" + dict.GetQueryString(); let request = HttpRequest() request.setMethod("GET"); request.setUrl(url); AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: PinStatusResult.self)); } public func ExchangePin<T:PinExchangeResult>(pin: PinCreationResult, final response: EmbyApiClient.Response<T>) { let args = QueryStringDictionary(); args.Add("deviceId", value: pin.getDeviceId()); args.Add("pin", value: pin.getPin()); let url = GetConnectUrl("pin/authenticate"); let request = HttpRequest() request.setMethod("POST"); request.setUrl(url); request.setPostData(args); AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: PinExchangeResult.self)); } public func GetConnectUser<T:ConnectUser>(query: ConnectUserQuery, connectAccessToken: String?, final response: EmbyApiClient.Response<T>) throws { let dict = QueryStringDictionary(); if let id = query.getId() { dict.Add("id", value: id); } else if let name = query.getName() { dict.Add("name", value: name); } else if let email = query.getEmail() { dict.Add("email", value: email); } else if let nameOrEmail = query.getNameOrEmail() { dict.Add("nameOrEmail", value: nameOrEmail); } else { throw Error.IllegalArgumentException("Empty ConnectUserQuery") } let url = GetConnectUrl("user") + "?" + dict.GetQueryString(); let request = HttpRequest() request.setMethod("GET"); request.setUrl(url); try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: ConnectUser.self)); } public func GetServers<T:ConnectUserServers>(userId: String, connectAccessToken: String, final response: EmbyApiClient.Response<T>) throws { let dict = QueryStringDictionary(); dict.Add("userId", value: userId) let url = GetConnectUrl("servers") + "?" + dict.GetQueryString(); let request = HttpRequest() request.setMethod("GET"); request.setUrl(url); try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: ConnectUserServers.self)); } public func Logout<T:EmptyResponse>(connectAccessToken: String, final response: EmbyApiClient.Response<T>) throws { let url = GetConnectUrl("user/logout"); let request = HttpRequest() request.setMethod("POST"); request.setUrl(url); try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: EmptyResponse.self)); } private func GetConnectUrl(handler: String) -> String { return Configuration.mediaBrowserTV_APIServer + handler; } private func AddUserAccessToken(request: HttpRequest, accessToken: String?) throws { if let accessToken = accessToken { request.getRequestHeaders()?.put("X-Connect-UserToken", value: accessToken); } else { throw Error.IllegalArgumentException("accessToken") } } private func AddXApplicationName(request: HttpRequest) { request.getRequestHeaders()?.put("X-Application", value: appName + "/" + appVersion); } public func GetRegistrationInfo<T:RegistrationInfo>(userId: String, feature: String, connectAccessToken: String, final response: EmbyApiClient.Response<T>) throws { let dict = QueryStringDictionary(); dict.Add("userId", value: userId) dict.Add("feature", value: feature); let url = GetConnectUrl("registrationInfo") + "?" + dict.GetQueryString(); let request = HttpRequest() request.setMethod("GET"); request.setUrl(url); try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request); httpClient.Send(request, response: SerializedResponse<T>(innerResponse: response, jsonSerializer: JsonSerializer, type: RegistrationInfo.self)); } }
mit
8bcacca3c1115ab6c7bc08c734a474e2
34.33463
166
0.647687
4.879097
false
false
false
false
finngaida/spotify2applemusic
Pods/Sweeft/Sources/Sweeft/Networking/Auth.swift
1
1024
// // Auth.swift // Pods // // Created by Mathias Quintero on 12/29/16. // // import Foundation /// Authentication protocol public protocol Auth { func apply(to request: inout URLRequest) } /// Object that doesn't do anything to authenticate the user public struct NoAuth: Auth { /// Shared instance public static let standard = NoAuth() public func apply(to request: inout URLRequest) { // Do Nothing } } /// Basic Http Auth public struct BasicAuth { fileprivate let username: String fileprivate let password: String public init(username: String, password: String) { self.username = username self.password = password } } extension BasicAuth: Auth { /// Adds authorization header public func apply(to request: inout URLRequest) { let string = ("\(username):\(password)".base64Encoded).? let auth = "Basic \(string)" request.addValue(auth, forHTTPHeaderField: "Authorization") } }
mit
f8ab6e7494a55e0fa487ac497d6261b4
19.48
67
0.636719
4.491228
false
false
false
false
hsavit1/LeetCode-Solutions-in-Swift
Solutions/Solutions/Easy/Easy_008_String_to_Integer_atoi.swift
1
2990
/* https://oj.leetcode.com/problems/string-to-integer-atoi/ #8 String to Integer (atoi) Level: easy Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. Inspired by @yuruofeifei at https://oj.leetcode.com/discuss/8886/my-simple-solution */ // Helper private extension String { subscript (index: Int) -> Character { return self[advance(self.startIndex, index)] } } class Easy_008_String_to_Integer_atoi { // O (N) class func atoi(str: String) -> Int { var sign: Bool = true, len: Int = str.characters.count, base: Int = 0 for j in 0..<len { let zeroString: String = String("0") let zeroValue: Int = Int(zeroString.utf8[zeroString.utf8.startIndex]) if base == 0 && str[j] == " " || str[j] == "+" { continue } else if base == 0 && str[j] == "-" { sign = false continue } else { let integerValue: Int = Int(str.utf8[advance(str.utf8.startIndex, j)]) - zeroValue if integerValue >= 0 && integerValue <= 9 { if base > Int.max/10 || (base == Int.max/10 && integerValue > 7) { if sign { return Int.max } else { return Int.min } } base = integerValue + 10 * base } } } if sign { return base } else { return 0 - base } } }
mit
e518cf7b5697b3fc0bdd5c0bd94ee042
41.728571
294
0.628763
4.390602
false
false
false
false
CharlinFeng/PhotoBrowser
PhotoBrowser/PhotoBrowser/View/ItemCell.swift
1
12645
// // ItemCell.swift // PhotoBrowser // // Created by 成林 on 15/7/29. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class ItemCell: UICollectionViewCell { var photoModel: PhotoBrowser.PhotoModel!{didSet{dataFill()}} var photoType: PhotoBrowser.PhotoType! var isHiddenBar: Bool = true{didSet{toggleDisplayBottomBar(isHiddenBar)}} weak var vc: UIViewController! /** 缓存 */ var cache: Cache<UIImage>! /** format */ var format: Format<UIImage>! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageV: ShowImageView! @IBOutlet weak var bottomContentView: UIView! @IBOutlet weak var msgTitleLabel: UILabel! @IBOutlet weak var msgContentTextView: UITextView! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var imgVHC: NSLayoutConstraint! @IBOutlet weak var imgVWC: NSLayoutConstraint! @IBOutlet weak var imgVTMC: NSLayoutConstraint! @IBOutlet weak var imgVLMC: NSLayoutConstraint! // @IBOutlet weak var layoutView: UIView! @IBOutlet weak var asHUD: NVActivityIndicatorView! var hasHDImage: Bool = false var isFix: Bool = false var isDeinit: Bool = false var isAlive: Bool = true fileprivate var doubleTapGesture: UITapGestureRecognizer! fileprivate var singleTapGesture: UITapGestureRecognizer! lazy var screenH: CGFloat = UIScreen.main.bounds.size.height lazy var screenW: CGFloat = UIScreen.main.bounds.size.width deinit{ cache = nil self.asHUD?.removeFromSuperview() NotificationCenter.default.removeObserver(self) } } extension ItemCell: UIScrollViewDelegate{ override func awakeFromNib() { super.awakeFromNib() doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ItemCell.doubleTap(_:))) doubleTapGesture.numberOfTapsRequired = 2 doubleTapGesture.numberOfTouchesRequired = 1 singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ItemCell.singleTap(_:))) singleTapGesture.require(toFail: self.doubleTapGesture) singleTapGesture.numberOfTapsRequired = 1 singleTapGesture.numberOfTouchesRequired = 1 addGestureRecognizer(doubleTapGesture) addGestureRecognizer(singleTapGesture) scrollView.delegate = self msgContentTextView.textContainerInset = UIEdgeInsets.zero NotificationCenter.default.addObserver(self, selector: #selector(ItemCell.didRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) //HUD初始化 asHUD.layer.cornerRadius = 40 // scrollView.layer.borderColor = UIColor.redColor().CGColor // scrollView.layer.borderWidth = 5 asHUD.type = NVActivityIndicatorType.ballTrianglePath //更新约束:默认居中 self.imgVLMC.constant = (self.screenW - 120)/2 self.imgVTMC.constant = (self.screenH - 120)/2 } override func layoutSubviews() { super.layoutSubviews() } func didRotate(){ DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {[unowned self] () -> Void in if self.imageV.image != nil {self.imageIsLoaded(self.imageV.image!, needAnim: false)} }) } func doubleTap(_ tapG: UITapGestureRecognizer){ if !hasHDImage {return} let location = tapG.location(in: tapG.view) if scrollView.zoomScale <= 1 { if !(imageV.convert(imageV.bounds, to: imageV.superview).contains(location)) {return} let location = tapG.location(in: tapG.view) let rect = CGRect(x: location.x, y: location.y, width: 10, height: 10) UIView.animate(withDuration: 0.3, animations: { () -> Void in UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!) self.scrollView.zoom(to: rect, animated: false) var c = (self.screenH - self.imageV.frame.height) / 2 if c <= 0 {c = 0} self.imgVTMC.constant = c print(self.imgVTMC.constant) self.imageV.setNeedsLayout() self.imageV.layoutIfNeeded() }) }else{ UIView.animate(withDuration: 0.3, animations: { () -> Void in UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!) self.scrollView.setZoomScale(1, animated: false) self.imgVTMC.constant = (self.screenH - self.imageV.showSize.height) / 2 self.imageV.setNeedsLayout() self.imageV.layoutIfNeeded() }) } } func singleTap(_ tapG: UITapGestureRecognizer){ if scrollView.zoomScale > 1 { doubleTap(doubleTapGesture) }else { NotificationCenter.default.post(name: Notification.Name(rawValue: CFPBSingleTapNofi), object: nil) } } func viewForZooming(in scrollView: UIScrollView) -> UIView? {return imageV} func scrollViewDidZoom(_ scrollView: UIScrollView) { // UIView.animateWithDuration(0.3, animations: { () -> Void in // UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!) var c = (self.screenH - self.imageV.frame.height) / 2 if c <= 0 {c = 0} self.imgVTMC.constant = c // print(self.imgVTMC.constant) // self.imageV.setNeedsLayout() // self.imageV.layoutIfNeeded() // }) } /** 复位 */ func reset(){ scrollView.setZoomScale(1, animated: false) msgContentTextView.setContentOffset(CGPoint.zero, animated: false) } /** 数据填充 */ func dataFill(){ if photoType == PhotoBrowser.PhotoType.local { /** 本地图片模式 */ hasHDImage = true /** 图片 */ imageV.image = photoModel.localImg /** 图片数据已经装载 */ imageIsLoaded(photoModel.localImg, needAnim: false) }else{ self.hasHDImage = false self.imgVHC.constant = CFPBThumbNailWH self.imgVWC.constant = CFPBThumbNailWH self.imageV.image = nil /** 服务器图片模式 */ let url = URL(string: photoModel.hostHDImgURL)! if cache == nil {cache = Cache<UIImage>(name: CFPBCacheKey)} if format == nil{format = Format(name: photoModel.hostHDImgURL, diskCapacity: 10 * 1024 * 1024, transform: { img in return img })} cache.fetch(key: photoModel.hostHDImgURL, failure: {[unowned self] fail in if !self.isAlive {return} self.showAsHUD() DispatchQueue.main.async(execute: { () -> Void in //更新约束:默认居中 self.imgVLMC.constant = (self.screenW - 120)/2 self.imgVTMC.constant = (self.screenH - 120)/2 }) self.imageV.image = self.photoModel.hostThumbnailImg self.cache.fetch(URL: URL(string: self.photoModel.hostHDImgURL)!, failure: {fail in print("失败\(fail)") }, success: {[unowned self] img in if !UserDefaults.standard.bool(forKey: CFPBShowKey) {return} if !self.isAlive {return} if self.photoModel?.excetionFlag == false {return} if self.photoModel.modelCell !== self {return} self.hasHDImage = true self.dismissAsHUD(true) self.imageIsLoaded(img, needAnim: true) self.imageV.image = img }) }, success: {[unowned self] img in if !self.isAlive {return} self.dismissAsHUD(false) self.imageV.image = img self.hasHDImage = true /** 图片数据已经装载 */ if !self.isFix && self.vc.view.bounds.size.width > self.vc.view.bounds.size.height{ DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.06 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {[unowned self] () -> Void in self.imageIsLoaded(img, needAnim: false) self.isFix = true }) }else{ self.imageIsLoaded(img, needAnim: false) } }) } /** 标题 */ if photoModel.titleStr != nil {msgTitleLabel.text = photoModel.titleStr} /** 内容 */ if photoModel.descStr != nil {msgContentTextView.text = photoModel.descStr} DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {[unowned self] () -> Void in self.reset() } } func toggleDisplayBottomBar(_ isHidden: Bool){ bottomContentView.isHidden = isHidden } /** 图片数据已经装载 */ func imageIsLoaded(_ img: UIImage,needAnim: Bool){ self.scrollView.setZoomScale(1, animated: true) if !hasHDImage {return} if vc == nil{return} //图片尺寸 let imgSize = img.size var boundsSize = self.bounds.size //这里有一个奇怪的bug,横屏时,bounds居然是竖屏的bounds if vc.view.bounds.size.width > vc.view.bounds.size.height { if boundsSize.width < boundsSize.height { boundsSize = CGSize(width: boundsSize.height, height: boundsSize.width) } } let contentSize = boundsSize.sizeMinusExtraWidth let showSize = CGSize.decisionShowSize(imgSize, contentSize: contentSize) imageV.showSize = showSize DispatchQueue.main.async(execute: {[unowned self] () -> Void in self.imgVHC.constant = showSize.height self.imgVWC.constant = showSize.width self.imgVLMC.constant = 0 self.imgVTMC.constant = (self.screenH - showSize.height) / 2 if self.photoModel.isLocal! {return} if !needAnim{return} self.scrollView.contentSize = showSize UIView.animate(withDuration: 0.25, animations: {[unowned self] () -> Void in UIView.setAnimationCurve(UIViewAnimationCurve.easeOut) self.imageV.setNeedsLayout() self.imageV.layoutIfNeeded() }) }) } /** 展示进度HUD */ func showAsHUD(){ if asHUD == nil {return} self.asHUD?.isHidden = false asHUD?.startAnimating() UIView.animate(withDuration: 0.25, animations: {[unowned self] () -> Void in self.asHUD?.alpha = 1 }) } /** 移除 */ func dismissAsHUD(_ needAnim: Bool){ if asHUD == nil {return} if needAnim{ UIView.animate(withDuration: 0.25, animations: {[unowned self] () -> Void in self.asHUD?.alpha = 0 }, completion: { (complete) -> Void in self.asHUD?.isHidden = true self.asHUD?.stopAnimating() }) }else{ self.asHUD?.alpha = 0 self.asHUD?.isHidden = true self.asHUD?.stopAnimating() } } }
mit
de47848615ebd499fb232c99cf9699a4
30.233668
186
0.538573
4.884479
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Home/RecentlyClosedTabsPanel.swift
2
7410
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import XCGLogger import Deferred private let log = Logger.browserLogger private struct RecentlyClosedPanelUX { static let IconSize = CGSize(width: 23, height: 23) static let IconBorderColor = UIColor.Photon.Grey30 static let IconBorderWidth: CGFloat = 0.5 } class RecentlyClosedTabsPanel: UIViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? let profile: Profile fileprivate lazy var recentlyClosedHeader: UILabel = { let headerLabel = UILabel() headerLabel.text = Strings.RecentlyClosedTabsPanelTitle headerLabel.textColor = UIColor.theme.tableView.headerTextDark headerLabel.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel headerLabel.textAlignment = .center headerLabel.backgroundColor = UIColor.theme.tableView.headerBackground return headerLabel }() fileprivate lazy var tableViewController = RecentlyClosedTabsPanelSiteTableViewController(profile: profile) fileprivate lazy var historyBackButton: HistoryBackButton = { let button = HistoryBackButton() button.addTarget(self, action: #selector(RecentlyClosedTabsPanel.historyBackButtonWasTapped), for: .touchUpInside) return button }() init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.theme.tableView.headerBackground tableViewController.homePanelDelegate = homePanelDelegate tableViewController.recentlyClosedTabsPanel = self self.addChildViewController(tableViewController) self.view.addSubview(tableViewController.view) self.view.addSubview(historyBackButton) self.view.addSubview(recentlyClosedHeader) historyBackButton.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(50) make.bottom.equalTo(recentlyClosedHeader.snp.top) } recentlyClosedHeader.snp.makeConstraints { make in make.top.equalTo(historyBackButton.snp.bottom) make.height.equalTo(20) make.bottom.equalTo(tableViewController.view.snp.top).offset(-10) make.left.right.equalTo(self.view) } tableViewController.view.snp.makeConstraints { make in make.left.right.bottom.equalTo(self.view) } tableViewController.didMove(toParentViewController: self) } @objc fileprivate func historyBackButtonWasTapped(_ gestureRecognizer: UITapGestureRecognizer) { _ = self.navigationController?.popViewController(animated: true) } } class RecentlyClosedTabsPanelSiteTableViewController: SiteTableViewController { weak var homePanelDelegate: HomePanelDelegate? var recentlyClosedTabs: [ClosedTab] = [] weak var recentlyClosedTabsPanel: RecentlyClosedTabsPanel? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(RecentlyClosedTabsPanelSiteTableViewController.longPress)) }() override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "Recently Closed Tabs List" self.recentlyClosedTabs = profile.recentlyClosedTabs.tabs } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) guard let twoLineCell = cell as? TwoLineTableViewCell else { return cell } let tab = recentlyClosedTabs[indexPath.row] let displayURL = tab.url.displayURL ?? tab.url twoLineCell.setLines(tab.title, detailText: displayURL.absoluteDisplayString) let site: Favicon? = (tab.faviconURL != nil) ? Favicon(url: tab.faviconURL!) : nil cell.imageView!.layer.borderColor = RecentlyClosedPanelUX.IconBorderColor.cgColor cell.imageView!.layer.borderWidth = RecentlyClosedPanelUX.IconBorderWidth cell.imageView?.setIcon(site, forURL: displayURL, completed: { (color, url) in if url == displayURL { cell.imageView?.image = cell.imageView?.image?.createScaled(RecentlyClosedPanelUX.IconSize) cell.imageView?.contentMode = .center cell.imageView?.backgroundColor = color } }) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let homePanelDelegate = homePanelDelegate, let recentlyClosedTabsPanel = recentlyClosedTabsPanel else { log.warning("No site or no URL when selecting row.") return } let visitType = VisitType.typed // Means History, too. homePanelDelegate.homePanel(recentlyClosedTabsPanel, didSelectURL: recentlyClosedTabs[indexPath.row].url, visitType: visitType) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } // Functions that deal with showing header rows. func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return profile.recentlyClosedTabs.tabs.count } } extension RecentlyClosedTabsPanelSiteTableViewController: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { let closedTab = recentlyClosedTabs[indexPath.row] let site: Site if let title = closedTab.title { site = Site(url: String(describing: closedTab.url), title: title) } else { site = Site(url: String(describing: closedTab.url), title: "") } return site } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { return getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) } } extension RecentlyClosedTabsPanel: Themeable { func applyTheme() { historyBackButton.applyTheme() tableViewController.tableView.reloadData() } }
mpl-2.0
8cab4d0cf229f5f19e00ce9a12e44413
38.83871
135
0.706343
5.319454
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/SwiftDemo/UserCenter/Cell/JWUserIntegralTableViewCell.swift
1
1441
// // JWUserIntegralTableViewCell.swift // SwiftDemo // // Created by apple on 2017/11/9. // Copyright © 2017年 UgoMedia. All rights reserved. // import UIKit class JWUserIntegralTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addIntegralLabel: UILabel! @IBOutlet weak var introduceLabel: UILabel! @IBOutlet weak var bottomLineView: UIView! var model:JWUserIntegralModel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // 首栏样式 func setTopStyle() { self.nameLabel.font = JWFontAdaptor.adjustFont(fixFontSize: 14.0) self.addIntegralLabel.font = JWFontAdaptor.adjustFont(fixFontSize: 14.0) self.introduceLabel.font = JWFontAdaptor.adjustFont(fixFontSize: 14.0) self.contentView.backgroundColor = JWTools.colorWithHexString(hex: "#f7edeb") self.bottomLineView.isHidden = true } func setData(dataModel:JWUserIntegralModel) { self.model = dataModel self.nameLabel.text = self.model.typeName self.addIntegralLabel.text = self.model.addIntegral self.introduceLabel.text = self.model.introduce } }
apache-2.0
e62fa66491e7286d2923fc4d2933bb69
27.6
85
0.679021
4.41358
false
false
false
false
mono0926/nlp100-swift
Carthage/Checkouts/SwiftyStringExtension/Sources/String.extension.swift
1
2407
// // String.extension.swift // nlp100-swift // // Created by mono on 2016/10/01. // // import Foundation // Enable collection operation extension String: BidirectionalCollection, RangeReplaceableCollection {} extension String { // MARK: - Subscript public subscript(sequentialAccess range: Range<Int>) -> String { return String(characters[sequentialAccess: range]) } public subscript(sequentialAccess index: Int) -> String { return self[sequentialAccess: index..<index + 1] } // MARK: - Other public var asciiCode: UInt32? { if unicodeScalars.index(after: unicodeScalars.startIndex) != unicodeScalars.endIndex { return nil } return characters.first?.asciiCode } // MARK: - Bug? public mutating func removeFirst(_ n: Int) { characters.removeFirst(n) } public mutating func removeLast(_ n: Int) { characters.removeLast(n) } // MARK: - Range public func makeNSRange(from range: Range<String.Index>) -> NSRange { let from = range.lowerBound.samePosition(in: utf16) let to = range.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to)) } public func makeRange(from range: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } // MARK: - Convenient public mutating func replace(of target: String, with replacement: String) { self = replacingOccurrences(of: target, with: replacement) } public func addingUrlEncoding() -> String { return addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! } public func getValueOrNil() -> String? { if String.isEmpty(self) { return nil } return self } public static func isEmpty(_ s: String?) -> Bool { if let s = s { return s.isEmpty } return true } }
mit
0b35e6c12cb05bc592a97be067f5e286
30.25974
108
0.618197
4.376364
false
false
false
false
anbo0123/ios5-weibo
microblog/microblog/Classes/Module/Main/Controller/ABMainTabBarController.swift
1
4249
// // ABMainTabBarController.swift // microblog // // Created by 安波 on 15/10/26. // Copyright © 2015年 anbo. All rights reserved. // import UIKit class ABMainTabBarController: UITabBarController { /// 撰写按钮的监听方法 func composeButtonClick(){ // 打印该方法 print(__FUNCTION__) } override func viewDidLoad() { super.viewDidLoad() // // 创建一个自定义的tabBar // let newTabBar = ABMainTabBar() // // 撰写按钮的监听 // newTabBar.composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside) // // 使用KVC设置值 // setValue(newTabBar, forKey: "tabBar") // 设置全局选中颜色 tabBar.tintColor = UIColor.orangeColor() //首页 let homeVc = ABHomeViewController() addChildViewController(homeVc, title: "首页", imageName: "tabbar_home") // homeVc.title = "首页" // homeVc.tabBarItem.image = UIImage(named: "tabbar_home") // addChildViewController(UINavigationController(rootViewController: homeVc)) //信息 let messageVc = ABMessageViewController() addChildViewController(messageVc, title: "信息", imageName: "tabbar_message_center") // messageVc.title = "信息" // messageVc.tabBarItem.image = UIImage(named: "tabbar_message_center") // addChildViewController(UINavigationController(rootViewController: messageVc)) //中间控制 let addVc = UIViewController() // addChildViewController(addVc, title: "中间", imageName: "ff") addChildViewController(UINavigationController(rootViewController: addVc)) //发现 let discoverVc = ABDiscoverViewController() addChildViewController(discoverVc, title: "发现", imageName: "tabbar_discover") // discoverVc.title = "发现" // discoverVc.tabBarItem.image = UIImage(named: "tabbar_discover") // addChildViewController(UINavigationController(rootViewController: discoverVc)) //我 let profileVc = ABProfileViewController() addChildViewController(profileVc, title: "我", imageName: "tabbar_profile") // profileVc.title = "我" // profileVc.tabBarItem.image = UIImage(named: "tabbar_profile") // addChildViewController(UINavigationController(rootViewController: profileVc)) } /** 添加子控制器,包装成 Nav - parameter controller: 控制器 - parameter title: 标题 - parameter imageName: 图片名称 */ private func addChildViewController(controller: UIViewController, title: String, imageName: String) { controller.title = title controller.tabBarItem.image = UIImage(named: imageName) addChildViewController(UINavigationController(rootViewController: controller)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // 计算宽度 let width = tabBar.bounds.width / CGFloat(5) // 设置撰写按钮的frame composeButton.frame = CGRect(x: width * 2, y: 0, width: width, height: tabBar.bounds.height) // 添加撰写 tabBar.addSubview(composeButton) } // MARK: - 懒加载 /// 撰写按钮 lazy var composeButton: UIButton = { // 创建按钮 let button = UIButton() // 设置按钮图片 button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) // 设置按钮背景 button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) // 监听点击 button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside) return button }() }
apache-2.0
d8ace7e9fd8c8d45758efdc78b0da9b1
33.929825
128
0.641637
4.75179
false
false
false
false
Tedko/DeviceGuru
DeviceGuru.swift
1
11126
// // DeviceGuru.swift // // Created by Inder Kumar Rathore on 06/02/15. // Copyright (c) 2015. All rights reserved. // // Hardware string can be found @http://www.everymac.com // import Foundation import UIKit /// Enum for different iPhone/iPad devices public enum Hardware: NSInteger { case NOT_AVAILABLE case IPHONE_2G case IPHONE_3G case IPHONE_3GS case IPHONE_4 case IPHONE_4_CDMA case IPHONE_4S case IPHONE_5 case IPHONE_5_CDMA_GSM case IPHONE_5C case IPHONE_5C_CDMA_GSM case IPHONE_5S case IPHONE_5S_CDMA_GSM case IPHONE_6 case IPHONE_6_PLUS case IPHONE_6S case IPHONE_6S_PLUS case IPOD_TOUCH_1G case IPOD_TOUCH_2G case IPOD_TOUCH_3G case IPOD_TOUCH_4G case IPOD_TOUCH_5G case IPOD_TOUCH_6G case IPAD case IPAD_2 case IPAD_2_WIFI case IPAD_2_CDMA case IPAD_3 case IPAD_3G case IPAD_3_WIFI case IPAD_3_WIFI_CDMA case IPAD_4 case IPAD_4_WIFI case IPAD_4_GSM_CDMA case IPAD_MINI case IPAD_MINI_WIFI case IPAD_MINI_WIFI_CDMA case IPAD_MINI_RETINA_WIFI case IPAD_MINI_RETINA_WIFI_CDMA case IPAD_MINI_3_WIFI case IPAD_MINI_3_WIFI_CELLULAR case IPAD_MINI_3_WIFI_CELLULAR_CN case IPAD_MINI_4_WIFI case IPAD_MINI_4_WIFI_CELLULAR case IPAD_MINI_RETINA_WIFI_CELLULAR_CN case IPAD_AIR_WIFI case IPAD_AIR_WIFI_GSM case IPAD_AIR_WIFI_CDMA case IPAD_AIR_2_WIFI case IPAD_AIR_2_WIFI_CELLULAR case IPAD_PRO_WIFI case IPAD_PRO_WIFI_CELLULAR case SIMULATOR } public class DeviceGuru { /// This method retruns the hardware type /// /// /// - returns: raw `String` of device type /// class public func hardwareString() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var hw_machine = [CChar](count: Int(size), repeatedValue: 0) sysctl(&name, 2, &hw_machine, &size, &name, 0) let hardware: String = String.fromCString(hw_machine)! return hardware } private static func getDeviceList() -> [String: AnyObject]? { // get the bundle of the DeviceUtil if it's main bundle then it returns main bundle // if it's DeviceUtil.framework then it returns the DeviceUtil.framework bundle let deviceUtilTopBundle = NSBundle(forClass:DeviceGuru.self) if let url = deviceUtilTopBundle.URLForResource("DeviceGuru", withExtension: "bundle") { let deviceUtilBundle = NSBundle(URL: url) if let path = deviceUtilBundle?.pathForResource("DeviceList", ofType: "plist") { return NSDictionary(contentsOfFile: path) as? [String: AnyObject] } } else if let path = deviceUtilTopBundle.pathForResource("DeviceList", ofType: "plist") { // falling back to main bundle return NSDictionary(contentsOfFile: path) as? [String: AnyObject] } assertionFailure("DevicePlist.plist not found in the bundle.") return nil } /// This method returns the Hardware enum depending upon harware string /// /// /// - returns: `Hardware` type of the device /// class public func hardware() -> Hardware { let hardware = hardwareString() if (hardware == "iPhone1,1") { return Hardware.IPHONE_2G } if (hardware == "iPhone1,2") { return Hardware.IPHONE_3G } if (hardware == "iPhone2,1") { return Hardware.IPHONE_3GS } if (hardware == "iPhone3,1") { return Hardware.IPHONE_4 } if (hardware == "iPhone3,2") { return Hardware.IPHONE_4 } if (hardware == "iPhone3,3") { return Hardware.IPHONE_4_CDMA } if (hardware == "iPhone4,1") { return Hardware.IPHONE_4S } if (hardware == "iPhone5,1") { return Hardware.IPHONE_5 } if (hardware == "iPhone5,2") { return Hardware.IPHONE_5_CDMA_GSM } if (hardware == "iPhone5,3") { return Hardware.IPHONE_5C } if (hardware == "iPhone5,4") { return Hardware.IPHONE_5C_CDMA_GSM } if (hardware == "iPhone6,1") { return Hardware.IPHONE_5S } if (hardware == "iPhone6,2") { return Hardware.IPHONE_5S_CDMA_GSM } if (hardware == "iPhone7,1") { return Hardware.IPHONE_6_PLUS } if (hardware == "iPhone7,2") { return Hardware.IPHONE_6 } if (hardware == "iPhone8,2") { return Hardware.IPHONE_6S_PLUS } if (hardware == "iPhone8,1") { return Hardware.IPHONE_6S } if (hardware == "iPod1,1") { return Hardware.IPOD_TOUCH_1G } if (hardware == "iPod2,1") { return Hardware.IPOD_TOUCH_2G } if (hardware == "iPod3,1") { return Hardware.IPOD_TOUCH_3G } if (hardware == "iPod4,1") { return Hardware.IPOD_TOUCH_4G } if (hardware == "iPod5,1") { return Hardware.IPOD_TOUCH_5G } if (hardware == "iPad1,1") { return Hardware.IPAD } if (hardware == "iPad1,2") { return Hardware.IPAD_3G } if (hardware == "iPad2,1") { return Hardware.IPAD_2_WIFI } if (hardware == "iPad2,2") { return Hardware.IPAD_2 } if (hardware == "iPad2,3") { return Hardware.IPAD_2_CDMA } if (hardware == "iPad2,4") { return Hardware.IPAD_2 } if (hardware == "iPad2,5") { return Hardware.IPAD_MINI_WIFI } if (hardware == "iPad2,6") { return Hardware.IPAD_MINI } if (hardware == "iPad2,7") { return Hardware.IPAD_MINI_WIFI_CDMA } if (hardware == "iPad3,1") { return Hardware.IPAD_3_WIFI } if (hardware == "iPad3,2") { return Hardware.IPAD_3_WIFI_CDMA } if (hardware == "iPad3,3") { return Hardware.IPAD_3 } if (hardware == "iPad3,4") { return Hardware.IPAD_4_WIFI } if (hardware == "iPad3,5") { return Hardware.IPAD_4 } if (hardware == "iPad3,6") { return Hardware.IPAD_4_GSM_CDMA } if (hardware == "iPad4,1") { return Hardware.IPAD_AIR_WIFI } if (hardware == "iPad4,2") { return Hardware.IPAD_AIR_WIFI_GSM } if (hardware == "iPad4,3") { return Hardware.IPAD_AIR_WIFI_CDMA } if (hardware == "iPad4,4") { return Hardware.IPAD_MINI_RETINA_WIFI } if (hardware == "iPad4,5") { return Hardware.IPAD_MINI_RETINA_WIFI_CDMA } if (hardware == "iPad4,6") { return Hardware.IPAD_MINI_RETINA_WIFI_CELLULAR_CN } if (hardware == "iPad4,7") { return Hardware.IPAD_MINI_3_WIFI } if (hardware == "iPad4,8") { return Hardware.IPAD_MINI_3_WIFI_CELLULAR } if (hardware == "iPad5,3") { return Hardware.IPAD_AIR_2_WIFI } if (hardware == "iPad5,4") { return Hardware.IPAD_AIR_2_WIFI_CELLULAR } if (hardware == "i386") { return Hardware.SIMULATOR } if (hardware == "x86_64") { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPhone")) { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPod")) { return Hardware.SIMULATOR } if (hardware.hasPrefix("iPad")) { return Hardware.SIMULATOR } //log message that your device is not present in the list logMessage(hardware) return Hardware.NOT_AVAILABLE } /// This method returns the readable description of hardware string /// /// - returns: readable description `String` of the device /// class public func hardwareDescription() -> String? { let hardware = hardwareString() if let deviceList = getDeviceList() { let hardwareDetail = deviceList[hardware] as? [String: AnyObject] if let hardwareDescription = hardwareDetail?["name"] { return hardwareDescription as? String } } //log message that your device is not present in the list logMessage(hardware) return nil } /// /// This method returns the hardware number not actual but logically. /// e.g. if the hardware string is 5,1 then hardware number would be 5.1 /// class public func hardwareNumber() -> Float { let hardware = hardwareString() if let deviceList = getDeviceList() { let hardwareDetail = deviceList[hardware] as? [String: Float] if let hardwareNumber = hardwareDetail?["version"] { return hardwareNumber } } //log message that your device is not present in the list logMessage(hardware) return 200.0 //device might be new one of missing one so returning 200.0f } /// This method returns the resolution for still image that can be received /// from back camera of the current device. Resolution returned for image oriented landscape right. /// /// - parameters: /// - hardware: `Hardware` type of the device /// /// - returns: `CGSize` of the image captured by the device /// class public func backCameraStillImageResolutionInPixels(hardware: Hardware) -> CGSize { switch (hardware) { case Hardware.IPHONE_2G, Hardware.IPHONE_3G: return CGSizeMake(1600, 1200) case Hardware.IPHONE_3GS: return CGSizeMake(2048, 1536) case Hardware.IPHONE_4, Hardware.IPHONE_4_CDMA, Hardware.IPAD_3_WIFI, Hardware.IPAD_3_WIFI_CDMA, Hardware.IPAD_3, Hardware.IPAD_4_WIFI, Hardware.IPAD_4, Hardware.IPAD_4_GSM_CDMA: return CGSizeMake(2592, 1936) case Hardware.IPHONE_4S, Hardware.IPHONE_5, Hardware.IPHONE_5_CDMA_GSM, Hardware.IPHONE_5C, Hardware.IPHONE_5C_CDMA_GSM, Hardware.IPHONE_6, Hardware.IPHONE_6_PLUS: return CGSizeMake(3264, 2448) case Hardware.IPHONE_6S, Hardware.IPHONE_6S_PLUS: return CGSizeMake(4032, 3024) case Hardware.IPOD_TOUCH_4G: return CGSizeMake(960, 720) case Hardware.IPOD_TOUCH_5G: return CGSizeMake(2440, 1605) case Hardware.IPAD_2_WIFI, Hardware.IPAD_2, Hardware.IPAD_2_CDMA: return CGSizeMake(872, 720) case Hardware.IPAD_MINI_WIFI, Hardware.IPAD_MINI, Hardware.IPAD_MINI_WIFI_CDMA: return CGSizeMake(1820, 1304) case Hardware.IPAD_AIR_2_WIFI, Hardware.IPAD_AIR_2_WIFI_CELLULAR: return CGSizeMake(1536, 2048) case Hardware.IPHONE_6S, Hardware.IPHONE_6S_PLUS: return CGSizeMake(3024, 4032) case Hardware.IPAD_PRO_WIFI, Hardware.IPAD_PRO_WIFI_CELLULAR: return CGSizeMake(2448, 3264) default: print("We have no resolution for your device's camera listed in this category. Please, make photo with back camera of your device, get its resolution in pixels (via Preview Cmd+I for example) and add a comment to this repository (https://github.com/InderKumarRathore/DeviceGuru) on GitHub.com in format Device = Hpx x Wpx.") } print("Your device is: \(hardwareDescription())") return CGSizeZero } /// Internal method for loggin, you don't need this method /// /// - parameters: /// - hardware: `String` hardware type of the device /// private static func logMessage(hardware: String) { print("This is a device which is not listed in this category. Please visit https://github.com/InderKumarRathore/DeviceGuru and add a comment there.") print("Your device hardware string is: %@", hardware) } }
mit
64c8e3a5fbd81896f8de759ec2671dd4
36.972696
332
0.637426
3.542184
false
false
false
false
Boerworz/Gagat
Gagat/Gagat.swift
1
4380
// // Gagat.swift // Gagat // // Created by Tim Andersson on 2017-02-17. // Copyright © 2017 Cocoabeans Software. All rights reserved. // import Foundation import UIKit /// A type that knows how to toggle between two alternative visual styles. public protocol GagatStyleable { /// Activates the alternative style that is currently not active. /// /// This method is called by Gagat at the start of a transition /// and at the end of a _cancelled_ transition (to revert to the /// previous style). /// /// This method is required. func toggleActiveStyle() /// Called when the style transition is about to begin. `toggleActiveStyle()` will be called just after this. /// /// This method is optional. func styleTransitionWillBegin() /// Called when the style transition ended. /// /// This method is optional. func styleTransitionDidEnd() } /// Since styleTransitionWillBegin() and styleTransitionDidEnd() aren't considered as required to implement /// the core functionality of the GagatStyleable protocol, this extension provides default (empty) implementations /// of those functions. This makes implementing them in your GagatStyleable object optional. public extension GagatStyleable { func styleTransitionWillBegin() {} func styleTransitionDidEnd() {} } public struct Gagat { /// The `Configuration` struct allows clients to configure certain /// aspects of the transition. /// /// Initialize an empty instance of the struct to use the defaults. public struct Configuration { /// Controls how much the border between the new and /// previous style is deformed when panning. The larger the /// factor is, the more the border is deformed. /// Specify a factor of 0 to entirely disable the deformation. /// /// Defaults to 1.0. public let jellyFactor: Double public init(jellyFactor: Double = 1.0) { self.jellyFactor = jellyFactor } } /// Represents a configured transition and allows clients to /// access properties that can be modified after configuration. public struct TransitionHandle { private let coordinator: TransitionCoordinator fileprivate init(coordinator: TransitionCoordinator) { self.coordinator = coordinator } /// The pan gesture recognizer that Gagat uses to trigger and drive the /// transition. /// /// You may use this property to configure the minimum or maximum number /// of required touches if you don't want to use the default two-finger /// pan. You may also use it to setup dependencies between this gesture /// recognizer and any other gesture recognizers in your application. /// /// - important: You *must not* change the gesture recognizer's delegate /// or remove targets not added by the client. public var panGestureRecognizer: UIPanGestureRecognizer { return coordinator.panGestureRecognizer } } /// Configures everything that's needed by Gagat to begin handling the transition /// in the specified window. /// /// - important: You *must* keep a reference to the `TransitionHandle` /// returned by this method even if you don't intend to access /// any of its properties. /// All Gagat-related objects will be torn down when the /// handle is deallocated, and the client will need to call /// `Gagat.configure(for:with:using:)` again to re-enable /// the Gagat transition. /// /// - note: This method shouldn't be called multiple times for the same window /// unless the returned handle has been deallocated. /// /// - parameter window: The window that the user will pan in to trigger the /// transition. /// - parameter styleableObject: An object that conforms to `GagatStyleable` and /// which is responsible for toggling to the alternative style when /// the transition is triggered or cancelled. /// - parameter configuration: The configuration to use for the transition. /// /// - returns: A new instance of `TransitionHandle`. public static func configure(for window: UIWindow, with styleableObject: GagatStyleable, using configuration: Configuration = Configuration()) -> TransitionHandle { let coordinator = TransitionCoordinator(targetView: window, styleableObject: styleableObject, configuration: configuration) return TransitionHandle(coordinator: coordinator) } }
mit
2387fba7f6a36049fec988a4cb6c1c19
38.098214
165
0.717972
4.423232
false
true
false
false
luckymore0520/GreenTea
Loyalty/Activity/Models/Activity.swift
1
6652
// // Activity.swift // Loyalty // // Created by WangKun on 16/1/27. // Copyright © 2016年 WangKun. All rights reserved. // import Foundation import AVOSCloud enum ActivityType:String{ case Promotion = "优惠促销"; case Loyalty = "集点卡"; } class Shop: AVObject, AVSubclassing { @NSManaged var shopName:String @NSManaged var rate:Double @NSManaged var commentCount:Int @NSManaged var location:AVGeoPoint @NSManaged var locationName:String @NSManaged var phoneNumber:String @NSManaged var shopDescription:String @NSManaged var avatar:AVFile @NSManaged var userId:String? @NSManaged var activitys:[Activity]? var comments:[Comment] = [] convenience init(shopName:String,location:CGPoint,locationName:String,phoneNumber:String,description:String,avatar:AVFile){ self.init() self.rate = 0 self.commentCount = 0 self.shopName = shopName self.locationName = locationName self.location = AVGeoPoint(latitude: Double(location.x), longitude: Double(location.y)) self.phoneNumber = phoneNumber self.avatar = avatar self.shopDescription = description if let user = UserInfoManager.sharedManager.currentUser { self.userId = user.username } } // AVSubClassing协议方法,返回对应的表名 static func parseClassName() -> String! { return "Shop" } func isMine()->Bool { return self.userId == UserInfoManager.sharedManager.currentUser?.username } } extension Shop { func rate(rate:Int, completionHandler:(success:Bool, errorMsg:String?) ->Void) { if rate == 0 { return } let newRate = (self.rate * Double(self.commentCount) + Double(rate)) / Double(self.commentCount + 1) self.rate = newRate self.commentCount += 1 self.saveInBackgroundWithBlock { (success, error) in completionHandler(success: success, errorMsg: NSError.errorMsg(error)) } } func addNewActivity(activity:Activity) { if self.activitys == nil { self.activitys = [] } self.activitys?.append(activity) self.saveInBackground() } } class Activity: AVObject, AVSubclassing { @NSManaged var activityTypeString:String? @NSManaged var avatar:AVFile @NSManaged var location:AVGeoPoint @NSManaged var locationName:String @NSManaged var shopId:String @NSManaged var creatorId:String @NSManaged var loyaltyCoinMaxCount:Int @NSManaged var likeCount:Int @NSManaged var name:String @NSManaged var startTime:NSDate @NSManaged var endTime:NSDate @NSManaged var activityDescription:String var shopInfo:Shop? var like:Like? var isLikedByMySelf:Bool? convenience init(shop:Shop,name:String,startTime:NSDate,endTime:NSDate,description:String,avatar:AVFile,activityType:String,loyaltyCoinMaxCount:Int) { self.init() self.activityTypeString = activityType self.shopId = shop.objectId self.creatorId = shop.userId ?? "" self.name = name self.startTime = startTime self.endTime = endTime self.loyaltyCoinMaxCount = loyaltyCoinMaxCount self.activityDescription = description self.avatar = avatar self.location = shop.location self.locationName = shop.locationName } var activityType:ActivityType? { get { guard let activityTypeString = self.activityTypeString else { return nil } return ActivityType(rawValue: activityTypeString) } } var isMine:Bool { return self.creatorId == UserInfoManager.sharedManager.currentUser?.username } static func parseClassName() -> String! { return "Activity" } } extension Activity { func queryIsLikedBySelf(completionHandler:(like:Like?)->Void){ if self.isLikedByMySelf != nil { completionHandler(like: self.like) return } guard let userId = UserInfoManager.sharedManager.currentUser?.objectId else { return } let query = Like.query() query.whereKey("userId", equalTo: userId) query.whereKey("activityId", equalTo: self.objectId) query.getFirstObjectInBackgroundWithBlock { (object, error) in self.like = object as? Like self.isLikedByMySelf = (self.like != nil) completionHandler(like: self.like) } } func queryShopInfo(completion:Shop->Void) { //获取shop的查询对象 let query = Shop.query() query.includeKey("activitys") //根据shopId查询shop query.getObjectInBackgroundWithId(self.shopId) { (shop, error) in if let shop = shop as? Shop { //回调 self.shopInfo = shop completion(shop) } } } static func query(keyword:String,completion:[Activity] -> Void) { let nameQuery = Activity.query() nameQuery.whereKey("name", containsString: keyword) let contentQuery = Activity.query() contentQuery.whereKey("activityDescription", containsString: keyword) let locationNameQuery = Activity.query() locationNameQuery.whereKey("locationName", containsString: keyword) let query = AVQuery.orQueryWithSubqueries([nameQuery,contentQuery,locationNameQuery]) query.findObjectsInBackgroundWithBlock { (activityObject, error) in var activityArray:[Activity] = [] for object in activityObject { if let activity = object as? Activity { activityArray.append(activity) } } completion(activityArray) } } static func query(nearGeoPoint:CGPoint?, type:ActivityType, completion:[Activity] -> Void) { let query = Activity.query() query.limit = 10 if let nearGeoPoint = nearGeoPoint { query.whereKey("location", nearGeoPoint: AVGeoPoint(latitude: Double(nearGeoPoint.x), longitude: Double(nearGeoPoint.y))) } query.whereKey("activityTypeString", equalTo: type.rawValue) query.findObjectsInBackgroundWithBlock { (activityObject, error) in var activityArray:[Activity] = [] for object in activityObject { if let activity = object as? Activity { activityArray.append(activity) } } completion(activityArray) } } }
mit
2372612fc8742713715cac3196a9bc32
32.769231
154
0.63508
4.7103
false
false
false
false
hooman/swift
test/AutoDiff/validation-test/custom_derivatives.swift
1
1454
// RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off) // REQUIRES: executable_test import StdlibUnittest #if canImport(Darwin) import Darwin.C #elseif canImport(Glibc) import Glibc #elseif os(Windows) import CRT #else #error("Unsupported platform") #endif import DifferentiationUnittest var CustomDerivativesTests = TestSuite("CustomDerivatives") // Specify non-differentiable functions. // These will be wrapped in `differentiableFunction` and tested. func unary(_ x: Tracked<Float>) -> Tracked<Float> { var x = x x *= 2 return x } func binary(_ x: Tracked<Float>, _ y: Tracked<Float>) -> Tracked<Float> { var x = x x *= y return x } CustomDerivativesTests.testWithLeakChecking("SumOfGradPieces") { var grad: Tracked<Float> = 0 func addToGrad(_ x: inout Tracked<Float>) { grad += x } _ = gradient(at: 4) { (x: Tracked<Float>) in x.withDerivative(addToGrad) * x.withDerivative(addToGrad) * x.withDerivative(addToGrad) } expectEqual(48, grad) } CustomDerivativesTests.testWithLeakChecking("ModifyGradientOfSum") { expectEqual(30, gradient(at: 4) { (x: Tracked<Float>) in x.withDerivative { $0 *= 10 } + x.withDerivative { $0 *= 20 } }) } CustomDerivativesTests.testWithLeakChecking("WithoutDerivative") { expectEqual(0, gradient(at: Tracked<Float>(4)) { x in withoutDerivative(at: x) { x in Tracked<Float>(sinf(x.value) + cosf(x.value)) } }) } runAllTests()
apache-2.0
878baf109d8a370fd3b060b56127d9e7
24.068966
73
0.697387
3.453682
false
true
false
false
yujinjcho/movie_recommendations
ios_ui/MovieRec/Classes/Modules/Rate/Application Logic/Manager/RateDataManager.swift
1
6814
// // RateDataManager.swift // MovieRec // // Created by Yujin Cho on 10/8/17. // Copyright © 2017 Yujin Cho. All rights reserved. // import os.log import Foundation import CloudKit import Kingfisher class RateDataManager : NSObject { var networkManager : NetworkManager? var moviesToRate = [Movie]() var ratings = [Rating]() var moviesStorePath = MovieStore.ArchiveURL.path var ratingsStorePath = RatingStore.ArchiveURL.path var prefetcher: ImagePrefetcher? let host = "https://movie-rec-project.herokuapp.com" let defaultUser = "test_user_03" var movieCounts: Int { return moviesToRate.count } var currentUser: String { if let userID = UserDefaults.standard.string(forKey: "userID") { return userID } else { return defaultUser } } var currentMovie: Movie? { if (moviesToRate.count > 0) { return moviesToRate.first } return nil } override init() { super.init() // saveCurrentRatingsToDisk(path: ratingsStorePath) // saveCurrentMoviesStateToDisk(path: moviesStorePath) } func loadMovies(completion: @escaping (Movie) -> Void) { let moviesFromDisk = loadMoviesFromDisk(path: moviesStorePath) if let moviesFromDisk = moviesFromDisk, moviesFromDisk.count > 0 { moviesToRate = moviesFromDisk.map { Movie(title:$0.title, photoUrl:$0.photoUrl, movieId:$0.movieId, createdDate: $0.createdDate) } completion(currentMovie!) } else { os_log("Loading Movies via API call", log: OSLog.default, type: .debug) let url = "\(host)/api/start" if let networkManager = networkManager { networkManager.getRequest(endPoint: url) { (data: Data) -> Void in if let newMovies = self.convertJSONtoMovies(data: data) { self.moviesToRate = newMovies.map { Movie(title:$0.title, photoUrl:$0.photoUrl, movieId:$0.movieId, createdDate: $0.createdDate) } self.saveCurrentMoviesStateToDisk(path: self.moviesStorePath) completion(self.currentMovie!) } } } } } func storeRating(rating: String) { if let currentMovie = currentMovie { let rating = Rating(movieID: currentMovie.movieId, rating: rating, userID: currentUser) ratings.append(rating) saveCurrentRatingsToDisk(path: ratingsStorePath) } } func removeFirstMovie() { if (moviesToRate.count > 0) { moviesToRate.remove(at: 0) print("movies length is now \(moviesToRate.count)") saveCurrentMoviesStateToDisk(path: moviesStorePath) } } func loadRatings() { if let ratingsFromDisk = loadRatingsFromDisk(path: ratingsStorePath) { ratings = ratingsFromDisk.map { Rating(movieID: $0.movieID, rating: $0.rating, userID: $0.userID) } } else { return } } func getNewMoviesToRate() { let url = "\(host)/api/refresh" let postData = formatUploadDataForMovieFetch() if let networkManager = networkManager { networkManager.postRequest(endPoint: url, postData: postData, completionHandler: { (data:Data)->Void in if let fetchedMovies = self.convertJSONtoMovies(data: data) { let moviesToAdd = self.selectMoviesToAdd(moviesToAdd: fetchedMovies.map { Movie(title:$0.title, photoUrl:$0.photoUrl, movieId:$0.movieId, createdDate: $0.createdDate) } ) self.moviesToRate += moviesToAdd self.saveCurrentMoviesStateToDisk(path: self.moviesStorePath) self.startImagePrefetcher(urls: moviesToAdd.map { $0.photoUrl }) } }) } } private func selectMoviesToAdd(moviesToAdd: [Movie]) -> [Movie] { let movieIds = Set(self.moviesToRate.map { $0.movieId }) return moviesToAdd.filter { !movieIds.contains($0.movieId) } } private func startImagePrefetcher(urls: [String]) { let urls = urls.map { URL(string: $0)! } prefetcher = ImagePrefetcher(urls: urls) { skippedResources, failedResources, completedResources in } if let prefetcher = prefetcher { prefetcher.start() } } private func convertJSONtoMovies(data: Data) -> [MovieStore]? { let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [[String: String]] { let newMovies = responseJSON.map { (movieToRate: [String: String]) -> MovieStore in let movieTitle = movieToRate["title"]! let movieId = movieToRate["movieId"]! let photoUrl = movieToRate["photoUrl"]! let createdDate = Date() return MovieStore(title: movieTitle, movieId: movieId, photoUrl: photoUrl, createdDate: createdDate) } return newMovies } return nil } private func loadRatingsFromDisk(path: String) -> [RatingStore]? { return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [RatingStore] } private func loadMoviesFromDisk(path: String) -> [MovieStore]? { return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [MovieStore] } private func saveCurrentRatingsToDisk(path: String) { let ratingsStore = ratings.map { RatingStore(movieID: $0.movieID, rating: $0.rating, userID: $0.userID) } let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(ratingsStore, toFile: path) if isSuccessfulSave { os_log("Ratings successfully saved.", log: OSLog.default, type: .debug) } else { os_log("Failed to save ratings", log: OSLog.default, type: .error) } } private func saveCurrentMoviesStateToDisk(path: String) { let moviesStore = moviesToRate.map { MovieStore(title: $0.title, movieId: $0.movieId, photoUrl: $0.photoUrl, createdDate: $0.createdDate) } NSKeyedArchiver.archiveRootObject(moviesStore, toFile: path) } private func formatUploadDataForMovieFetch() -> [String: Any] { let uploadRatings = ratings.map { ["movie_id": $0.movieID, "rating": $0.rating] } let unratedMovies = moviesToRate.map { $0.movieId } return [ "user_id": currentUser, "ratings": uploadRatings, "not_rated_movies": unratedMovies ] } }
mit
195cadc2df8884655f542219f79596bf
38.155172
154
0.603846
4.548064
false
false
false
false
ShaneQi/ZEGBot
Sources/Methods.swift
1
11374
// // Methods.swift // ZEGBot // // Created by Shane Qi on 5/29/16. // Copyright © 2016 com.github.shaneqi. All rights reserved. // // Licensed under Apache License v2.0 // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Dispatch /// All methods are performed synchronized. extension ZEGBot { @discardableResult public func send( message text: String, to receiver: Sendable, parseMode: ParseMode? = nil, disableWebPagePreview: Bool? = nil, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { let payload = SendingPayload( content: .message(text: text, parseMode: parseMode, disableWebPagePreview: disableWebPagePreview), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: replyMarkup) return try performRequest(ofMethod: payload.methodName, payload: payload) } @discardableResult public func forward( message: ForwardableMessage, to receiver: Sendable, disableNotification: Bool? = nil) throws -> Message { let payload = SendingPayload( content: .forwardableMessage(chatId: message.chatId, messageId: message.messageId), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: nil) return try performRequest(ofMethod: payload.methodName, payload: payload) } @discardableResult public func send( serverStoredContent: ServerStoredContent, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { let payload = SendingPayload( content: .serverStoredContent(serverStoredContent), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: nil) return try performRequest(ofMethod: payload.methodName, payload: payload) } @discardableResult public func send( _ sticker: Sticker, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .sticker(location: .telegramServer(fileId: sticker.fileId)), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ photo: PhotoSize, caption: String? = nil, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .photo(location: .telegramServer(fileId: photo.fileId), caption: caption), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ audio: Audio, caption: String? = nil, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .audio(location: .telegramServer(fileId: audio.fileId), caption: caption), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ document: Document, caption: String? = nil, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .document(location: .telegramServer(fileId: document.fileId), caption: caption), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ video: Video, caption: String? = nil, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .video(location: .telegramServer(fileId: video.fileId), caption: caption), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ voice: Voice, caption: String? = nil, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { return try send( serverStoredContent: .voice(location: .telegramServer(fileId: voice.fileId), caption: caption), to: receiver, disableNotification: disableNotification, replyMarkup: nil) } @discardableResult public func send( _ location: Location, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { let payload = SendingPayload( content: .location(latitude: location.latitude, longitude: location.longitude), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: nil) return try performRequest(ofMethod: payload.methodName, payload: payload) } @discardableResult public func send( _ venue: Venue, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { let payload = SendingPayload( content: .venue( latitude: venue.location.latitude, longitude: venue.location.longitude, title: venue.title, address: venue.address, foursquareId: venue.foursquareId), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: nil) return try performRequest(ofMethod: payload.methodName, payload: payload) } @discardableResult public func send( _ contact: Contact, to receiver: Sendable, disableNotification: Bool? = nil, replyMarkup: InlineKeyboardMarkup? = nil) throws -> Message { let payload = SendingPayload( content: .contact(phoneNumber: contact.phoneNumber, firstName: contact.firstName, lastName: contact.lastName), chatId: receiver.chatId, replyToMessageId: (receiver as? Replyable)?.replyToMessageId, disableNotification: disableNotification, replyMarkup: nil) return try performRequest(ofMethod: payload.methodName, payload: payload) } public func send(chatAction: ChatAction, to receiver: Sendable) throws { let payload = SendingPayload( content: .chatAction(chatAction: chatAction), chatId: receiver.chatId, replyToMessageId: nil, disableNotification: nil, replyMarkup: nil) let _: Bool = try performRequest(ofMethod: payload.methodName, payload: payload) } public func deleteMessage(inChat chatId: Int, messageId: Int) throws { let _: Bool = try performRequest(ofMethod: "deleteMessage", payload: ["chat_id": chatId, "message_id": messageId]) } public func getFile(ofId fileId: String) throws -> File { return try performRequest(ofMethod: "getFile", payload: ["file_id": fileId]) } public func getChatAdministrators(ofChatWithId chatId: Int) throws -> [ChatMember] { return try performRequest(ofMethod: "getChatAdministrators", payload: ["chat_id": chatId]) } public func answerCallbackQuery( callbackQueryId: String, text: String? = nil, showAlert: Bool? = nil, url: String? = nil, cacheTime: Int? = nil) throws { let _: Bool = try performRequest( ofMethod: "answerCallbackQuery", payload: AnswerCallbackQueryPayload( callbackQueryId: callbackQueryId, text: text, showAlert: showAlert, url: url, cacheTime: cacheTime)) } public func restrictChatMember( chatId: Int, userId: Int, untilDate: Date? = nil, canSendMessages: Bool? = nil, canSendMediaMessages: Bool? = nil, canSendOtherMessages: Bool? = nil, canAddWebPagePreviews: Bool? = nil) throws { let _: Bool = try performRequest( ofMethod: "restrictChatMember", payload: RestrictChatMemberPayload( chatId: chatId, userId: userId, untilDate: untilDate?.unixTimeInt ?? nil, canSendMessages: canSendMessages, canSendMediaMessages: canSendMediaMessages, canSendOtherMessages: canSendOtherMessages, canAddWebPagePreviews: canAddWebPagePreviews)) } public func kickChatMember( chatId: Int, userId: Int, untilDate: Date? = nil) throws { let _: Bool = try performRequest( ofMethod: "kickChatMember", payload: KickChatMemberPayload( chatId: chatId, userId: userId, untilDate: untilDate?.unixTimeInt ?? nil)) } @discardableResult public func editMessage( messageId: Int, chatId: Int, newText: String, parseMode: ParseMode? = nil, disableWebPagePreview: Bool? = nil) throws -> Message { let payload = UpdatingPayload( messageId: messageId, chatId: chatId, newContent: .text(newText: newText, parseMode: parseMode, disableWebPagePreview: disableWebPagePreview)) return try performRequest(ofMethod: "editMessageText", payload: payload) } @discardableResult public func editMessage( messageId: Int, chatId: Int, newCaption: String, parseMode: ParseMode? = nil) throws -> Message { let payload = UpdatingPayload( messageId: messageId, chatId: chatId, newContent: .caption(newCaption: newCaption, parseMode: parseMode)) return try performRequest(ofMethod: "editMessageCaption", payload: payload) } } extension ZEGBot { private func performRequest<Input, Output>(ofMethod method: String, payload: Input) throws -> Output where Input: Encodable, Output: Decodable { // Preparing the request. let bodyData = try JSONEncoder().encode(payload) let semaphore = DispatchSemaphore(value: 0) var request = URLRequest(url: URL(string: urlPrefix + method)!) request.httpMethod = "POST" request.httpBody = bodyData request.addValue("application/json", forHTTPHeaderField: "Content-Type") // Perform the request. var result: Result<Output>? let task = URLSession(configuration: .default).dataTask(with: request) { data, _, error in if let data = data { result = Result<Output>.decode(from: data) } else { result = .failure(error!) } semaphore.signal() } task.resume() semaphore.wait() switch result! { case .success(let output): return output case .failure(let error): throw error } } } private struct AnswerCallbackQueryPayload: Encodable { let callbackQueryId: String let text: String? let showAlert: Bool? let url: String? let cacheTime: Int? private enum CodingKeys: String, CodingKey { case text, url case callbackQueryId = "callback_query_id" case showAlert = "show_alert" case cacheTime = "cache_time" } } private struct RestrictChatMemberPayload: Encodable { let chatId: Int let userId: Int let untilDate: Int? let canSendMessages: Bool? let canSendMediaMessages: Bool? let canSendOtherMessages: Bool? let canAddWebPagePreviews: Bool? private enum CodingKeys: String, CodingKey { case chatId = "chat_id" case userId = "user_id" case untilDate = "until_date" case canSendMessages = "can_send_messages" case canSendMediaMessages = "can_send_media_messages" case canSendOtherMessages = "can_send_other_messages" case canAddWebPagePreviews = "can_add_web_page_previews" } } private struct KickChatMemberPayload: Encodable { let chatId: Int let userId: Int let untilDate: Int? private enum CodingKeys: String, CodingKey { case chatId = "chat_id" case userId = "user_id" case untilDate = "until_date" } }
apache-2.0
e7ef0e01c4459d4a4e0aa94ccc4367ea
30.244505
113
0.737009
3.76839
false
false
false
false
edwinbosire/YAWA
YAWA-Weather/NavigationController.swift
1
925
// // NavigationController.swift // YAWA-Weather // // Created by edwin bosire on 03/06/2015. // Copyright (c) 2015 Edwin Bosire. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.navigationBar.setBackgroundImage(UIImage(named: "navigationBarBackground"), forBarMetrics: .Default) self.navigationBar.shadowImage = UIImage() self.navigationBar.translucent = false let navigationBarAppearance = UINavigationBar.appearance() navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.blackColor(), NSFontAttributeName : UIFont(name: "Open Sans", size: 16.0)!] } } extension UINavigationBar { public override func sizeThatFits(size: CGSize) -> CGSize { let newsize: CGSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 60) return newsize } }
gpl-2.0
d1d081d14824efb58e188f80d02a80d4
27.030303
113
0.747027
4.363208
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Model/Location.swift
1
4089
// // MIT License // Copyright (c) Gathering Hall Studios // import Foundation import GRDB class Location: RowConvertible { var id: Int var name: String var icon: String? lazy var monsters: [LocationMonster] = { return Database.shared.locationMonsters(locationId: self.id) }() func items(rank: Quest.Rank) -> [LocationItem] { return Database.shared.locationItems(locationId: self.id, rank: rank) } func itemsByNode(rank: Quest.Rank) -> [String: [LocationItem]] { let allItems = Database.shared.locationItems(locationId: self.id, rank: rank) var itemsByNode = [String: [LocationItem]]() for item in allItems { let nodeName = item.nodeName var node = itemsByNode[nodeName] ?? [LocationItem]() node.append(item) itemsByNode[nodeName] = node } return itemsByNode } required init(row: Row) { id = row["_id"] name = row["name"] icon = row["map"] } } class LocationMonster : RowConvertible { let monsterId: Int let monster: String? let icon: String? let startArea: String? let moneArea: String? let restArea: String? var areas: String { return "\(startArea ?? "")" + " > " + (moneArea ?? "") + " > \(restArea ?? "")" } required init(row: Row) { monsterId = row["monsterid"] monster = row["monstername"] icon = row["monstericon"] startArea = row["start_area"] moneArea = row["move_area"] restArea = row["rest_area"] } } class LocationItem : RowConvertible { var itemId: Int var name: String? var icon: String? var rank: String? var area: String? var site: String? var group: Int? var isFixed: Bool var isRare: Bool var chance: Int? var stack: Int? var nodeName: String { return "\(area ?? "")" + (isFixed ? " Fixed" : " Random") + (site != nil ? " \(site!)" : "") + (group != nil ? " \(group!)" : "") + (isRare ? " Rare" : "") } required init(row: Row) { itemId = row["itemid"] name = row["itemname"] icon = row["itemicon"] rank = row["rank"] area = row["area"] site = row["site"] group = row["group_num"] chance = row["percentage"] stack = row["quantity"] isFixed = (row["fixed"] ?? false) isRare = (row["rare"] ?? false) } } extension Database { func location(id: Int) -> Location { let query = "SELECT * FROM locations WHERE _id == '\(id)'" return fetch(query)[0] } func locations(_ search: String? = nil) -> [Location] { let query = "SELECT * FROM locations " let order = "ORDER BY name" return fetch(select: query, order: order, search: search) } func locationMonsters(locationId: Int) -> [LocationMonster] { let query = "SELECT *," + " monsters.name AS monstername," + " monsters.icon_name AS monstericon," + " monsters._id AS monsterid" + " FROM monster_habitat" + " LEFT JOIN locations on monster_habitat.location_id = locations._id" + " LEFT JOIN monsters on monster_habitat.monster_id = monsters._id" + " WHERE locations._id == \(locationId)" return fetch(query) } func locationItems(locationId: Int, rank: Quest.Rank) -> [LocationItem] { let query = "SELECT *" + " ,items.name AS itemname," + " items.icon_name AS itemicon," + " items._id AS itemid" + " FROM gathering" + " LEFT JOIN items on gathering.item_id = items._id" + " LEFT JOIN locations on gathering.location_id = locations._id" + " WHERE locations._id == \(locationId)" + " AND rank == '\(rank.rawValue)'" + " ORDER BY site, percentage DESC" return fetch(query) } }
mit
21e5d775555597d7d8d86234fb65442b
28.207143
85
0.537295
3.997067
false
false
false
false
tamaki-shingo/SoraKit
Example/SoraKit/AnimeInfoTableViewController.swift
1
1372
// // YearPeriodTableViewController.swift // SoraKit // // Created by tamaki on 7/3/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import SoraKit class AnimeInfoTableViewController: UITableViewController { var targetYear: Int? var targetSeason: SoraSeason? private var dataSource: [AnimeInfo]? override func viewDidLoad() { super.viewDidLoad() if let year = targetYear, let season = targetSeason { Sora.animeInfo(OfYear: year, season: season, success: { (animeInfoList) in self.dataSource = animeInfoList self.tableView.reloadData() }, failure: { (error) in print(error) }) } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = dataSource?[indexPath.row].title cell.detailTextLabel?.text = "#" + (dataSource?[indexPath.row].twitter_hash_tag)! return cell } }
mit
289dab73c0f3a3d99f4e87aaa35c1fe4
28.170213
109
0.641867
4.71134
false
false
false
false
ikesyo/swift-corelibs-foundation
TestFoundation/HTTPServer.swift
6
18762
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //This is a very rudimentary HTTP server written plainly for testing URLSession. //It is not concurrent. It listens on a port, reads once and writes back only once. //We can make it better everytime we need more functionality to test different aspects of URLSession. import Dispatch #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public let globalDispatchQueue = DispatchQueue.global() public let dispatchQueueMake: (String) -> DispatchQueue = { DispatchQueue.init(label: $0) } public let dispatchGroupMake: () -> DispatchGroup = DispatchGroup.init struct _HTTPUtils { static let CRLF = "\r\n" static let VERSION = "HTTP/1.1" static let SPACE = " " static let CRLF2 = CRLF + CRLF static let EMPTY = "" } extension UInt16 { public init(networkByteOrder input: UInt16) { self.init(bigEndian: input) } } class _TCPSocket { private var listenSocket: Int32! private var socketAddress = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1) private var connectionSocket: Int32! private func isNotNegative(r: CInt) -> Bool { return r != -1 } private func isZero(r: CInt) -> Bool { return r == 0 } private func attempt(_ name: String, file: String = #file, line: UInt = #line, valid: (CInt) -> Bool, _ b: @autoclosure () -> CInt) throws -> CInt { let r = b() guard valid(r) else { throw ServerError(operation: name, errno: r, file: file, line: line) } return r } public private(set) var port: UInt16 init(port: UInt16?) throws { #if os(Linux) && !os(Android) let SOCKSTREAM = Int32(SOCK_STREAM.rawValue) #else let SOCKSTREAM = SOCK_STREAM #endif self.port = port ?? 0 listenSocket = try attempt("socket", valid: isNotNegative, socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP))) var on: Int = 1 _ = try attempt("setsockopt", valid: isZero, setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int>.size))) let sa = createSockaddr(port) socketAddress.initialize(to: sa) try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, { let addr = UnsafePointer<sockaddr>($0) _ = try attempt("bind", valid: isZero, bind(listenSocket, addr, socklen_t(MemoryLayout<sockaddr>.size))) }) var actualSA = sockaddr_in() withUnsafeMutablePointer(to: &actualSA) { ptr in ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { (ptr: UnsafeMutablePointer<sockaddr>) in var len = socklen_t(MemoryLayout<sockaddr>.size) getsockname(listenSocket, ptr, &len) } } self.port = UInt16(networkByteOrder: actualSA.sin_port) } private func createSockaddr(_ port: UInt16?) -> sockaddr_in { // Listen on the loopback address so that OSX doesnt pop up a dialog // asking to accept incoming connections if the firewall is enabled. let addr = UInt32(INADDR_LOOPBACK).bigEndian let netPort = UInt16(bigEndian: port ?? 0) #if os(Android) return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), __pad: (0,0,0,0,0,0,0,0)) #elseif os(Linux) return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0)) #else return sockaddr_in(sin_len: 0, sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0)) #endif } func acceptConnection(notify: ServerSemaphore) throws { _ = try attempt("listen", valid: isZero, listen(listenSocket, SOMAXCONN)) try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, { let addr = UnsafeMutablePointer<sockaddr>($0) var sockLen = socklen_t(MemoryLayout<sockaddr>.size) notify.signal() connectionSocket = try attempt("accept", valid: isNotNegative, accept(listenSocket, addr, &sockLen)) }) } func readData() throws -> String { var buffer = [UInt8](repeating: 0, count: 4096) _ = try attempt("read", valid: isNotNegative, CInt(read(connectionSocket, &buffer, 4096))) return String(cString: &buffer) } func split(_ str: String, _ count: Int) -> [String] { return stride(from: 0, to: str.count, by: count).map { i -> String in let startIndex = str.index(str.startIndex, offsetBy: i) let endIndex = str.index(startIndex, offsetBy: count, limitedBy: str.endIndex) ?? str.endIndex return String(str[startIndex..<endIndex]) } } func writeRawData(_ data: Data) throws { _ = try data.withUnsafeBytes { ptr in try attempt("write", valid: isNotNegative, CInt(write(connectionSocket, ptr, data.count))) } } func writeData(header: String, body: String, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { var header = Array(header.utf8) _ = try attempt("write", valid: isNotNegative, CInt(write(connectionSocket, &header, header.count))) if let sendDelay = sendDelay, let bodyChunks = bodyChunks { let count = max(1, Int(Double(body.utf8.count) / Double(bodyChunks))) let texts = split(body, count) for item in texts { sleep(UInt32(sendDelay)) var bytes = Array(item.utf8) _ = try attempt("write", valid: isNotNegative, CInt(write(connectionSocket, &bytes, bytes.count))) } } else { var bytes = Array(body.utf8) _ = try attempt("write", valid: isNotNegative, CInt(write(connectionSocket, &bytes, bytes.count))) } } func shutdown() { if let connectionSocket = self.connectionSocket { close(connectionSocket) } close(listenSocket) } } class _HTTPServer { let socket: _TCPSocket var port: UInt16 { get { return self.socket.port } } init(port: UInt16?) throws { socket = try _TCPSocket(port: port) } public class func create(port: UInt16?) throws -> _HTTPServer { return try _HTTPServer(port: port) } public func listen(notify: ServerSemaphore) throws { try socket.acceptConnection(notify: notify) } public func stop() { socket.shutdown() } public func request() throws -> _HTTPRequest { return try _HTTPRequest(request: socket.readData()) } public func respond(with response: _HTTPResponse, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { let semaphore = DispatchSemaphore(value: 0) let deadlineTime: DispatchTime if let startDelay = startDelay { deadlineTime = .now() + .seconds(Int(startDelay)) } else { deadlineTime = .now() } DispatchQueue.main.asyncAfter(deadline: deadlineTime) { do { try self.socket.writeData(header: response.header, body: response.body, sendDelay: sendDelay, bodyChunks: bodyChunks) semaphore.signal() } catch { } } semaphore.wait() } func respondWithBrokenResponses(uri: String) throws { let responseData: Data switch uri { case "/LandOfTheLostCities/Pompeii": /* this is an example of what you get if you connect to an HTTP2 server using HTTP/1.1. Curl interprets that as a HTTP/0.9 simple-response and therefore sends this back as a response body. Go figure! */ responseData = Data(bytes: [ 0x00, 0x00, 0x18, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x40, 0x00, 0x00, 0x06, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x86, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x32, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x70, 0x72, 0x65, 0x66, 0x61, 0x63, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x72, 0x72, 0x75, 0x70, 0x74, 0x2e, 0x20, 0x48, 0x65, 0x78, 0x20, 0x64, 0x75, 0x6d, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x20, 0x62, 0x79, 0x74, 0x65, 0x73, 0x3a, 0x20, 0x34, 0x37, 0x34, 0x35, 0x35, 0x34, 0x32, 0x30, 0x32, 0x66, 0x33, 0x33, 0x32, 0x66, 0x36, 0x34, 0x36, 0x35, 0x37, 0x36, 0x36, 0x39, 0x36, 0x33, 0x36, 0x35, 0x32, 0x66, 0x33, 0x31, 0x33, 0x32, 0x33, 0x33, 0x33, 0x34, 0x33, 0x35, 0x33, 0x36, 0x33, 0x37, 0x33, 0x38, 0x33, 0x39, 0x33, 0x30]) case "/LandOfTheLostCities/Sodom": /* a technically valid HTTP/0.9 simple-response */ responseData = ("technically, this is a valid HTTP/0.9 " + "simple-response. I know it's odd but CURL supports it " + "still...\r\nFind out more in those URLs:\r\n " + " - https://www.w3.org/Protocols/HTTP/1.0/spec.html#Message-Types\r\n" + " - https://github.com/curl/curl/issues/467\r\n").data(using: .utf8)! case "/LandOfTheLostCities/Gomorrah": /* just broken, hope that's not officially HTTP/0.9 :p */ responseData = "HTTP/1.1\r\n\r\n\r\n".data(using: .utf8)! case "/LandOfTheLostCities/Myndus": responseData = ("HTTP/1.1 200 OK\r\n" + "\r\n" + "this is a body that isn't legal as it's " + "neither chunked encoding nor any Content-Length\r\n").data(using: .utf8)! case "/LandOfTheLostCities/Kameiros": responseData = ("HTTP/1.1 999 Wrong Code\r\n" + "illegal: status code (too large)\r\n" + "\r\n").data(using: .utf8)! case "/LandOfTheLostCities/Dinavar": responseData = ("HTTP/1.1 20 Too Few Digits\r\n" + "illegal: status code (too few digits)\r\n" + "\r\n").data(using: .utf8)! case "/LandOfTheLostCities/Kuhikugu": responseData = ("HTTP/1.1 2000 Too Many Digits\r\n" + "illegal: status code (too many digits)\r\n" + "\r\n").data(using: .utf8)! default: responseData = ("HTTP/1.1 500 Internal Server Error\r\n" + "case-missing-in: TestFoundation/HTTPServer.swift\r\n" + "\r\n").data(using: .utf8)! } try self.socket.writeRawData(responseData) } } struct _HTTPRequest { enum Method : String { case GET case POST case PUT } let method: Method let uri: String let body: String let headers: [String] public init(request: String) { let lines = request.components(separatedBy: _HTTPUtils.CRLF2)[0].components(separatedBy: _HTTPUtils.CRLF) headers = Array(lines[0...lines.count-2]) method = Method(rawValue: headers[0].components(separatedBy: " ")[0])! uri = headers[0].components(separatedBy: " ")[1] body = lines.last! } public func getCommaSeparatedHeaders() -> String { var allHeaders = "" for header in headers { allHeaders += header + "," } return allHeaders } } struct _HTTPResponse { enum Response : Int { case OK = 200 case REDIRECT = 302 } private let responseCode: Response private let headers: String public let body: String public init(response: Response, headers: String = _HTTPUtils.EMPTY, body: String) { self.responseCode = response self.headers = headers self.body = body } public var header: String { let statusLine = _HTTPUtils.VERSION + _HTTPUtils.SPACE + "\(responseCode.rawValue)" + _HTTPUtils.SPACE + "\(responseCode)" return statusLine + (headers != _HTTPUtils.EMPTY ? _HTTPUtils.CRLF + headers : _HTTPUtils.EMPTY) + _HTTPUtils.CRLF2 } } public class TestURLSessionServer { let capitals: [String:String] = ["Nepal":"Kathmandu", "Peru":"Lima", "Italy":"Rome", "USA":"Washington, D.C.", "UnitedStates": "USA", "country.txt": "A country is a region that is identified as a distinct national entity in political geography"] let httpServer: _HTTPServer let startDelay: TimeInterval? let sendDelay: TimeInterval? let bodyChunks: Int? var port: UInt16 { get { return self.httpServer.port } } public init (port: UInt16?, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { httpServer = try _HTTPServer.create(port: port) self.startDelay = startDelay self.sendDelay = sendDelay self.bodyChunks = bodyChunks } public func start(started: ServerSemaphore) throws { started.signal() try httpServer.listen(notify: started) } public func readAndRespond() throws { let req = try httpServer.request() if req.uri.hasPrefix("/LandOfTheLostCities/") { /* these are all misbehaving servers */ try httpServer.respondWithBrokenResponses(uri: req.uri) } else { try httpServer.respond(with: process(request: req), startDelay: self.startDelay, sendDelay: self.sendDelay, bodyChunks: self.bodyChunks) } } func process(request: _HTTPRequest) -> _HTTPResponse { if request.method == .GET || request.method == .POST || request.method == .PUT { return getResponse(request: request) } else { fatalError("Unsupported method!") } } func getResponse(request: _HTTPRequest) -> _HTTPResponse { let uri = request.uri if uri == "/upload" { let text = "Upload completed!" return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text) } if uri == "/country.txt" { let text = capitals[String(uri.dropFirst())]! return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text) } if uri == "/requestHeaders" { let text = request.getCommaSeparatedHeaders() return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text) } if uri == "/UnitedStates" { let value = capitals[String(uri.dropFirst())]! let text = request.getCommaSeparatedHeaders() let host = request.headers[1].components(separatedBy: " ")[1] let ip = host.components(separatedBy: ":")[0] let port = host.components(separatedBy: ":")[1] let newPort = Int(port)! + 1 let newHost = ip + ":" + String(newPort) let httpResponse = _HTTPResponse(response: .REDIRECT, headers: "Location: http://\(newHost + "/" + value)", body: text) return httpResponse } return _HTTPResponse(response: .OK, body: capitals[String(uri.dropFirst())]!) } func stop() { httpServer.stop() } } struct ServerError : Error { let operation: String let errno: CInt let file: String let line: UInt var _code: Int { return Int(errno) } var _domain: String { return NSPOSIXErrorDomain } } extension ServerError : CustomStringConvertible { var description: String { let s = String(validatingUTF8: strerror(errno)) ?? "" return "\(operation) failed: \(s) (\(_code))" } } public class ServerSemaphore { let dispatchSemaphore = DispatchSemaphore(value: 0) public func wait() { dispatchSemaphore.wait() } public func signal() { dispatchSemaphore.signal() } } class LoopbackServerTest : XCTestCase { private static let staticSyncQ = DispatchQueue(label: "org.swift.TestFoundation.HTTPServer.StaticSyncQ") private static var _serverPort: Int = -1 static var serverPort: Int { get { return staticSyncQ.sync { _serverPort } } set { staticSyncQ.sync { _serverPort = newValue } } } override class func setUp() { super.setUp() func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws { while true { let test = try TestURLSessionServer(port: nil, startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks) serverPort = Int(test.port) try test.start(started: condition) try test.readAndRespond() serverPort = -2 test.stop() } } let serverReady = ServerSemaphore() globalDispatchQueue.async { do { try runServer(with: serverReady) } catch { XCTAssertTrue(true) return } } serverReady.wait() } }
apache-2.0
f634717b548b8389aaa7cefcaaf78a78
37.684536
157
0.580642
3.83838
false
false
false
false
qinting513/SwiftNote
youtube/YouTube/Supporting views/Search.swift
1
6393
// // Search.swift // YouTube // // Created by Haik Aslanyan on 7/4/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // protocol SearchDelegate { func hideSearchView(status : Bool) } import UIKit class Search: UIView, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { //MARK: Properties let statusView: UIView = { let st = UIView.init(frame: UIApplication.shared.statusBarFrame) st.backgroundColor = UIColor.black st.alpha = 0.15 return st }() lazy var searchView: UIView = { let sv = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: 68)) sv.backgroundColor = UIColor.white sv.alpha = 0 return sv }() lazy var backgroundView: UIView = { let bv = UIView.init(frame: self.frame) bv.backgroundColor = UIColor.black bv.alpha = 0 return bv }() lazy var backButton: UIButton = { let bb = UIButton.init(frame: CGRect.init(x: 0, y: 20, width: 48, height: 48)) bb.setBackgroundImage(UIImage.init(named: "cancel"), for: []) bb.addTarget(self, action: #selector(Search.dismiss), for: .touchUpInside) return bb }() lazy var searchField: UITextField = { let sf = UITextField.init(frame: CGRect.init(x: 48, y: 20, width: self.frame.width - 50, height: 48)) sf.placeholder = "Seach on Youtube" sf.keyboardAppearance = .dark return sf }() lazy var tableView: UITableView = { let tv: UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 68, width: self.frame.width, height: 288)) return tv }() var items = [String]() var delegate:SearchDelegate? //MARK: Methods func customization() { self.addSubview(self.backgroundView) self.backgroundView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(Search.dismiss))) self.addSubview(self.searchView) self.searchView.addSubview(self.searchField) self.searchView.addSubview(self.backButton) self.tableView.register(searchCell.self, forCellReuseIdentifier: "Cell") self.tableView.delegate = self self.tableView.dataSource = self self.tableView.tableFooterView = UIView() self.tableView.backgroundColor = UIColor.clear self.searchField.delegate = self self.addSubview(self.statusView) } func animate() { UIView.animate(withDuration: 0.2, animations: { self.backgroundView.alpha = 0.5 self.searchView.alpha = 1 self.searchField.becomeFirstResponder() }) } func dismiss() { self.searchField.text = "" self.items.removeAll() self.tableView.removeFromSuperview() UIView.animate(withDuration: 0.2, animations: { self.backgroundView.alpha = 0 self.searchView.alpha = 0 self.searchField.resignFirstResponder() }, completion: {(Bool) in self.delegate?.hideSearchView(status: true) }) } //MARK: TextField Delegates func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if (self.searchField.text == "" || self.searchField.text == nil) { self.items = [] self.tableView.removeFromSuperview() } else{ let _ = URLSession.shared.dataTask(with: requestSuggestionsURL(text: self.searchField.text!), completionHandler: { (data, response, error) in if error == nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSArray self.items = json[1] as! [String] DispatchQueue.main.async(execute: { if self.items.count > 0 { self.addSubview(self.tableView) } else { self.tableView.removeFromSuperview() } self.tableView.reloadData() }) } catch _ { print("Something wrong happened") } } else { print("error downloading suggestions") } }).resume() } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { dismiss() return true } //MARK: TableView Delegates and Datasources func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! searchCell cell.itemLabel.text = items[indexPath.row] cell.backgroundColor = UIColor.rbg(r: 245, g: 245, b: 245) cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 48 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.searchField.text = items[indexPath.row] } //MARK: Inits override init(frame: CGRect) { super.init(frame: frame) customization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { self.tableView.separatorStyle = .none } } class searchCell: UITableViewCell { lazy var itemLabel: UILabel = { let il: UILabel = UILabel.init(frame: CGRect.init(x: 48, y: 0, width: self.contentView.bounds.width - 48, height: self.contentView.bounds.height)) il.textColor = UIColor.gray return il }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: "Cell") self.addSubview(itemLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
640006e0b67a22b3dcf453ccb43b1a13
34.120879
154
0.593085
4.727811
false
false
false
false
JGiola/swift-corelibs-foundation
Foundation/Decimal.swift
1
72697
// This source file is part of the Swift.org open source project // // Copyright (c) 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public var NSDecimalMaxSize: Int32 { return 8 } // Give a precision of at least 38 decimal digits, 128 binary positions. public var NSDecimalNoScale: Int32 { return Int32(Int16.max) } public struct Decimal { fileprivate static let maxSize: UInt32 = UInt32(NSDecimalMaxSize) fileprivate var __exponent: Int8 fileprivate var __lengthAndFlags: UInt8 fileprivate var __reserved: UInt16 public var _exponent: Int32 { get { return Int32(__exponent) } set { __exponent = Int8(truncatingIfNeeded: newValue) } } // length == 0 && isNegative -> NaN public var _length: UInt32 { get { return UInt32((__lengthAndFlags & 0b0000_1111)) } set { guard newValue <= maxMantissaLength else { fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)") } __lengthAndFlags = (__lengthAndFlags & 0b1111_0000) | UInt8(newValue & 0b0000_1111) } } public var _isNegative: UInt32 { get { return UInt32(((__lengthAndFlags) & 0b0001_0000) >> 4) } set { __lengthAndFlags = (__lengthAndFlags & 0b1110_1111) | (UInt8(newValue & 0b0000_0001 ) << 4) } } public var _isCompact: UInt32 { get { return UInt32(((__lengthAndFlags) & 0b0010_0000) >> 5) } set { __lengthAndFlags = (__lengthAndFlags & 0b1101_1111) | (UInt8(newValue & 0b0000_00001 ) << 5) } } public var _reserved: UInt32 { get { return UInt32(UInt32(__lengthAndFlags & 0b1100_0000) << 10 | UInt32(__reserved)) } set { __lengthAndFlags = (__lengthAndFlags & 0b0011_1111) | UInt8(UInt32(newValue & (0b11 << 16)) >> 10) __reserved = UInt16(newValue & 0b1111_1111_1111_1111) } } public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) public init() { self._mantissa = (0,0,0,0,0,0,0,0) self.__exponent = 0 self.__lengthAndFlags = 0 self.__reserved = 0 } fileprivate init(length: UInt32, mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)) { self._mantissa = mantissa self.__exponent = 0 self.__lengthAndFlags = 0 self.__reserved = 0 self._length = length } public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)){ self._mantissa = _mantissa self.__exponent = Int8(truncatingIfNeeded: _exponent) self.__lengthAndFlags = UInt8(_length & 0b1111) self.__reserved = 0 self._isNegative = _isNegative self._isCompact = _isCompact self._reserved = _reserved } } extension Decimal { public static let leastFiniteMagnitude = Decimal( _exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff) ) public static let greatestFiniteMagnitude = Decimal( _exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff) ) public static let leastNormalMagnitude = Decimal( _exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000) ) public static let leastNonzeroMagnitude = Decimal( _exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000) ) public static let pi = Decimal( _exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58) ) public var exponent: Int { get { return Int(self.__exponent) } } public var significand: Decimal { get { return Decimal(_exponent: 0, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa) } } public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) { self.init(_exponent: Int32(exponent) + significand._exponent, _length: significand._length, _isNegative: sign == .plus ? 0 : 1, _isCompact: significand._isCompact, _reserved: 0, _mantissa: significand._mantissa) } public init(signOf: Decimal, magnitudeOf magnitude: Decimal) { self.init(_exponent: magnitude._exponent, _length: magnitude._length, _isNegative: signOf._isNegative, _isCompact: magnitude._isCompact, _reserved: 0, _mantissa: magnitude._mantissa) } public var sign: FloatingPointSign { return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus } public static var radix: Int { return 10 } public var ulp: Decimal { if !self.isFinite { return Decimal.nan } return Decimal(_exponent: _exponent, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } public func isEqual(to other: Decimal) -> Bool { return self.compare(to: other) == .orderedSame } public func isLess(than other: Decimal) -> Bool { return self.compare(to: other) == .orderedAscending } public func isLessThanOrEqualTo(_ other: Decimal) -> Bool { let comparison = self.compare(to: other) return comparison == .orderedAscending || comparison == .orderedSame } public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool { // Notes: Decimal does not have -0 or infinities to worry about if self.isNaN { return false } else if self < other { return true } else if other < self { return false } // fall through to == behavior return true } public var isCanonical: Bool { return true } public var nextUp: Decimal { return self + Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } public var nextDown: Decimal { return self - Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } } extension Decimal : Hashable, Comparable { internal var doubleValue: Double { if _length == 0 { if _isNegative == 1 { return Double.nan } else { return 0 } } var d = 0.0 for idx in stride(from: min(_length, 8), to: 0, by: -1) { d = d * 65536 + Double(self[idx - 1]) } if _exponent < 0 { for _ in _exponent..<0 { d /= 10.0 } } else { for _ in 0..<_exponent { d *= 10.0 } } return _isNegative != 0 ? -d : d } public var hashValue: Int { return Int(bitPattern: __CFHashDouble(doubleValue)) } public static func ==(lhs: Decimal, rhs: Decimal) -> Bool { if lhs.isNaN { return rhs.isNaN } if lhs.__exponent == rhs.__exponent && lhs.__lengthAndFlags == rhs.__lengthAndFlags && lhs.__reserved == rhs.__reserved { if lhs._mantissa.0 == rhs._mantissa.0 && lhs._mantissa.1 == rhs._mantissa.1 && lhs._mantissa.2 == rhs._mantissa.2 && lhs._mantissa.3 == rhs._mantissa.3 && lhs._mantissa.4 == rhs._mantissa.4 && lhs._mantissa.5 == rhs._mantissa.5 && lhs._mantissa.6 == rhs._mantissa.6 && lhs._mantissa.7 == rhs._mantissa.7 { return true } } var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame } public static func <(lhs: Decimal, rhs: Decimal) -> Bool { var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending } } extension Decimal : ExpressibleByFloatLiteral { public init(floatLiteral value: Double) { self.init(value) } } extension Decimal : ExpressibleByIntegerLiteral { public init(integerLiteral value: Int) { self.init(value) } } extension Decimal : SignedNumeric { public var magnitude: Decimal { return Decimal(_exponent: _exponent, _length: _length, _isNegative: 0, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa) } // FIXME(integers): implement properly public init?<T : BinaryInteger>(exactly source: T) { fatalError() } public static func +=(_ lhs: inout Decimal, _ rhs: Decimal) { var leftOp = lhs var rightOp = rhs _ = NSDecimalAdd(&lhs, &leftOp, &rightOp, .plain) } public static func -=(_ lhs: inout Decimal, _ rhs: Decimal) { var leftOp = lhs var rightOp = rhs _ = NSDecimalSubtract(&lhs, &leftOp, &rightOp, .plain) } public static func *=(_ lhs: inout Decimal, _ rhs: Decimal) { var leftOp = lhs var rightOp = rhs _ = NSDecimalMultiply(&lhs, &leftOp, &rightOp, .plain) } public static func /=(_ lhs: inout Decimal, _ rhs: Decimal) { var leftOp = lhs var rightOp = rhs _ = NSDecimalDivide(&lhs, &leftOp, &rightOp, .plain) } public static func +(lhs: Decimal, rhs: Decimal) -> Decimal { var answer = lhs answer += rhs return answer; } public static func -(lhs: Decimal, rhs: Decimal) -> Decimal { var answer = lhs answer -= rhs return answer; } public static func /(lhs: Decimal, rhs: Decimal) -> Decimal { var answer = lhs answer /= rhs return answer; } public static func *(lhs: Decimal, rhs: Decimal) -> Decimal { var answer = lhs answer *= rhs return answer; } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") } public mutating func negate() { guard _length != 0 else { return } _isNegative = _isNegative == 0 ? 1 : 0 } } extension Decimal { @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func add(_ other: Decimal) { self += other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func subtract(_ other: Decimal) { self -= other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func multiply(by other: Decimal) { self *= other } @available(swift, obsoleted: 4, message: "Please use arithmetic operators instead") @_transparent public mutating func divide(by other: Decimal) { self /= other } } extension Decimal : Strideable { public func distance(to other: Decimal) -> Decimal { return self - other } public func advanced(by n: Decimal) -> Decimal { return self + n } } extension Decimal { public typealias RoundingMode = NSDecimalNumber.RoundingMode public typealias CalculationError = NSDecimalNumber.CalculationError public init(_ value: UInt8) { self.init(UInt64(value)) } public init(_ value: Int8) { self.init(Int64(value)) } public init(_ value: UInt16) { self.init(UInt64(value)) } public init(_ value: Int16) { self.init(Int64(value)) } public init(_ value: UInt32) { self.init(UInt64(value)) } public init(_ value: Int32) { self.init(Int64(value)) } public init(_ value: Double) { precondition(!value.isInfinite, "Decimal does not yet fully adopt FloatingPoint") if value.isNaN { self = Decimal.nan } else if value == 0.0 { self = Decimal() } else { self = Decimal() let negative = value < 0 var val = negative ? -1 * value : value var exponent = 0 while val < Double(UInt64.max - 1) { val *= 10.0 exponent -= 1 } while Double(UInt64.max - 1) < val { val /= 10.0 exponent += 1 } var mantissa = UInt64(val) var i = Int32(0) // this is a bit ugly but it is the closest approximation of the C initializer that can be expressed here. while mantissa != 0 && i < NSDecimalMaxSize { switch i { case 0: _mantissa.0 = UInt16(truncatingIfNeeded:mantissa) case 1: _mantissa.1 = UInt16(truncatingIfNeeded:mantissa) case 2: _mantissa.2 = UInt16(truncatingIfNeeded:mantissa) case 3: _mantissa.3 = UInt16(truncatingIfNeeded:mantissa) case 4: _mantissa.4 = UInt16(truncatingIfNeeded:mantissa) case 5: _mantissa.5 = UInt16(truncatingIfNeeded:mantissa) case 6: _mantissa.6 = UInt16(truncatingIfNeeded:mantissa) case 7: _mantissa.7 = UInt16(truncatingIfNeeded:mantissa) default: fatalError("initialization overflow") } mantissa = mantissa >> 16 i += 1 } _length = UInt32(i) _isNegative = negative ? 1 : 0 _isCompact = 0 _exponent = Int32(exponent) self.compact() } } public init(_ value: UInt64) { self = Decimal() if value == 0 { return } var compactValue = value var exponent: Int32 = 0 while compactValue % 10 == 0 { compactValue /= 10 exponent += 1 } _isCompact = 1 _exponent = exponent let wordCount = ((UInt64.bitWidth - compactValue.leadingZeroBitCount) + (UInt16.bitWidth - 1)) / UInt16.bitWidth _length = UInt32(wordCount) _mantissa.0 = UInt16(truncatingIfNeeded: compactValue >> 0) _mantissa.1 = UInt16(truncatingIfNeeded: compactValue >> 16) _mantissa.2 = UInt16(truncatingIfNeeded: compactValue >> 32) _mantissa.3 = UInt16(truncatingIfNeeded: compactValue >> 48) } public init(_ value: Int64) { self.init(value.magnitude) if value < 0 { _isNegative = 1 } } public init(_ value: UInt) { self.init(UInt64(value)) } public init(_ value: Int) { self.init(Int64(value)) } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var infinity: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var signalingNaN: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } public var isSignalingNaN: Bool { return false } public static var nan: Decimal { return quietNaN } public static var quietNaN: Decimal { var quiet = Decimal() quiet._isNegative = 1 return quiet } public var floatingPointClass: FloatingPointClassification { if _length == 0 && _isNegative == 1 { return .quietNaN } else if _length == 0 { return .positiveZero } if _isNegative == 1 { return .negativeNormal } else { return .positiveNormal } } public var isSignMinus: Bool { return _isNegative != 0 } public var isNormal: Bool { return !isZero && !isInfinite && !isNaN } public var isFinite: Bool { return !isNaN } public var isZero: Bool { return _length == 0 && _isNegative == 0 } public var isSubnormal: Bool { return false } public var isInfinite: Bool { return false } public var isNaN: Bool { return _length == 0 && _isNegative == 1 } public var isSignaling: Bool { return false } } extension Decimal : CustomStringConvertible { public init?(string: String, locale: Locale? = nil) { let scan = Scanner(string: string) var theDecimal = Decimal() if !scan.scanDecimal(&theDecimal) { return nil } self = theDecimal } public var description: String { if self.isNaN { return "NaN" } if _length == 0 { return "0" } var copy = self let ZERO : CChar = 0x30 // ASCII '0' == 0x30 let decimalChar : CChar = 0x2e // ASCII '.' == 0x2e let MINUS : CChar = 0x2d // ASCII '-' == 0x2d let bufferSize = 200 // max value : 39+128+sign+decimalpoint var buffer = Array<CChar>(repeating: 0, count: bufferSize) var i = bufferSize - 1 while copy._exponent > 0 { i -= 1 buffer[i] = ZERO copy._exponent -= 1 } if copy._exponent == 0 { copy._exponent = 1 } while copy._length != 0 { var remainder: UInt16 = 0 if copy._exponent == 0 { i -= 1 buffer[i] = decimalChar } copy._exponent += 1 (remainder,_) = divideByShort(&copy, 10) i -= 1 buffer[i] = Int8(remainder) + ZERO } if copy._exponent <= 0 { while copy._exponent != 0 { i -= 1 buffer[i] = ZERO copy._exponent += 1 } i -= 1 buffer[i] = decimalChar i -= 1 buffer[i] = ZERO } if copy._isNegative != 0 { i -= 1 buffer[i] = MINUS } return String(cString: Array(buffer.suffix(from:i))) } } fileprivate func divideByShort<T:VariableLengthNumber>(_ d: inout T, _ divisor:UInt16) -> (UInt16,NSDecimalNumber.CalculationError) { if divisor == 0 { d._length = 0 return (0,.divideByZero) } // note the below is not the same as from length to 0 by -1 var carry: UInt32 = 0 for i in (0..<d._length).reversed() { let accumulator = UInt32(d[i]) + carry * (1<<16) d[i] = UInt16(accumulator / UInt32(divisor)) carry = accumulator % UInt32(divisor) } d.trimTrailingZeros() return (UInt16(carry),.noError) } fileprivate func multiplyByShort<T:VariableLengthNumber>(_ d: inout T, _ mul:UInt16) -> NSDecimalNumber.CalculationError { if mul == 0 { d._length = 0 return .noError } var carry: UInt32 = 0 // FIXME handle NSCalculationOverflow here? for i in 0..<d._length { let accumulator: UInt32 = UInt32(d[i]) * UInt32(mul) + carry carry = accumulator >> 16 d[i] = UInt16(truncatingIfNeeded: accumulator) } if carry != 0 { if d._length >= Decimal.maxSize { return .overflow } d[d._length] = UInt16(truncatingIfNeeded: carry) d._length += 1 } return .noError } fileprivate func addShort<T:VariableLengthNumber>(_ d: inout T, _ add:UInt16) -> NSDecimalNumber.CalculationError { var carry:UInt32 = UInt32(add) for i in 0..<d._length { let accumulator: UInt32 = UInt32(d[i]) + carry carry = accumulator >> 16 d[i] = UInt16(truncatingIfNeeded: accumulator) } if carry != 0 { if d._length >= Decimal.maxSize { return .overflow } d[d._length] = UInt16(truncatingIfNeeded: carry) d._length += 1 } return .noError } public func NSDecimalIsNotANumber(_ dcm: UnsafePointer<Decimal>) -> Bool { return dcm.pointee.isNaN } /*************** Operations ***********/ public func NSDecimalCopy(_ destination: UnsafeMutablePointer<Decimal>, _ source: UnsafePointer<Decimal>) { destination.pointee.__lengthAndFlags = source.pointee.__lengthAndFlags destination.pointee.__exponent = source.pointee.__exponent destination.pointee.__reserved = source.pointee.__reserved destination.pointee._mantissa = source.pointee._mantissa } public func NSDecimalCompact(_ number: UnsafeMutablePointer<Decimal>) { number.pointee.compact() } // NSDecimalCompare:Compares leftOperand and rightOperand. public func NSDecimalCompare(_ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>) -> ComparisonResult { let left = leftOperand.pointee let right = rightOperand.pointee return left.compare(to: right) } fileprivate extension UInt16 { func compareTo(_ other: UInt16) -> ComparisonResult { if self < other { return .orderedAscending } else if self > other { return .orderedDescending } else { return .orderedSame } } } fileprivate func mantissaCompare<T:VariableLengthNumber>( _ left: T, _ right: T) -> ComparisonResult { if left._length > right._length { return .orderedDescending } if left._length < right._length { return .orderedAscending } let length = left._length // == right._length for i in (0..<length).reversed() { let comparison = left[i].compareTo(right[i]) if comparison != .orderedSame { return comparison } } return .orderedSame } fileprivate func fitMantissa(_ big: inout WideDecimal, _ exponent: inout Int32, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { if big._length <= Decimal.maxSize { return .noError } var remainder: UInt16 = 0 var previousRemainder: Bool = false // Divide by 10 as much as possible while big._length > Decimal.maxSize + 1 { if remainder != 0 { previousRemainder = true } (remainder,_) = divideByShort(&big,10000) exponent += 4 } while big._length > Decimal.maxSize { if remainder != 0 { previousRemainder = true } (remainder,_) = divideByShort(&big,10) exponent += 1 } // If we are on a tie, adjust with previous remainder. // .50001 is equivalent to .6 if previousRemainder && (remainder == 0 || remainder == 5) { remainder += 1 } if remainder == 0 { return .noError } // Round the result switch roundingMode { case .down: break case .bankers: if remainder == 5 && (big[0] & 1) == 0 { break } fallthrough case .plain: if remainder < 5 { break } fallthrough case .up: let originalLength = big._length // big._length += 1 ?? _ = addShort(&big,1) if originalLength > big._length { // the last digit is == 0. Remove it. _ = divideByShort(&big, 10) exponent += 1 } } return .lossOfPrecision; } fileprivate func integerMultiply<T:VariableLengthNumber>(_ big: inout T, _ left: T, _ right: Decimal) -> NSDecimalNumber.CalculationError { if left._length == 0 || right._length == 0 { big._length = 0 return .noError } if big._length == 0 || big._length > left._length + right._length { big._length = min(big.maxMantissaLength,left._length + right._length) } big.zeroMantissa() var carry: UInt16 = 0 for j in 0..<right._length { var accumulator: UInt32 = 0 carry = 0 for i in 0..<left._length { if i + j < big._length { let bigij = UInt32(big[i+j]) accumulator = UInt32(carry) + bigij + UInt32(right[j]) * UInt32(left[i]) carry = UInt16(truncatingIfNeeded:accumulator >> 16) big[i+j] = UInt16(truncatingIfNeeded:accumulator) } else if carry != 0 || (right[j] == 0 && left[j] == 0) { return .overflow } } if carry != 0 { if left._length + j < big._length { big[left._length + j] = carry } else { return .overflow } } } big.trimTrailingZeros() return .noError } fileprivate func integerDivide<T:VariableLengthNumber>(_ r: inout T, _ cu: T, _ cv: Decimal) -> NSDecimalNumber.CalculationError { // Calculate result = a / b. // Result could NOT be a pointer to same space as a or b. // resultLen must be >= aLen - bLen. // // Based on algorithm in The Art of Computer Programming, Volume 2, // Seminumerical Algorithms by Donald E. Knuth, 2nd Edition. In addition // you need to consult the erratas for the book available at: // // http://www-cs-faculty.stanford.edu/~uno/taocp.html var u = WideDecimal(true) var v = WideDecimal(true) // divisor // Simple case if cv.isZero { return .divideByZero; } // If u < v, the result is approximately 0... if cu._length < cv._length { for i in 0..<cv._length { if cu[i] < cv[i] { r._length = 0 return .noError; } } } // Fast algorithm if cv._length == 1 { r = cu let (_,error) = divideByShort(&r, cv[0]) return error } u.copyMantissa(from: cu) v.copyMantissa(from: cv) u._length = cu._length + 1 v._length = cv._length + 1 // D1: Normalize // Calculate d such that d*highest_digit of v >= b/2 (0x8000) // // I could probably use something smarter to get d to be a power of 2. // In this case the multiply below became only a shift. let d: UInt32 = UInt32((1 << 16) / Int(cv[cv._length - 1] + 1)) // This is to make the whole algorithm work and u*d/v*d == u/v _ = multiplyByShort(&u, UInt16(d)) _ = multiplyByShort(&v, UInt16(d)) u.trimTrailingZeros() v.trimTrailingZeros() // Set a zero at the leftmost u position if the multiplication // does not have a carry. if u._length == cu._length { u[u._length] = 0 u._length += 1 } v[v._length] = 0; // Set a zero at the leftmost v position. // the algorithm will use it during the // multiplication/subtraction phase. // Determine the size of the quotient. // It's an approximate value. let ql:UInt16 = UInt16(u._length - v._length) // Some useful constants for the loop // It's used to determine the quotient digit as fast as possible // The test vl > 1 is probably useless, since optimizations // up there are taking over this case. I'll keep it, just in case. let v1:UInt16 = v[v._length-1] let v2:UInt16 = v._length > 1 ? v[v._length-2] : 0 // D2: initialize j // On each pass, build a single value for the quotient. for j in 0..<ql { // D3: calculate q^ // This formula and test for q gives at most q+1; See Knuth for proof. let ul = u._length let tmp:UInt32 = UInt32(u[ul - UInt32(j) - UInt32(1)]) << 16 + UInt32(u[ul - UInt32(j) - UInt32(2)]) var q:UInt32 = tmp / UInt32(v1) // Quotient digit. could be a short. var rtmp:UInt32 = tmp % UInt32(v1) // This test catches all cases where q is really q+2 and // most where it is q+1 if q == (1 << 16) || UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)]) { q -= 1 rtmp += UInt32(v1) if (rtmp < (1 << 16)) && ( (q == (1 << 16) ) || ( UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)])) ) { q -= 1 rtmp += UInt32(v1) } } // D4: multiply and subtract. var mk:UInt32 = 0 // multiply carry var sk:UInt32 = 1 // subtraction carry var acc:UInt32 // We perform a multiplication and a subtraction // during the same pass... for i in 0...v._length { let ul = u._length let vl = v._length acc = q * UInt32(v[i]) + mk // multiply mk = acc >> 16 // multiplication carry acc = acc & 0xffff; acc = 0xffff + UInt32(u[ul - vl + i - UInt32(j) - UInt32(1)]) - acc + sk; // subtract sk = acc >> 16; u[ul - vl + i - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc) } // D5: test remainder // This test catches cases where q is still q + 1 if sk == 0 { // D6: add back. var k:UInt32 = 0 // Addition carry // subtract one from the quotient digit q -= 1 for i in 0...v._length { let ul = u._length let vl = v._length acc = UInt32(v[i]) + UInt32(u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)]) + k k = acc >> 16; u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc) } // k must be == 1 here } r[UInt32(ql - j - UInt16(1))] = UInt16(q) // D7: loop on j } r._length = UInt32(ql); r.trimTrailingZeros() return .noError; } fileprivate func integerMultiplyByPowerOf10<T:VariableLengthNumber>(_ result: inout T, _ left: T, _ p: Int) -> NSDecimalNumber.CalculationError { var power = p if power == 0 { result = left return .noError } let isNegative = power < 0 if isNegative { power = -power } result = left let maxpow10 = pow10.count - 1 var error:NSDecimalNumber.CalculationError = .noError while power > maxpow10 { var big = T() power -= maxpow10 let p10 = pow10[maxpow10] if !isNegative { error = integerMultiply(&big,result,p10) } else { error = integerDivide(&big,result,p10) } if error != .noError && error != .lossOfPrecision { return error; } for i in 0..<big._length { result[i] = big[i] } result._length = big._length } var big = T() // Handle the rest of the power (<= maxpow10) let p10 = pow10[Int(power)] if !isNegative { error = integerMultiply(&big, result, p10) } else { error = integerDivide(&big, result, p10) } for i in 0..<big._length { result[i] = big[i] } result._length = big._length return error; } public func NSDecimalRound(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) { NSDecimalCopy(result,number) // this is unnecessary if they are the same address, but we can't test that here result.pointee.round(scale: scale,roundingMode: roundingMode) } // Rounds num to the given scale using the given mode. // result may be a pointer to same space as num. // scale indicates number of significant digits after the decimal point public func NSDecimalNormalize(_ a: UnsafeMutablePointer<Decimal>, _ b: UnsafeMutablePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { var diffexp = a.pointee.__exponent - b.pointee.__exponent var result = Decimal() // // If the two numbers share the same exponents, // the normalisation is already done // if diffexp == 0 { return .noError } // // Put the smallest of the two in aa // var aa: UnsafeMutablePointer<Decimal> var bb: UnsafeMutablePointer<Decimal> if diffexp < 0 { aa = b bb = a diffexp = -diffexp } else { aa = a bb = b } // // Build a backup for aa // var backup = Decimal() NSDecimalCopy(&backup,aa) // // Try to multiply aa to reach the same exponent level than bb // if integerMultiplyByPowerOf10(&result, aa.pointee, Int(diffexp)) == .noError { // Succeed. Adjust the length/exponent info // and return no errorNSDecimalNormalize aa.pointee.copyMantissa(from: result) aa.pointee._exponent = bb.pointee._exponent return .noError; } // // Failed, restart from scratch // NSDecimalCopy(aa, &backup); // // What is the maximum pow10 we can apply to aa ? // let logBase10of2to16 = 4.81647993 let aaLength = aa.pointee._length let maxpow10 = Int8(floor(Double(Decimal.maxSize - aaLength) * logBase10of2to16)) // // Divide bb by this value // _ = integerMultiplyByPowerOf10(&result, bb.pointee, Int(maxpow10 - diffexp)) bb.pointee.copyMantissa(from: result) bb.pointee._exponent -= Int32(maxpow10 - diffexp); // // If bb > 0 multiply aa by the same value // if !bb.pointee.isZero { _ = integerMultiplyByPowerOf10(&result, aa.pointee, Int(maxpow10)) aa.pointee.copyMantissa(from: result) aa.pointee._exponent -= Int32(maxpow10) } else { bb.pointee._exponent = aa.pointee._exponent; } // // the two exponents are now identical, but we've lost some digits in the operation. // return .lossOfPrecision; } public func NSDecimalAdd(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN { result.pointee.setNaN() return .overflow } if leftOperand.pointee.isZero { NSDecimalCopy(result, rightOperand) return .noError } else if rightOperand.pointee.isZero { NSDecimalCopy(result, leftOperand) return .noError } else { var a = Decimal() var b = Decimal() var error:NSDecimalNumber.CalculationError = .noError NSDecimalCopy(&a,leftOperand) NSDecimalCopy(&b,rightOperand) let normalizeError = NSDecimalNormalize(&a, &b,roundingMode) if a.isZero { NSDecimalCopy(result,&b) return normalizeError } if b.isZero { NSDecimalCopy(result,&a) return normalizeError } result.pointee._exponent = a._exponent if a.isNegative == b.isNegative { var big = WideDecimal() result.pointee.isNegative = a.isNegative // No possible error here. _ = integerAdd(&big,&a,&b) if big._length > Decimal.maxSize { var exponent:Int32 = 0 error = fitMantissa(&big, &exponent, roundingMode) let newExponent = result.pointee._exponent + exponent // Just to be sure! if newExponent > Int32(Int8.max) { result.pointee.setNaN() return .overflow } result.pointee._exponent = newExponent } let length = min(Decimal.maxSize,big._length) for i in 0..<length { result.pointee[i] = big[i] } result.pointee._length = length } else { // not the same sign let comparison = mantissaCompare(a,b) switch comparison { case .orderedSame: result.pointee.setZero() case .orderedAscending: _ = integerSubtract(&result.pointee,&b,&a) result.pointee.isNegative = b.isNegative case .orderedDescending: _ = integerSubtract(&result.pointee,&a,&b) result.pointee.isNegative = a.isNegative } } result.pointee._isCompact = 0 NSDecimalCompact(result) return error == .noError ? normalizeError : error } } fileprivate func integerAdd(_ result: inout WideDecimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError { var idx: UInt32 = 0 var carry: UInt16 = 0 let maxIndex: UInt32 = min(left._length, right._length) // The highest index with bits set in both values while idx < maxIndex { let li = UInt32(left[idx]) let ri = UInt32(right[idx]) let sum = li + ri + UInt32(carry) carry = UInt16(truncatingIfNeeded: sum >> 16) result[idx] = UInt16(truncatingIfNeeded: sum) idx += 1 } while idx < left._length { if carry != 0 { let li = UInt32(left[idx]) let sum = li + UInt32(carry) carry = UInt16(truncatingIfNeeded: sum >> 16) result[idx] = UInt16(truncatingIfNeeded: sum) idx += 1 } else { while idx < left._length { result[idx] = left[idx] idx += 1 } break } } while idx < right._length { if carry != 0 { let ri = UInt32(right[idx]) let sum = ri + UInt32(carry) carry = UInt16(truncatingIfNeeded: sum >> 16) result[idx] = UInt16(truncatingIfNeeded: sum) idx += 1 } else { while idx < right._length { result[idx] = right[idx] idx += 1 } break } } result._length = idx if carry != 0 { result[idx] = carry idx += 1 result._length = idx } if idx > Decimal.maxSize { return .overflow } return .noError; } // integerSubtract: Subtract b from a, put the result in result, and // modify resultLen to match the length of the result. // Result may be a pointer to same space as a or b. // resultLen must be >= Max(aLen,bLen). // Could return NSCalculationOverflow if b > a. In this case 0 - result // give b-a... // fileprivate func integerSubtract(_ result: inout Decimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError { var idx: UInt32 = 0 let maxIndex: UInt32 = min(left._length, right._length) // The highest index with bits set in both values var borrow: UInt16 = 0 while idx < maxIndex { let li = UInt32(left[idx]) let ri = UInt32(right[idx]) // 0x10000 is to borrow in advance to avoid underflow. let difference: UInt32 = (0x10000 + li) - UInt32(borrow) - ri result[idx] = UInt16(truncatingIfNeeded: difference) // borrow = 1 if the borrow was used. borrow = 1 - UInt16(truncatingIfNeeded: difference >> 16) idx += 1 } while idx < left._length { if borrow != 0 { let li = UInt32(left[idx]) let sum = 0xffff + li // + no carry borrow = 1 - UInt16(truncatingIfNeeded: sum >> 16) result[idx] = UInt16(truncatingIfNeeded: sum) idx += 1 } else { while idx < left._length { result[idx] = left[idx] idx += 1 } break } } while idx < right._length { let ri = UInt32(right[idx]) let difference = 0xffff - ri + UInt32(borrow) borrow = 1 - UInt16(truncatingIfNeeded: difference >> 16) result[idx] = UInt16(truncatingIfNeeded: difference) idx += 1 } if borrow != 0 { return .overflow } result._length = idx; result.trimTrailingZeros() return .noError; } // Exact operations. result may be a pointer to same space as leftOperand or rightOperand public func NSDecimalSubtract(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { var r = rightOperand.pointee r.negate() return NSDecimalAdd(result, leftOperand, &r, roundingMode) } // Exact operations. result may be a pointer to same space as leftOperand or rightOperand public func NSDecimalMultiply(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN { result.pointee.setNaN() return .overflow } if leftOperand.pointee.isZero || rightOperand.pointee.isZero { result.pointee.setZero() return .noError } var big = WideDecimal() var calculationError:NSDecimalNumber.CalculationError = .noError calculationError = integerMultiply(&big,WideDecimal(leftOperand.pointee),rightOperand.pointee) result.pointee._isNegative = (leftOperand.pointee._isNegative + rightOperand.pointee._isNegative) % 2 var newExponent = leftOperand.pointee._exponent + rightOperand.pointee._exponent if big._length > Decimal.maxSize { var exponent:Int32 = 0 calculationError = fitMantissa(&big, &exponent, roundingMode) newExponent += exponent } for i in 0..<big._length { result.pointee[i] = big[i] } result.pointee._length = big._length result.pointee._isCompact = 0 if newExponent > Int32(Int8.max) { result.pointee.setNaN() return .overflow } result.pointee._exponent = newExponent NSDecimalCompact(result) return calculationError } // Exact operations. result may be a pointer to same space as leftOperand or rightOperand public func NSDecimalDivide(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN { result.pointee.setNaN() return .overflow } if rightOperand.pointee.isZero { result.pointee.setNaN() return .divideByZero } if leftOperand.pointee.isZero { result.pointee.setZero() return .noError } var a = Decimal() var b = Decimal() var big = WideDecimal() var exponent:Int32 = 0 NSDecimalCopy(&a, leftOperand) NSDecimalCopy(&b, rightOperand) /* If the precision of the left operand is much smaller * than that of the right operand (for example, * 20 and 0.112314123094856724234234572), then the * difference in their exponents is large and a lot of * precision will be lost below. This is particularly * true as the difference approaches 38 or larger. * Normalizing here looses some precision on the * individual operands, but often produces a more * accurate result later. I chose 19 arbitrarily * as half of the magic 38, so that normalization * doesn't always occur. */ if (19 <= Int(a._exponent - b._exponent)) { _ = NSDecimalNormalize(&a, &b, roundingMode); /* We ignore the small loss of precision this may * induce in the individual operands. */ /* Sometimes the normalization done previously is inappropriate and * forces one of the operands to 0. If this happens, restore both. */ if a.isZero || b.isZero { NSDecimalCopy(&a, leftOperand); NSDecimalCopy(&b, rightOperand); } } _ = integerMultiplyByPowerOf10(&big, WideDecimal(a), 38) // Trust me, it's 38 ! _ = integerDivide(&big, big, b) _ = fitMantissa(&big, &exponent, .down) let length = min(big._length,Decimal.maxSize) for i in 0..<length { result.pointee[i] = big[i] } result.pointee._length = length result.pointee.isNegative = a._isNegative != b._isNegative exponent = a._exponent - b._exponent - 38 + exponent if exponent < Int32(Int8.min) { result.pointee.setNaN() return .underflow } if exponent > Int32(Int8.max) { result.pointee.setNaN() return .overflow; } result.pointee._exponent = Int32(exponent) result.pointee._isCompact = 0 NSDecimalCompact(result) return .noError } // Division could be silently inexact; // Exact operations. result may be a pointer to same space as leftOperand or rightOperand public func NSDecimalPower(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { if number.pointee.isNaN { result.pointee.setNaN() return .overflow } NSDecimalCopy(result,number) return result.pointee.power(UInt(power), roundingMode:roundingMode) } public func NSDecimalMultiplyByPowerOf10(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int16, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError { NSDecimalCopy(result,number) return result.pointee.multiply(byPowerOf10: power) } public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: Any?) -> String { guard locale == nil else { fatalError("Locale not supported: \(locale!)") } return dcm.pointee.description } private func multiplyBy10(_ dcm: inout Decimal, andAdd extra:Int) -> NSDecimalNumber.CalculationError { let backup = dcm if multiplyByShort(&dcm, 10) == .noError && addShort(&dcm, UInt16(extra)) == .noError { return .noError } else { dcm = backup // restore the old values return .overflow // this is the only possible error } } fileprivate protocol VariableLengthNumber { var _length: UInt32 { get set } init() subscript(index:UInt32) -> UInt16 { get set } var isZero:Bool { get } mutating func copyMantissa<T:VariableLengthNumber>(from other:T) mutating func zeroMantissa() mutating func trimTrailingZeros() var maxMantissaLength: UInt32 { get } } extension Decimal: VariableLengthNumber { var maxMantissaLength:UInt32 { return Decimal.maxSize } fileprivate mutating func zeroMantissa() { for i in 0..<Decimal.maxSize { self[i] = 0 } } internal mutating func trimTrailingZeros() { if _length > Decimal.maxSize { _length = Decimal.maxSize } while _length != 0 && self[_length - 1] == 0 { _length -= 1 } } fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) { if other._length > maxMantissaLength { for i in maxMantissaLength..<other._length { guard other[i] == 0 else { fatalError("Loss of precision during copy other[\(i)] \(other[i]) != 0") } } } let length = min(other._length, maxMantissaLength) for i in 0..<length { self[i] = other[i] } self._length = length self._isCompact = 0 } } // Provides a way with dealing with extra-length decimals, used for calculations fileprivate struct WideDecimal : VariableLengthNumber { var maxMantissaLength:UInt32 { return _extraWide ? 17 : 16 } fileprivate mutating func zeroMantissa() { for i in 0..<maxMantissaLength { self[i] = 0 } } fileprivate mutating func trimTrailingZeros() { while _length != 0 && self[_length - 1] == 0 { _length -= 1 } } init() { self.init(false) } fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) { let length = other is Decimal ? min(other._length,Decimal.maxSize) : other._length for i in 0..<length { self[i] = other[i] } self._length = length } var isZero: Bool { return _length == 0 } var __length: UInt16 var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) // Most uses of this class use 16 shorts, but integer division uses 17 shorts var _extraWide: Bool var _length: UInt32 { get { return UInt32(__length) } set { guard newValue <= maxMantissaLength else { fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)") } __length = UInt16(newValue) } } init(_ extraWide:Bool = false) { __length = 0 _mantissa = (UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0)) _extraWide = extraWide } init(_ decimal:Decimal) { self.__length = UInt16(decimal._length) self._extraWide = false self._mantissa = (decimal[0],decimal[1],decimal[2],decimal[3],decimal[4],decimal[5],decimal[6],decimal[7],UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0)) } subscript(index:UInt32) -> UInt16 { get { switch index { case 0: return _mantissa.0 case 1: return _mantissa.1 case 2: return _mantissa.2 case 3: return _mantissa.3 case 4: return _mantissa.4 case 5: return _mantissa.5 case 6: return _mantissa.6 case 7: return _mantissa.7 case 8: return _mantissa.8 case 9: return _mantissa.9 case 10: return _mantissa.10 case 11: return _mantissa.11 case 12: return _mantissa.12 case 13: return _mantissa.13 case 14: return _mantissa.14 case 15: return _mantissa.15 case 16 where _extraWide: return _mantissa.16 // used in integerDivide default: fatalError("Invalid index \(index) for _mantissa") } } set { switch index { case 0: _mantissa.0 = newValue case 1: _mantissa.1 = newValue case 2: _mantissa.2 = newValue case 3: _mantissa.3 = newValue case 4: _mantissa.4 = newValue case 5: _mantissa.5 = newValue case 6: _mantissa.6 = newValue case 7: _mantissa.7 = newValue case 8: _mantissa.8 = newValue case 9: _mantissa.9 = newValue case 10: _mantissa.10 = newValue case 11: _mantissa.11 = newValue case 12: _mantissa.12 = newValue case 13: _mantissa.13 = newValue case 14: _mantissa.14 = newValue case 15: _mantissa.15 = newValue case 16 where _extraWide: _mantissa.16 = newValue default: fatalError("Invalid index \(index) for _mantissa") } } } func toDecimal() -> Decimal { var result = Decimal() result._length = self._length for i in 0..<_length { result[i] = self[i] } return result } } // == Internal (Swifty) functions == extension Decimal { fileprivate var isCompact: Bool { get { return _isCompact != 0 } set { _isCompact = newValue ? 1 : 0 } } fileprivate var isNegative: Bool { get { return _isNegative != 0 } set { _isNegative = newValue ? 1 : 0 } } fileprivate mutating func compact() { if isCompact || isNaN || _length == 0 { return } var newExponent = self._exponent var remainder: UInt16 = 0 // Divide by 10 as much as possible repeat { (remainder,_) = divideByShort(&self,10) newExponent += 1 } while remainder == 0 // Put the non-empty remainder in place _ = multiplyByShort(&self,10) _ = addShort(&self,remainder) newExponent -= 1 // Set the new exponent while newExponent > Int32(Int8.max) { _ = multiplyByShort(&self,10) newExponent -= 1 } _exponent = newExponent isCompact = true } fileprivate mutating func round(scale:Int, roundingMode:RoundingMode) { // scale is the number of digits after the decimal point var s = Int32(scale) + _exponent if s == NSDecimalNoScale || s >= 0 { return } s = -s var remainder: UInt16 = 0 var previousRemainder = false let negative = _isNegative != 0 var newExponent = _exponent + s while s > 4 { if remainder != 0 { previousRemainder = true } (remainder,_) = divideByShort(&self, 10000) s -= 4 } while s > 0 { if remainder != 0 { previousRemainder = true } (remainder,_) = divideByShort(&self, 10) s -= 1 } // If we are on a tie, adjust with premdr. .50001 is equivalent to .6 if previousRemainder && (remainder == 0 || remainder == 5) { remainder += 1; } if remainder != 0 { if negative { switch roundingMode { case .up: break case .bankers: if remainder == 5 && (self[0] & 1) == 0 { remainder += 1 } fallthrough case .plain: if remainder < 5 { break } fallthrough case .down: _ = addShort(&self, 1) } if _length == 0 { _isNegative = 0; } } else { switch roundingMode { case .down: break case .bankers: if remainder == 5 && (self[0] & 1) == 0 { remainder -= 1 } fallthrough case .plain: if remainder < 5 { break } fallthrough case .up: _ = addShort(&self, 1) } } } _isCompact = 0; while newExponent > Int32(Int8.max) { newExponent -= 1; _ = multiplyByShort(&self, 10); } _exponent = newExponent; self.compact(); } internal func compare(to other:Decimal) -> ComparisonResult { // NaN is a special case and is arbitrary ordered before everything else // Conceptually comparing with NaN is bogus anyway but raising or // always returning the same answer will confuse the sorting algorithms if self.isNaN { return other.isNaN ? .orderedSame : .orderedAscending } if other.isNaN { return .orderedDescending } // Check the sign if self._isNegative > other._isNegative { return .orderedAscending } if self._isNegative < other._isNegative { return .orderedDescending } // If one of the two is == 0, the other is bigger // because 0 implies isNegative = 0... if self.isZero && other.isZero { return .orderedSame } if self.isZero { return .orderedAscending } if other.isZero { return .orderedDescending } var selfNormal = self var otherNormal = other _ = NSDecimalNormalize(&selfNormal, &otherNormal, .down) let comparison = mantissaCompare(selfNormal,otherNormal) if selfNormal._isNegative == 1 { if comparison == .orderedDescending { return .orderedAscending } else if comparison == .orderedAscending { return .orderedDescending } else { return .orderedSame } } return comparison } fileprivate subscript(index:UInt32) -> UInt16 { get { switch index { case 0: return _mantissa.0 case 1: return _mantissa.1 case 2: return _mantissa.2 case 3: return _mantissa.3 case 4: return _mantissa.4 case 5: return _mantissa.5 case 6: return _mantissa.6 case 7: return _mantissa.7 default: fatalError("Invalid index \(index) for _mantissa") } } set { switch index { case 0: _mantissa.0 = newValue case 1: _mantissa.1 = newValue case 2: _mantissa.2 = newValue case 3: _mantissa.3 = newValue case 4: _mantissa.4 = newValue case 5: _mantissa.5 = newValue case 6: _mantissa.6 = newValue case 7: _mantissa.7 = newValue default: fatalError("Invalid index \(index) for _mantissa") } } } fileprivate mutating func setNaN() { _length = 0 _isNegative = 1 } fileprivate mutating func setZero() { _length = 0 _isNegative = 0 } fileprivate mutating func multiply(byPowerOf10 power:Int16) -> CalculationError { if isNaN { return .overflow } if isZero { return .noError } let newExponent = _exponent + Int32(power) if newExponent < Int32(Int8.min) { setNaN() return .underflow } if newExponent > Int32(Int8.max) { setNaN() return .overflow } _exponent = newExponent return .noError } fileprivate mutating func power(_ p:UInt, roundingMode:RoundingMode) -> CalculationError { if isNaN { return .overflow } var power = p if power == 0 { _exponent = 0 _length = 1 _isNegative = 0 self[0] = 1 _isCompact = 1 return .noError } else if power == 1 { return .noError } var temporary = Decimal(1) var error:CalculationError = .noError while power > 1 { if power % 2 == 1 { let previousError = error var leftOp = temporary error = NSDecimalMultiply(&temporary, &leftOp, &self, roundingMode) if previousError != .noError { // FIXME is this the intent? error = previousError } if error == .overflow || error == .underflow { setNaN() return error } power -= 1 } if power != 0 { let previousError = error var leftOp = self var rightOp = self error = NSDecimalMultiply(&self, &leftOp, &rightOp, roundingMode) if previousError != .noError { // FIXME is this the intent? error = previousError } if error == .overflow || error == .underflow { setNaN() return error } power /= 2 } } let previousError = error var rightOp = self error = NSDecimalMultiply(&self, &temporary, &rightOp, roundingMode) if previousError != .noError { // FIXME is this the intent? error = previousError } if error == .overflow || error == .underflow { setNaN() return error } return error } } fileprivate let pow10 = [ /*^00*/ Decimal(length: 1, mantissa:( 0x0001,0,0,0,0,0,0,0)), /*^01*/ Decimal(length: 1, mantissa:( 0x000a,0,0,0,0,0,0,0)), /*^02*/ Decimal(length: 1, mantissa:( 0x0064,0,0,0,0,0,0,0)), /*^03*/ Decimal(length: 1, mantissa:( 0x03e8,0,0,0,0,0,0,0)), /*^04*/ Decimal(length: 1, mantissa:( 0x2710,0,0,0,0,0,0,0)), /*^05*/ Decimal(length: 2, mantissa:( 0x86a0, 0x0001,0,0,0,0,0,0)), /*^06*/ Decimal(length: 2, mantissa:( 0x4240, 0x000f,0,0,0,0,0,0)), /*^07*/ Decimal(length: 2, mantissa:( 0x9680, 0x0098,0,0,0,0,0,0)), /*^08*/ Decimal(length: 2, mantissa:( 0xe100, 0x05f5,0,0,0,0,0,0)), /*^09*/ Decimal(length: 2, mantissa:( 0xca00, 0x3b9a,0,0,0,0,0,0)), /*^10*/ Decimal(length: 3, mantissa:( 0xe400, 0x540b, 0x0002,0,0,0,0,0)), /*^11*/ Decimal(length: 3, mantissa:( 0xe800, 0x4876, 0x0017,0,0,0,0,0)), /*^12*/ Decimal(length: 3, mantissa:( 0x1000, 0xd4a5, 0x00e8,0,0,0,0,0)), /*^13*/ Decimal(length: 3, mantissa:( 0xa000, 0x4e72, 0x0918,0,0,0,0,0)), /*^14*/ Decimal(length: 3, mantissa:( 0x4000, 0x107a, 0x5af3,0,0,0,0,0)), /*^15*/ Decimal(length: 4, mantissa:( 0x8000, 0xa4c6, 0x8d7e, 0x0003,0,0,0,0)), /*^16*/ Decimal(length: 4, mantissa:( 0x0000, 0x6fc1, 0x86f2, 0x0023,0,0,0,0)), /*^17*/ Decimal(length: 4, mantissa:( 0x0000, 0x5d8a, 0x4578, 0x0163,0,0,0,0)), /*^18*/ Decimal(length: 4, mantissa:( 0x0000, 0xa764, 0xb6b3, 0x0de0,0,0,0,0)), /*^19*/ Decimal(length: 4, mantissa:( 0x0000, 0x89e8, 0x2304, 0x8ac7,0,0,0,0)), /*^20*/ Decimal(length: 5, mantissa:( 0x0000, 0x6310, 0x5e2d, 0x6bc7, 0x0005,0,0,0)), /*^21*/ Decimal(length: 5, mantissa:( 0x0000, 0xdea0, 0xadc5, 0x35c9, 0x0036,0,0,0)), /*^22*/ Decimal(length: 5, mantissa:( 0x0000, 0xb240, 0xc9ba, 0x19e0, 0x021e,0,0,0)), /*^23*/ Decimal(length: 5, mantissa:( 0x0000, 0xf680, 0xe14a, 0x02c7, 0x152d,0,0,0)), /*^24*/ Decimal(length: 5, mantissa:( 0x0000, 0xa100, 0xcced, 0x1bce, 0xd3c2,0,0,0)), /*^25*/ Decimal(length: 6, mantissa:( 0x0000, 0x4a00, 0x0148, 0x1614, 0x4595, 0x0008,0,0)), /*^26*/ Decimal(length: 6, mantissa:( 0x0000, 0xe400, 0x0cd2, 0xdcc8, 0xb7d2, 0x0052,0,0)), /*^27*/ Decimal(length: 6, mantissa:( 0x0000, 0xe800, 0x803c, 0x9fd0, 0x2e3c, 0x033b,0,0)), /*^28*/ Decimal(length: 6, mantissa:( 0x0000, 0x1000, 0x0261, 0x3e25, 0xce5e, 0x204f,0,0)), /*^29*/ Decimal(length: 7, mantissa:( 0x0000, 0xa000, 0x17ca, 0x6d72, 0x0fae, 0x431e, 0x0001,0)), /*^30*/ Decimal(length: 7, mantissa:( 0x0000, 0x4000, 0xedea, 0x4674, 0x9cd0, 0x9f2c, 0x000c,0)), /*^31*/ Decimal(length: 7, mantissa:( 0x0000, 0x8000, 0x4b26, 0xc091, 0x2022, 0x37be, 0x007e,0)), /*^32*/ Decimal(length: 7, mantissa:( 0x0000, 0x0000, 0xef81, 0x85ac, 0x415b, 0x2d6d, 0x04ee,0)), /*^33*/ Decimal(length: 7, mantissa:( 0x0000, 0x0000, 0x5b0a, 0x38c1, 0x8d93, 0xc644, 0x314d,0)), /*^34*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x8e64, 0x378d, 0x87c0, 0xbead, 0xed09, 0x0001)), /*^35*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x8fe8, 0x2b87, 0x4d82, 0x72c7, 0x4261, 0x0013)), /*^36*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x9f10, 0xb34b, 0x0715, 0x7bc9, 0x97ce, 0x00c0)), /*^37*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x36a0, 0x00f4, 0x46d9, 0xd5da, 0xee10, 0x0785)), /*^38*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x2240, 0x098a, 0xc47a, 0x5a86, 0x4ca8, 0x4b3b)) /*^39 is on 9 shorts. */ ] // Copied from Scanner.swift private func decimalSep(_ locale: Locale?) -> String { if let loc = locale { if let sep = loc._bridgeToObjectiveC().object(forKey: .decimalSeparator) as? NSString { return sep._swiftObject } return "." } else { return decimalSep(Locale.current) } } // Copied from Scanner.swift private func isADigit(_ ch: unichar) -> Bool { struct Local { static let set = CharacterSet.decimalDigits } return Local.set.contains(UnicodeScalar(ch)!) } // Copied from Scanner.swift private func numericValue(_ ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else { return __CFCharDigitValue(UniChar(ch)) } } // Could be silently inexact for float and double. extension Scanner { public func scanDecimal(_ dcm: inout Decimal) -> Bool { if let result = scanDecimal() { dcm = result return true } else { return false } } public func scanDecimal() -> Decimal? { var result = Decimal() let string = self._scanString let length = string.length var buf = _NSStringBuffer(string: string, start: self._scanLocation, end: length) let ds_chars = decimalSep(locale).utf16 let ds = ds_chars[ds_chars.startIndex] buf.skip(_skipSet) var neg = false if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(_skipSet) } guard isADigit(buf.currentCharacter) else { return nil } var tooBig = false // build the mantissa repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError { tooBig = true if result._exponent == Int32(Int8.max) { repeat { buf.advance() } while isADigit(buf.currentCharacter) return Decimal.nan } result._exponent += 1 } buf.advance() } while isADigit(buf.currentCharacter) // get the decimal point if buf.currentCharacter == ds { buf.advance() // continue to build the mantissa repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError { tooBig = true } else { if result._exponent == Int32(Int8.min) { repeat { buf.advance() } while isADigit(buf.currentCharacter) return Decimal.nan } result._exponent -= 1 } buf.advance() } while isADigit(buf.currentCharacter) } if buf.currentCharacter == unichar(unicodeScalarLiteral: "e") || buf.currentCharacter == unichar(unicodeScalarLiteral: "E") { var exponentIsNegative = false var exponent: Int32 = 0 buf.advance() if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") { exponentIsNegative = true buf.advance() } else if buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { buf.advance() } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } exponent = 10 * exponent + Int32(numeral) guard exponent <= 2*Int32(Int8.max) else { return Decimal.nan } buf.advance() } while isADigit(buf.currentCharacter) if exponentIsNegative { exponent = -exponent } exponent += result._exponent guard exponent >= Int32(Int8.min) && exponent <= Int32(Int8.max) else { return Decimal.nan } result._exponent = exponent } result.isNegative = neg // if we get to this point, and have NaN, then the input string was probably "-0" // or some variation on that, and normalize that to zero. if result.isNaN { result = Decimal(0) } result.compact() self._scanLocation = buf.location return result } } extension Decimal : Codable { private enum CodingKeys : Int, CodingKey { case exponent case length case isNegative case isCompact case mantissa } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let exponent = try container.decode(CInt.self, forKey: .exponent) let length = try container.decode(CUnsignedInt.self, forKey: .length) let isNegative = try container.decode(Bool.self, forKey: .isNegative) let isCompact = try container.decode(Bool.self, forKey: .isCompact) var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa) var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0) mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self) mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self) self.init(_exponent: exponent, _length: length, _isNegative: CUnsignedInt(isNegative ? 1 : 0), _isCompact: CUnsignedInt(isCompact ? 1 : 0), _reserved: 0, _mantissa: mantissa) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(_exponent, forKey: .exponent) try container.encode(_length, forKey: .length) try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative) try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact) var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa) try mantissaContainer.encode(_mantissa.0) try mantissaContainer.encode(_mantissa.1) try mantissaContainer.encode(_mantissa.2) try mantissaContainer.encode(_mantissa.3) try mantissaContainer.encode(_mantissa.4) try mantissaContainer.encode(_mantissa.5) try mantissaContainer.encode(_mantissa.6) try mantissaContainer.encode(_mantissa.7) } }
apache-2.0
eb49e50550c2d7994374d5f8d2da6c1b
32.347248
233
0.564329
4.144641
false
false
false
false
KeithPiTsui/Pavers
Pavers/Sources/UI/Base/NSLayoutConstraint+Reporting.swift
1
2521
// // NSLayoutConstraint+Reporting.swift // Pavers // // Created by Pi on 28/08/2017. // Copyright © 2017 Keith. All rights reserved. // import Foundation import PaversFRP extension NSLayoutConstraint { // public var equation: String { // // let fstViewName = self.fisrtView.identification // let fstAttr = self.firstAttribute.stringValue // let fstStr = "\(fstViewName).\(fstAttr)" // // let relStr = self.relation.stringValue // // guard let sndView = self.secondView else { return "\(fstStr) \(relStr) \(self.constant)" } // // let sndViewName = sndView.identification // let sndAttr = self.secondAttribute.stringValue // let sndStr = "\(sndViewName).\(sndAttr)" // // let rhsVariablePart = self.multiplier == 1 // ? sndStr // : "\(sndStr) * \(self.multiplier)" // // let constantString = "\((self.constant.sign as NumericSign).symbol) \(self.constant.abs())" // // let rhs = self.constant == 0 ? rhsVariablePart : "\(rhsVariablePart) \(constantString)" // // return "\(fstStr) \(relStr) \(rhs)" // } // open override var description: String { // let active = self.isActive ? "Active" : "Inactive" // return "<\(self.identification) \(self.equation) (\(active))>" // } } extension NSLayoutConstraint.Attribute { public var stringValue: String { switch self { case .left: return "left" case .right: return "right" case .top: return "top" case .bottom: return "bottom" case .leading: return "leading" case .trailing: return "trailing" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .lastBaseline: return "lastBaseline" case .firstBaseline: return "firstBaseline" case .leftMargin: return "leftMargin" case .rightMargin: return "rightMargin" case .topMargin: return "topMargin" case .bottomMargin: return "bottomMargin" case .leadingMargin: return "leadingMargin" case .trailingMargin: return "trailingMargin" case .centerXWithinMargins: return "centerXWithinMargins" case .centerYWithinMargins: return "centerYWithinMargins" case .notAnAttribute: return "notAnAttribute" @unknown default: fatalError() } } } extension NSLayoutConstraint.Relation { public var stringValue: String { switch self { case .lessThanOrEqual: return "<=" case .equal: return "==" case .greaterThanOrEqual: return ">=" @unknown default: fatalError() } } }
mit
a9dd3cacbedf608ec8873e34e351d71e
27.636364
97
0.66627
4
false
false
false
false
JGiola/swift
test/SILGen/boxed_existentials.swift
1
12458
// RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle %s | %FileCheck %s // RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle %s | %FileCheck %s --check-prefix=GUARANTEED func test_type_lowering(_ x: Error) { } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@guaranteed Error) -> () { // CHECK-NOT: destroy_value %0 : $Error class Document {} enum ClericalError: Error { case MisplacedDocument(Document) var _domain: String { return "" } var _code: Int { return 0 } } func test_concrete_erasure(_ x: ClericalError) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials21test_concrete_erasureys5Error_pAA08ClericalF0OF // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClericalError): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError // CHECK: [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error // CHECK: store [[EXISTENTIAL]] to [init] [[EXISTENTIAL_BUF:%.*]] : // CHECK: store [[ARG_COPY]] to [init] [[ADDR]] : $*ClericalError // CHECK-NOT: destroy_value [[ARG]] // CHECK: [[EXISTENTIAL2:%.*]] = load [take] [[EXISTENTIAL_BUF]] // CHECK: return [[EXISTENTIAL2]] : $Error protocol HairType {} func test_composition_erasure(_ x: HairType & Error) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials24test_composition_erasureys5Error_psAC_AA8HairTypepF // CHECK: [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*, Error & HairType\) Self]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: store [[NEW_EXISTENTIAL]] to [init] [[NEW_EXISTENTIALBUF:%.*]] : // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[ADDR]] // CHECK-NOT: destroy_addr [[OLD_EXISTENTIAL]] // CHECK: [[NEW_EXISTENTIAL2:%.*]] = load [take] [[NEW_EXISTENTIALBUF]] // CHECK: return [[NEW_EXISTENTIAL2]] protocol HairClass: class {} func test_class_composition_erasure(_ x: HairClass & Error) -> Error { return x } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials30test_class_composition_erasureys5Error_psAC_AA9HairClasspF // CHECK: [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*, Error & HairClass\) Self]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: store [[NEW_EXISTENTIAL]] to [init] [[NEW_EXISTENTIALBUF:%.*]] : // CHECK: [[COPIED_VALUE:%.*]] = copy_value [[VALUE]] // CHECK: store [[COPIED_VALUE]] to [init] [[ADDR]] // CHECK: [[NEW_EXISTENTIAL2:%.*]] = load [take] [[NEW_EXISTENTIALBUF]] // CHECK: return [[NEW_EXISTENTIAL2]] func test_property(_ x: Error) -> String { return x._domain } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials13test_propertyySSs5Error_pF // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*, Error\) Self]] // FIXME: Extraneous copy here // CHECK-NEXT: [[COPY:%[0-9]+]] = alloc_stack $[[VALUE_TYPE]] // CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[COPY]] : $*[[VALUE_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter // -- self parameter of witness is @in_guaranteed; no need to copy since // value in box is immutable and box is guaranteed // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]]) // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] func test_property_of_lvalue(_ x: Error) -> String { var x = x return x._domain } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials23test_property_of_lvalueySSs5Error_pF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VAR:%.*]] = alloc_box ${ var Error } // CHECK: [[VAR_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[VAR]] // CHECK: [[PVAR:%.*]] = project_box [[VAR_LIFETIME]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Error // CHECK: store [[ARG_COPY]] to [init] [[PVAR]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PVAR]] : $*Error // CHECK: [[VALUE_BOX:%.*]] = load [copy] [[ACCESS]] // CHECK: [[BORROWED_VALUE_BOX:%.*]] = begin_borrow [[VALUE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_VALUE_BOX]] : $Error to $*[[VALUE_TYPE:@opened\(.*, Error\) Self]] // CHECK: [[COPY:%.*]] = alloc_stack $[[VALUE_TYPE]] // CHECK: copy_addr [[VALUE]] to [initialization] [[COPY]] // CHECK: destroy_value [[VALUE_BOX]] // CHECK: [[BORROW:%.*]] = alloc_stack $[[VALUE_TYPE]] // CHECK: copy_addr [[COPY]] to [initialization] [[BORROW]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[BORROW]]) // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: end_borrow [[VAR_LIFETIME]] // CHECK: destroy_value [[VAR]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '$s18boxed_existentials23test_property_of_lvalueySSs5Error_pF' extension Error { func extensionMethod() { } } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials21test_extension_methodyys5Error_pF func test_extension_method(_ error: Error) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_addr [[COPY]] // CHECK-NOT: destroy_addr [[VALUE]] // CHECK-NOT: destroy_addr [[VALUE]] // -- destroy_value the owned argument // CHECK-NOT: destroy_value %0 error.extensionMethod() } func plusOneError() -> Error { } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // GUARANTEED-LABEL: sil hidden [ossa] @$s18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // CHECK: bb0([[ARG0:%.*]]: @guaranteed $Error, // GUARANTEED: bb0([[ARG0:%.*]]: @guaranteed $Error, func test_open_existential_semantics(_ guaranteed: Error, _ immediate: Error) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[IMMEDIATE_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[IMMEDIATE_BOX]] // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_LIFETIME]] // GUARANTEED: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // GUARANTEED: [[IMMEDIATE_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[IMMEDIATE_BOX]] // GUARANTEED: [[PB:%.*]] = project_box [[IMMEDIATE_LIFETIME]] // CHECK-NOT: copy_value [[ARG0]] // CHECK: [[VALUE:%.*]] = open_existential_box [[ARG0]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_value [[ARG0]] // GUARANTEED-NOT: copy_value [[ARG0]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[ARG0]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED-NOT: destroy_value [[ARG0]] guaranteed.extensionMethod() // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // CHECK: [[IMMEDIATE_BORROW:%.*]] = begin_borrow [[IMMEDIATE]] // CHECK: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE_BORROW]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // -- end the guarantee // -- TODO: could in theory do this sooner, after the value's been copied // out. // CHECK: destroy_value [[IMMEDIATE]] // GUARANTEED: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // GUARANTEED: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // GUARANTEED: [[BORROWED_IMMEDIATE:%.*]] = begin_borrow [[IMMEDIATE]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_IMMEDIATE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // -- end the guarantee // GUARANTEED: destroy_value [[IMMEDIATE]] immediate.extensionMethod() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[PLUS_ONE_BORROW:%.*]] = begin_borrow [[PLUS_ONE]] // CHECK: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE_BORROW]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[PLUS_ONE]] // GUARANTEED: [[F:%.*]] = function_ref {{.*}}plusOneError // GUARANTEED: [[PLUS_ONE:%.*]] = apply [[F]]() // GUARANTEED: [[BORROWED_PLUS_ONE:%.*]] = begin_borrow [[PLUS_ONE]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_PLUS_ONE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED: destroy_value [[PLUS_ONE]] plusOneError().extensionMethod() } // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials14erasure_to_anyyyps5Error_p_sAC_ptF // CHECK: bb0([[OUT:%.*]] : $*Any, [[GUAR:%.*]] : @guaranteed $Error, func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[IMMEDIATE_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[IMMEDIATE_BOX]] // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_LIFETIME]] if true { // CHECK-NOT: copy_value [[GUAR]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[GUAR:%.*]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK-NOT: destroy_value [[GUAR]] return guaranteed } else if true { // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // CHECK: [[BORROWED_IMMEDIATE:%.*]] = begin_borrow [[IMMEDIATE]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[BORROWED_IMMEDIATE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[IMMEDIATE]] return immediate } else if true { // CHECK: function_ref boxed_existentials.plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply // CHECK: [[BORROWED_PLUS_ONE:%.*]] = begin_borrow [[PLUS_ONE]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[BORROWED_PLUS_ONE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[PLUS_ONE]] return plusOneError() } } extension Error { var myError: Error { return self } } // Make sure we don't assert on this. // CHECK-LABEL: sil hidden [ossa] @$s18boxed_existentials4testyyF // CHECK: [[ERROR_ADDR:%.*]] = alloc_stack $Error // CHECK: [[ARRAY_GET:%.*]] = function_ref @$sSayxSicig // CHECK: apply [[ARRAY_GET]]<Error>([[ERROR_ADDR]] // CHECK: [[ERROR:%.*]] = load [take] [[ERROR_ADDR]] : $*Error // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: open_existential_box [[BORROWED_ERROR]] func test() { var errors: [Error] = [] test_property(errors[0].myError) }
apache-2.0
9c3145e45c52e6f81668518f6ce54bd5
47.854902
179
0.595521
3.653372
false
true
false
false
gnachman/iTerm2
sources/CommandLinePasswordDataSource.swift
2
37307
// // CommandLinePasswordDataSource.swift // iTerm2SharedARC // // Created by George Nachman on 3/19/22. // import Foundation import OSLog /* @available(macOS 11.0, *) private let passwordLogger = Logger(subsystem: "com.googlecode.iterm2.PasswordManager", category: "default") */ class CommandLineProvidedAccount: NSObject, PasswordManagerAccount { private let configuration: CommandLinePasswordDataSource.Configuration let identifier: String let accountName: String let userName: String var displayString: String { return "\(accountName)\u{2002}—\u{2002}\(userName)" } func fetchPassword(_ completion: @escaping (String?, Error?) -> ()) { configuration.getPasswordRecipe.transformAsync(inputs: CommandLinePasswordDataSource.AccountIdentifier(value: identifier)) { result, error in completion(result, error) } } func set(password: String, completion: @escaping (Error?) -> ()) { let accountIdentifier = CommandLinePasswordDataSource.AccountIdentifier(value: identifier) let request = CommandLinePasswordDataSource.SetPasswordRequest(accountIdentifier: accountIdentifier, newPassword: password) configuration.setPasswordRecipe.transformAsync(inputs: request) { _, error in completion(error) } } func delete(_ completion: @escaping (Error?) -> ()) { configuration.deleteRecipe.transformAsync(inputs: CommandLinePasswordDataSource.AccountIdentifier(value: identifier)) { _, error in if error == nil { self.configuration.listAccountsRecipe.invalidateRecipe() } completion(error) } } func matches(filter: String) -> Bool { return accountName.containsCaseInsensitive(filter) || userName.containsCaseInsensitive(filter) } init(identifier: String, accountName: String, userName: String, configuration: CommandLinePasswordDataSource.Configuration) { self.identifier = identifier self.accountName = accountName self.userName = userName self.configuration = configuration } } struct Output { let stderr: Data let stdout: Data let returnCode: Int32 let terminationReason: Process.TerminationReason fileprivate(set) var timedOut = false let userData: [String: String]? var lines: [String] { return String(data: stdout, encoding: .utf8)?.components(separatedBy: "\n") ?? [] } } protocol CommandLinePasswordDataSourceExecutableCommand { func exec() throws -> Output func execAsync(_ completion: @escaping (Output?, Error?) -> ()) } protocol Recipe { associatedtype Inputs associatedtype Outputs func transformAsync(inputs: Inputs, completion: @escaping (Outputs?, Error?) -> ()) } protocol InvalidatableRecipe { func invalidateRecipe() } protocol CommandWriting { func write(_ data: Data, completion: (() -> ())?) func closeForWriting() } class CommandLinePasswordDataSource: NSObject { struct OutputBuilder { var stderr = Data() var stdout = Data() var timedOut = MutableAtomicObject<Bool>(false) var returnCode: Int32? = nil var terminationReason: Process.TerminationReason? = nil var userData: [String: String]? fileprivate var canBuild: Bool { return returnCode != nil && terminationReason != nil } func tryBuild() -> Output? { guard let returnCode = returnCode, let terminationReason = terminationReason else { return nil } return Output(stderr: stderr, stdout: stdout, returnCode: returnCode, terminationReason: terminationReason, timedOut: (terminationReason == .uncaughtSignal) && timedOut.value, userData: userData) } } struct CommandRequestWithInput: CommandLinePasswordDataSourceExecutableCommand { var command: String var args: [String] var env: [String: String] var input: Data private var request: InteractiveCommandRequest { var request = InteractiveCommandRequest(command: command, args: args, env: env) request.callbacks = InteractiveCommandRequest.Callbacks( callbackQueue: InteractiveCommandRequest.ioQueue, handleStdout: nil, handleStderr: nil, handleTermination: nil, didLaunch: { writing in writing.write(input) { writing.closeForWriting() } }) return request } func execAsync(_ completion: @escaping (Output?, Error?) -> ()) { request.execAsync { output, error in DispatchQueue.main.async { completion(output, error) } } } func exec() throws -> Output { return try request.exec() } } struct InteractiveCommandRequest: CommandLinePasswordDataSourceExecutableCommand { var command: String var args: [String] var env: [String: String] var userData: [String: String]? var deadline: Date? var callbacks: Callbacks? = nil var useTTY = false var executionQueue = DispatchQueue.global() static let ioQueue = DispatchQueue(label: "com.iterm2.pwcmd-io") struct Callbacks { var callbackQueue: DispatchQueue var handleStdout: ((Data) throws -> Data?)? = nil var handleStderr: ((Data) throws -> Data?)? = nil var handleTermination: ((Int32, Process.TerminationReason) throws -> ())? = nil var didLaunch: ((CommandWriting) -> ())? = nil } init(command: String, args: [String], env: [String: String]) { self.command = command self.args = args self.env = env } func exec() throws -> Output { var _output: Output? = nil var _error: Error? = nil let group = DispatchGroup() group.enter() DLog("Execute: \(command) \(args) with environment keys \(Array(env.keys.map { String($0) }))") execAsync { output, error in _output = output _error = error group.leave() } group.wait() if let error = _error { throw error } return _output! } func execAsync(_ completion: @escaping (Output?, Error?) -> ()) { let tty: TTY? if useTTY { do { var term = termios.standard var size = winsize(ws_row: 25, ws_col: 80, ws_xpixel: 250, ws_ypixel: 800) tty = try TTY(term: &term, size: &size) } catch { completion(nil, error) return } } else { tty = nil } executionQueue.async { do { let command = RunningInteractiveCommand( request: self, process: Process(), stdout: Pipe(), stderr: Pipe(), stdin: tty ?? Pipe(), ioQueue: Self.ioQueue) let output = try command.run() completion(output, nil) } catch { completion(nil, error) } } } } private class RunningInteractiveCommand: CommandWriting { private enum Event: CustomDebugStringConvertible { case readOutput(Data?) case readError(Data?) case terminated(Int32, Process.TerminationReason) var debugDescription: String { switch self { case .readOutput(let data): guard let data = data else { return "stdout:[eof]" } guard let string = String(data: data, encoding: .utf8) else { return "stdout:[not utf-8]" } return "stdout:\(string)" case .readError(let data): guard let data = data else { return "stderr:[eof]" } guard let string = String(data: data, encoding: .utf8) else { return "stderr:[not utf-8]" } return "stderr:\(string)" case .terminated(let code, let reason): return "terminated(code=\(code), reason=\(reason))" } } } private let request: InteractiveCommandRequest private let process: Process private var stdoutChannel: DispatchIO? private var stderrChannel: DispatchIO? private var stdinChannel: DispatchIO? private var stdin: ReadWriteFileHandleVending private let queue: AtomicQueue<Event> private let timedOut = MutableAtomicObject(false) private let ioQueue: DispatchQueue private let group = DispatchGroup() private var debugging: Bool { gDebugLogging.boolValue } private let lastError = MutableAtomicObject<Error?>(nil) private var returnCode: Int32? = nil private var terminationReason: Process.TerminationReason? = nil private var stdoutData = Data() private var stderrData = Data() private var ran = false private static func readingChannel(_ pipe: ReadWriteFileHandleVending, ioQueue: DispatchQueue, handler: @escaping (Data?) -> ()) -> DispatchIO { let channel = DispatchIO(type: .stream, fileDescriptor: pipe.fileHandleForReading.fileDescriptor, queue: ioQueue, cleanupHandler: { _ in }) channel.setLimit(lowWater: 1) read(channel, ioQueue: ioQueue, handler: handler) return channel } private static func read(_ channel: DispatchIO, ioQueue: DispatchQueue, handler: @escaping (Data?) -> ()) { channel.read(offset: 0, length: 1024, queue: ioQueue) { [channel] done, data, error in Self.didRead(channel, done: done, data: data, error: error, ioQueue: ioQueue, handler: handler) } } private static func didRead(_ channel: DispatchIO?, done: Bool, data: DispatchData?, error: Int32, ioQueue: DispatchQueue, handler: @escaping (Data?) -> ()) { if done && (data?.isEmpty ?? true) { handler(nil) return } guard let regions = data?.regions else { if done { handler(nil) } return } for region in regions { var data = Data(count: region.count) data.withUnsafeMutableBytes { _ = region.copyBytes(to: $0) } handler(data) } if let channel = channel { read(channel, ioQueue: ioQueue, handler: handler) } } init(request: InteractiveCommandRequest, process: Process, stdout: ReadWriteFileHandleVending, stderr: ReadWriteFileHandleVending, stdin: ReadWriteFileHandleVending, ioQueue: DispatchQueue) { self.request = request self.process = process self.stdin = stdin let queue = AtomicQueue<Event>() self.queue = queue self.ioQueue = ioQueue stdoutChannel = Self.readingChannel(stdout, ioQueue: ioQueue) { data in queue.enqueue(.readOutput(data)) } stderrChannel = Self.readingChannel(stderr, ioQueue: ioQueue) { data in DLog("\(request.command) \(request.args) produced error output: \(String(data: data ?? Data(), encoding: .utf8) ?? String(describing: data))") queue.enqueue(.readError(data)) } stdinChannel = DispatchIO(type: .stream, fileDescriptor: stdin.fileHandleForWriting.fileDescriptor, queue: ioQueue) { _ in } stdinChannel!.setLimit(lowWater: 1) process.launchPath = request.command process.arguments = request.args process.environment = request.env process.standardOutput = stdout process.standardError = stderr // NSProcess treats Pipe and NSFileHandle as magic types and defines standardInput as // Any? so the hacks trickle downhill to me here. if let pipe = stdin as? Pipe { process.standardInput = pipe } else if let tty = stdin as? TTY { process.standardInput = tty.slave } else { fatalError("Don't know what to do with stdin of type \(type(of: stdin))") } } private func beginTimeoutTimer(_ date: Date) { let dt = date.timeIntervalSinceNow self.ioQueue.asyncAfter(deadline: .now() + max(0, dt)) { [weak self] in _ = try? ObjC.catching { self?.timedOut.set(true) self?.process.terminate() } } } private func waitInBackground() { DispatchQueue.global().async { self.process.waitUntilExit() DLog("\(self.request.command) \(self.request.args) terminated status=\(self.process.terminationStatus) reason=\(self.process.terminationReason)") self.log("TERMINATED status=\(self.process.terminationStatus) reason=\(self.process.terminationReason)") self.queue.enqueue(.terminated(self.process.terminationStatus, self.process.terminationReason)) } } private func terminate() throws { try ObjC.catching { DLog("Terminate \(Thread.callStackSymbols)") process.terminate() } } private func runCallback(_ closure: @escaping () throws -> ()) { request.callbacks?.callbackQueue.async { guard self.lastError.value == nil else { return } do { try closure() } catch { self.lastError.set(error) try? self.terminate() } } } private func mainloop() -> Output { var builder = OutputBuilder(userData: request.userData) while !allChannelsClosed || !builder.canBuild { log("dequeue…") let event = queue.dequeue() log("handle event \(event)") switch event { case .readOutput(let data): log("\(request.command) \(request.args) read from stdout") handleRead(channel: &stdoutChannel, destination: &builder.stdout, handler: request.callbacks?.handleStdout, data: data) case .readError(let data): log("\(request.command) \(request.args) read from stderr") handleRead(channel: &stderrChannel, destination: &builder.stderr, handler: request.callbacks?.handleStderr, data: data) case .terminated(let code, let reason): log("\(request.command) \(request.args) terminated") stdinChannel?.close() stdinChannel = nil builder.returnCode = code builder.terminationReason = reason } } group.wait() let output = builder.tryBuild()! runTerminationHandler(output: output) group.wait() return output } private func runTerminationHandler(output: Output) { guard let handler = request.callbacks?.handleTermination else { return } group.enter() runCallback { [weak self] in try handler(output.returnCode, output.terminationReason) self?.group.leave() } } private func handleRead(channel: inout DispatchIO?, destination: inout Data, handler: ((Data) throws -> Data?)?, data: Data?) { if let data = data { destination.append(data) if let handler = handler { group.enter() runCallback { [weak self] in if let dataToWrite = try handler(data) { self?.write(dataToWrite, completion: nil) } self?.group.leave() } } } else { channel?.close() channel = nil } } private var allChannelsClosed: Bool { return stdoutChannel == nil && stderrChannel == nil && stdinChannel == nil } func write(_ data: Data, completion: (() -> ())?) { dispatchPrecondition(condition: .onQueue(ioQueue)) guard let channel = stdinChannel else { return } log("\(request.command) \(request.args) wants to write \(data.count) bytes: \(String(data: data, encoding: .utf8) ?? "(non-utf-8")") data.withUnsafeBytes { pointer in channel.write(offset: 0, data: DispatchData(bytes: pointer), queue: ioQueue) { _done, _data, _error in self.log("\(self.request.command) \(self.request.args) wrote \(_data?.count ?? 0) of \(data.count) bytes. done=\(_done) error=\(_error)") if _done, let completion = completion { completion() } guard self.debugging else { return } if let data = _data { for region in data.regions { var data = Data(count: region.count) data.withUnsafeMutableBytes { _ = region.copyBytes(to: $0) } self.log("stdin> \(String(data: data, encoding: .utf8) ?? "(non-UTF8)")") } } else if _error != 0 { self.log("stdin error: \(_error)") } } } } func closeForWriting() { dispatchPrecondition(condition: .onQueue(ioQueue)) log("close stdin") stdin.fileHandleForWriting.closeFile() stdinChannel?.close() stdinChannel = nil } func run() throws -> Output { precondition(!ran) ran = true try ObjC.catching { self.process.launch() } log("Launched \(self.process.executableURL!.path) with args \(self.process.arguments ?? [])") if let date = request.deadline { beginTimeoutTimer(date) } waitInBackground() if let handler = request.callbacks?.didLaunch { runCallback { handler(self) } } let output = mainloop() if let error = lastError.value { log("command threw \(error)") throw error } log("[\(request.command) \(request.args.joined(separator: " "))] Completed with return code \(output.returnCode)") return output } private func log(_ messageBlock: @autoclosure () -> String, file: String = #file, line: Int = #line, function: String = #function) { if debugging { let message = messageBlock() // This is commented out because we don't want to log passwords. I keep it around // only for testing locally. /* if #available(macOS 11.0, *) { passwordLogger.info("\(message, privacy: .public)") } */ DebugLogImpl(file, Int32(line), function, message) } } } struct AsyncCommandRecipe<Inputs, Outputs>: Recipe { private let asyncInputTransformer: (Inputs, @escaping (Result<CommandLinePasswordDataSourceExecutableCommand, Error>) -> ()) -> Void private let asyncRecovery: (Error, @escaping (Error?) -> ()) -> Void private let asyncOutputTransformer: (Output, @escaping (Result<Outputs, Error>) -> ()) -> Void func transformAsync(inputs: Inputs, completion: @escaping (Outputs?, Error?) -> ()) { asyncInputTransformer(inputs) { result in switch result { case .success(let command): DLog("\(inputs) -> \(command)") execAsync(command, retriesLeft: 3, completion: completion) return case .failure(let error): completion(nil, error) } } } private func execAsync(_ command: CommandLinePasswordDataSourceExecutableCommand, retriesLeft: Int, completion: @escaping (Outputs?, Error?) -> ()) { command.execAsync { output, error in DispatchQueue.main.async { if let output = output { asyncOutputTransformer(output) { result in switch result { case .success(let outputs): completion(outputs, nil) return case .failure(let error): guard retriesLeft > 0 else { completion(nil, error) return } asyncRecovery(error) { maybeError in if let error = maybeError { completion(nil, error) return } self.execAsync(command, retriesLeft: retriesLeft - 1, completion: completion) } } } } } } } init(inputTransformer: @escaping (Inputs, @escaping (Result<CommandLinePasswordDataSourceExecutableCommand, Error>) -> ()) -> Void, recovery: @escaping (Error, @escaping (Error?) -> ()) -> Void, outputTransformer: @escaping (Output, @escaping (Result<Outputs, Error>) -> ()) -> Void) { self.asyncInputTransformer = inputTransformer self.asyncRecovery = recovery self.asyncOutputTransformer = outputTransformer } } struct CommandRecipe<Inputs, Outputs>: Recipe { private let inputTransformer: (Inputs) throws -> (CommandLinePasswordDataSourceExecutableCommand) private let recovery: (Error) throws -> Void private let outputTransformer: (Output) throws -> Outputs func transformAsync(inputs: Inputs, completion: @escaping (Outputs?, Error?) -> ()) { do { let command = try inputTransformer(inputs) DLog("\(inputs) -> \(command)") execAsync(command, completion) } catch { completion(nil, error) return } } private func execAsync(_ command: CommandLinePasswordDataSourceExecutableCommand, _ completion: @escaping (Outputs?, Error?) -> ()) { command.execAsync { output, error in DispatchQueue.main.async { if let output = output { do { completion(try outputTransformer(output), nil) } catch { do { try recovery(error) self.execAsync(command, completion) } catch { completion(nil, error) } } } } } } init(inputTransformer: @escaping (Inputs) throws -> (CommandLinePasswordDataSourceExecutableCommand), recovery: @escaping (Error) throws -> Void, outputTransformer: @escaping (Output) throws -> Outputs) { self.inputTransformer = inputTransformer self.recovery = recovery self.outputTransformer = outputTransformer } } struct PipelineRecipe<FirstRecipe: Recipe, SecondRecipe: Recipe>: Recipe where FirstRecipe.Outputs == SecondRecipe.Inputs { typealias Inputs = FirstRecipe.Inputs typealias Outputs = SecondRecipe.Outputs let firstRecipe: FirstRecipe let secondRecipe: SecondRecipe init(_ firstRecipe: FirstRecipe, _ secondRecipe: SecondRecipe) { self.firstRecipe = firstRecipe self.secondRecipe = secondRecipe } func transformAsync(inputs: FirstRecipe.Inputs, completion: @escaping (SecondRecipe.Outputs?, Error?) -> ()) { firstRecipe.transformAsync(inputs: inputs) { outputs, error in if let outputs = outputs { secondRecipe.transformAsync(inputs: outputs) { value, error in completion(value, error) } return } completion(nil, error) } } } // Run firstRecipe, then run secondRecipe. The result of SecondRecipe gets returned. struct SequenceRecipe<FirstRecipe: Recipe, SecondRecipe: Recipe>: Recipe where SecondRecipe.Inputs == (FirstRecipe.Inputs, FirstRecipe.Outputs) { typealias Inputs = FirstRecipe.Inputs typealias Outputs = SecondRecipe.Outputs let firstRecipe: FirstRecipe let secondRecipe: SecondRecipe init(_ firstRecipe: FirstRecipe, _ secondRecipe: SecondRecipe) { self.firstRecipe = firstRecipe self.secondRecipe = secondRecipe } func transformAsync(inputs: FirstRecipe.Inputs, completion: @escaping (SecondRecipe.Outputs?, Error?) -> ()) { firstRecipe.transformAsync(inputs: inputs) { intermediate, error in if let intermediate = intermediate { secondRecipe.transformAsync(inputs: (inputs, intermediate), completion: completion) return } completion(nil, error) } } } struct CatchRecipe<Inner: Recipe>: Recipe { typealias Inputs = Inner.Inputs typealias Outputs = Inner.Outputs let inner: Inner let errorHandler: (Inputs, Error) -> () init(_ recipe: Inner, errorHandler: @escaping (Inputs, Error) -> ()) { inner = recipe self.errorHandler = errorHandler } func transformAsync(inputs: Inner.Inputs, completion: @escaping (Inner.Outputs?, Error?) -> ()) { inner.transformAsync(inputs: inputs) { outputs, error in if let outputs = outputs { completion(outputs, nil) return } errorHandler(inputs, error!) completion(nil, error) } } } // Note that this only works with inputs of type Void. That's because the input type needs to // be equatable for the cache to make any kind of sense, but sadly Void is not and cannot // be made equatable. For a good time, read: https://nshipster.com/void/ class CachingVoidRecipe<Outputs>: Recipe, InvalidatableRecipe { typealias Inputs = Void private struct Entry { let outputs: Outputs private let timestamp: TimeInterval var age: TimeInterval { return NSDate.it_timeSinceBoot() - timestamp } init(_ outputs: Outputs) { self.outputs = outputs self.timestamp = NSDate.it_timeSinceBoot() } } private var cacheEntry: Entry? let maxAge: TimeInterval let inner: AnyRecipe<Inputs, Outputs> func transformAsync(inputs: Void, completion: @escaping (Outputs?, Error?) -> ()) { if let value = cacheEntry, value.age < maxAge { completion(value.outputs, nil) return } inner.transformAsync(inputs: inputs) { [weak self] result, error in if let result = result { self?.cacheEntry = Entry(result) completion(result, nil) } else { completion(nil, error) } } } func invalidateRecipe() { cacheEntry = nil } init(_ recipe: AnyRecipe<Inputs, Outputs>, maxAge: TimeInterval) { inner = recipe self.maxAge = maxAge } } enum CommandLineRecipeError: Error { case unsupported(reason: String) } struct UnsupportedRecipe<Inputs, Outputs>: Recipe { let reason: String func transform(inputs: Inputs) throws -> Outputs { throw CommandLineRecipeError.unsupported(reason: reason) } func transformAsync(inputs: Inputs, completion: @escaping (Outputs?, Error?) -> ()) { completion(nil, CommandLineRecipeError.unsupported(reason: reason)) } } struct AnyRecipe<Inputs, Outputs>: Recipe, InvalidatableRecipe { private let closure: (Inputs, @escaping (Outputs?, Error?) -> ()) -> () private let invalidate: () -> () func transformAsync(inputs: Inputs, completion: @escaping (Outputs?, Error?) -> ()) { DispatchQueue.main.async { closure(inputs, completion) } } init<T: Recipe>(_ recipe: T) where T.Inputs == Inputs, T.Outputs == Outputs { closure = { recipe.transformAsync(inputs: $0, completion: $1) } invalidate = { (recipe as? InvalidatableRecipe)?.invalidateRecipe() } } func invalidateRecipe() { invalidate() } } struct AccountIdentifier { let value: String } struct Account { let identifier: AccountIdentifier let userName: String let accountName: String } struct SetPasswordRequest { let accountIdentifier: AccountIdentifier let newPassword: String } struct AddRequest { let userName: String let accountName: String let password: String } struct Configuration { let listAccountsRecipe: AnyRecipe<Void, [Account]> let getPasswordRecipe: AnyRecipe<AccountIdentifier, String> let setPasswordRecipe: AnyRecipe<SetPasswordRequest, Void> let deleteRecipe: AnyRecipe<AccountIdentifier, Void> let addAccountRecipe: AnyRecipe<AddRequest, AccountIdentifier> } func standardAccounts(_ configuration: Configuration, completion: @escaping ([PasswordManagerAccount]?, Error?) -> ()) { return configuration.listAccountsRecipe.transformAsync(inputs: ()) { maybeAccounts, maybeError in if let error = maybeError { completion(nil, error) return } let accounts = maybeAccounts!.compactMap { account in CommandLineProvidedAccount(identifier: account.identifier.value, accountName: account.accountName, userName: account.userName, configuration: configuration) } completion(accounts, nil) } } func standardAdd(_ configuration: Configuration, userName: String, accountName: String, password: String, completion: @escaping (PasswordManagerAccount?, Error?) -> ()) { let inputs = AddRequest(userName: userName, accountName: accountName, password: password) configuration.addAccountRecipe.transformAsync(inputs: inputs) { accountIdentifier, maybeError in configuration.listAccountsRecipe.invalidateRecipe() if let error = maybeError { completion(nil, error) return } let account = CommandLineProvidedAccount(identifier: accountIdentifier!.value, accountName: accountName, userName: userName, configuration: configuration) completion(account, nil) } } } protocol ReadWriteFileHandleVending: AnyObject { var fileHandleForReading: FileHandle { get } var fileHandleForWriting: FileHandle { get } } extension Pipe: ReadWriteFileHandleVending { } class TTY: NSObject, ReadWriteFileHandleVending { private(set) var master: FileHandle private(set) var slave: FileHandle? private(set) var path: String = "" init(term: inout termios, size: inout winsize) throws { var temp = Array<CChar>(repeating: 0, count: Int(PATH_MAX)) var masterFD = Int32(-1) var slaveFD = Int32(-1) let rc = openpty(&masterFD, &slaveFD, &temp, &term, &size) if rc == -1 { throw POSIXError(POSIXError.Code(rawValue: errno)!) } master = FileHandle(fileDescriptor: masterFD) slave = FileHandle(fileDescriptor: slaveFD) path = String(cString: temp) super.init() } var fileHandleForReading: FileHandle { master } var fileHandleForWriting: FileHandle { master } } extension termios { static var standard: termios = { let ctrl = { (c: String) -> cc_t in cc_t(c.utf8[c.utf8.startIndex] - 64) } return termios(c_iflag: tcflag_t(ICRNL | IXON | IXANY | IMAXBEL | BRKINT | IUTF8), c_oflag: tcflag_t(OPOST | ONLCR), c_cflag: tcflag_t(CREAD | CS8 | HUPCL), c_lflag: tcflag_t(ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL), c_cc: (ctrl("D"), cc_t(0xff), cc_t(0xff), cc_t(0x7f), ctrl("W"), ctrl("U"), ctrl("R"), cc_t(0), ctrl("C"), cc_t(0x1c), ctrl("Z"), ctrl("Y"), ctrl("Q"), ctrl("S"), ctrl("V"), ctrl("O"), cc_t(1), cc_t(0), cc_t(0), ctrl("T")), c_ispeed: speed_t(B38400), c_ospeed: speed_t(B38400)) }() }
gpl-2.0
a8d08404749f174370732604f88550a7
38.183824
161
0.510468
5.472858
false
false
false
false
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/KeyboardObserverable.swift
1
5583
// // KeyboardObserverable.swift // BaseVCKit // // Created by frank on 2017. 4. 19.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit import SnapKit /** * This protoco is for UIViewController */ public protocol KeyboardObserverable: class { func willAnimateKeyboard(keyboardTargetHeight: CGFloat, duration: Double, animationType: UIView.AnimationOptions) func willChangeKeyboard(height: CGFloat) } private var keyboardChangeObserverKey = "keyboardChangeObserver" extension KeyboardObserverable where Self: UIViewController { private var keyboardOb: NSObjectProtocol? { get { return objc_getAssociatedObject(self, &keyboardChangeObserverKey) as? NSObjectProtocol } set { willChangeValue(forKey: keyboardChangeObserverKey) if newValue == nil { // to clear observer objc_setAssociatedObject(self, &keyboardChangeObserverKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) }else { objc_setAssociatedObject(self, &keyboardChangeObserverKey, newValue as NSObjectProtocol?, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } didChangeValue(forKey: keyboardChangeObserverKey) } } public func startKeyboardAnimationObserveWithViewWillAppear() { keyboardOb = NotificationCenter.default.addObserver( forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: OperationQueue.main, using: { [weak self] notification in guard let userInfo = notification.userInfo, let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double, let c = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt, let keyboardFrame = self?.view.convert(frame, from: nil), let viewBounds = self?.view.bounds else { return } let newBottomOffset = viewBounds.maxY - keyboardFrame.minY let animationType: UIView.AnimationOptions = UIView.AnimationOptions(rawValue: c) self?.willAnimateKeyboard(keyboardTargetHeight: newBottomOffset, duration: duration, animationType: animationType) self?.willChangeKeyboard(height: newBottomOffset) }) } public func stopKeyboardAnimationObserveWithViewWillDisAppear() { self.view.endEditing(true) // make dismiss keyboard before UIViewController if let ob = keyboardOb { NotificationCenter.default.removeObserver(ob) keyboardOb = nil } } public func willAnimateKeyboard(keyboardTargetHeight: CGFloat, duration: Double, animationType: UIView.AnimationOptions) {} public func willChangeKeyboard(height: CGFloat) {} } // + SnapKit public protocol KeyboardSanpable: KeyboardObserverable { // set keyboardFollowView as 'done button' or 'text input' var keyboardFollowView: UIView? { get } // set keyboardFollowOffsetForAppeared, keyboardFollowOffsetForDisappeared for vertical interval keyboardFollowView with Keyboard's top var keyboardFollowOffsetForAppeared: CGFloat { get } var keyboardFollowOffsetForDisappeared: CGFloat { get } func keyboardFollowViewUpdateContraintsAnimations(keyboardTargetHeight: CGFloat) -> (()->())? func keyboardFollowViewUpdateContraintsAnimationCompleted(finished: Bool) } extension KeyboardSanpable where Self: UIViewController { public var keyboardFollowView: UIView? { return nil } public var keyboardFollowOffsetForAppeared: CGFloat { return 0 } public var keyboardFollowOffsetForDisappeared: CGFloat { return 0 } public func willAnimateKeyboard(keyboardTargetHeight: CGFloat, duration: Double, animationType: UIView.AnimationOptions) { guard let animations = self.keyboardFollowViewUpdateContraintsAnimations(keyboardTargetHeight: keyboardTargetHeight) else { return } UIView.animate(withDuration: duration, delay: 0.0, options: animationType, animations: animations) { [weak self] finished in self?.keyboardFollowViewUpdateContraintsAnimationCompleted(finished: finished) } } public func keyboardFollowViewUpdateContraintsAnimations(keyboardTargetHeight: CGFloat) -> (()->())? { guard let _ = self.view.window else { // isVisible return nil } guard let v = keyboardFollowView, !v.constraints.isEmpty else { return nil } var keyboardH = keyboardTargetHeight if keyboardH < 0 { keyboardH = 0 } let isAppear: Bool = keyboardTargetHeight > 0 // for fix stacked UIViewController on iOS 13 /* if !isAppear && !isFirstResponder { return nil } */ let followViewIntervalV = isAppear ? keyboardFollowOffsetForAppeared : keyboardFollowOffsetForDisappeared let bottomOffset = keyboardH + followViewIntervalV let animations: () -> () = { v.snp.updateConstraints({ $0.bottom.equalToSuperview().offset(-bottomOffset) }) v.superview?.layoutIfNeeded() } return animations } public func keyboardFollowViewUpdateContraintsAnimationCompleted(finished: Bool) {} }
mit
d72311a291f20aa0b72ac0b71b18d339
38.295775
153
0.678315
5.360231
false
false
false
false
Schatzjason/cs212
Networking/FavoriteMovie/MovieList/FavoritesViewController.swift
1
1642
// // FavoritesViewController.swift // MovieList // // Created by Jason Schatz on 11/15/17. // Copyright © 2017 Jason Schatz. All rights reserved. // import UIKit class FavoritesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! var favoriteMovies: MovieStore! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate self.favoriteMovies = appDelegate.favoriteMovies } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favoriteMovies.movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let movie = favoriteMovies.movies[indexPath.row] cell.textLabel?.text = movie.title return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { favoriteMovies.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } }
mit
2baf0775f7510ae4d1e88b067c598846
29.962264
127
0.687995
5.193038
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_03/samplecode/iOS/RecChar/RecChar/MNISTLoader.swift
1
2911
// // MNISTLoader.swift // hogee // // Created by sonson on 2017/07/26. // Copyright © 2017年 sonson. All rights reserved. // import Foundation import CoreML func loadImage(index: Int) throws -> MLMultiArray { do { let path = Bundle.main.path(forResource: "t10k-images-idx3-ubyte", ofType: "") guard let handle: UnsafeMutablePointer<FILE> = fopen(path, "r") else { throw NSError(domain: "", code: 1, userInfo: nil) } let _: UInt32 = try read(from: handle).bigEndian let count: UInt32 = try read(from: handle).bigEndian let width: Int = Int(try read(from: handle).bigEndian as UInt32) let height: Int = Int(try read(from: handle).bigEndian as UInt32) guard index < count else { throw NSError(domain: "", code: 1, userInfo: nil) } let input = try MLMultiArray(shape: [1, NSNumber(value: width), NSNumber(value: height)], dataType: .double) fseek(handle, index * width * height, SEEK_CUR) var buffer = "" for x in 0..<width { for y in 0..<height { let label: UInt8 = try read(from: handle).bigEndian let value = Double(label) / 255.0 buffer = buffer.appendingFormat("%02x", label) let xx = NSNumber(value: x) let yy = NSNumber(value: y) input[[0, xx, yy]] = NSNumber(value: value) } buffer = buffer.appendingFormat("\n") } print(buffer) fclose(handle) return input } catch { throw error } } func loadLabel(index: Int) throws -> UInt8 { do { let path = Bundle.main.path(forResource: "t10k-labels-idx1-ubyte", ofType: "") guard let handle: UnsafeMutablePointer<FILE> = fopen(path, "r") else { throw NSError(domain: "", code: 1, userInfo: nil) } let _: UInt32 = try read(from: handle).bigEndian let count: UInt32 = try read(from: handle).bigEndian guard index < count else { throw NSError(domain: "", code: 1, userInfo: nil) } fseek(handle, index, SEEK_CUR) let label: UInt8 = try read(from: handle).bigEndian fclose(handle) return label } catch { throw error } } func read(from handle: UnsafeMutablePointer<FILE>) throws -> UInt8 { var buffer: [UInt8] = [UInt8](repeating: 0, count: 1) guard fread(&buffer, Int(MemoryLayout<UInt8>.size), 1, handle) == 1 else { throw NSError(domain: "", code: 0, userInfo: nil) } return buffer[0] } func read(from handle: UnsafeMutablePointer<FILE>) throws -> UInt32 { var buffer: [UInt32] = [UInt32](repeating: 0, count: 1) guard fread(&buffer, Int(MemoryLayout<UInt32>.size), 1, handle) == 1 else { throw NSError(domain: "", code: 0, userInfo: nil) } return buffer[0] }
mit
135337d136e37dfca4183bfcaa509604
34.463415
116
0.581499
3.867021
false
false
false
false
jum/CocoaLumberjack
Integration/Sources/Formatter.swift
2
1874
// Software License Agreement (BSD License) // // Copyright (c) 2010-2019, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. import Foundation import CocoaLumberjackSwift class Formatter: DDDispatchQueueLogFormatter { let threadUnsafeDateFormatter: DateFormatter override init() { threadUnsafeDateFormatter = DateFormatter() threadUnsafeDateFormatter.formatterBehavior = .behavior10_4 threadUnsafeDateFormatter.dateFormat = "HH:mm:ss.SSS" super.init() } override func format(message logMessage: DDLogMessage) -> String { let dateAndTime = threadUnsafeDateFormatter.string(from: logMessage.timestamp) let logLevel: String let logFlag = logMessage.flag if logFlag.contains(.error) { logLevel = "E" } else if logFlag.contains(.warning){ logLevel = "W" } else if logFlag.contains(.info) { logLevel = "I" } else if logFlag.contains(.debug) { logLevel = "D" } else if logFlag.contains(.verbose) { logLevel = "V" } else { logLevel = "?" } let formattedLog = "\(dateAndTime) |\(logLevel)| [\(logMessage.fileName) \(logMessage.function ?? "nil")] #\(logMessage.line): \(logMessage.message)" return formattedLog } }
bsd-3-clause
bc6061c2f8c2215f2cb65e588c0adf46
34.358491
157
0.652081
4.792839
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Models/VIMLiveQuota.swift
1
2657
// // VIMLiveQuota.swift // VimeoNetworking // // Created by Van Nguyen on 09/11/2017. // Copyright (c) Vimeo (https://vimeo.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public enum LiveQuotaStatus: String, CaseIterable { case available = "available" case privateMode = "private_mode" case streamLimit = "stream_limit" case timeLimit = "time_limit" } /// An object that represents the `live_quota` /// field in a `user` response. public class VIMLiveQuota: VIMModelObject { private struct Constants { static let StreamsKey = "streams" static let TimeKey = "time" } /// The `streams` field in a `live_quota` response. @objc dynamic public private(set) var streams: VIMLiveStreams? /// The `time` field in a `live_quota` response. @objc dynamic public private(set) var time: VIMLiveTime? /// The `status` field in a `live_quota` response. @objc dynamic public private(set) var status: String? /// The status of the live quota in `LiveQuotaStatus` enum. public var liveQuotaStatus: LiveQuotaStatus? { guard let stringValue = self.status, let quotaStatus = LiveQuotaStatus(rawValue: stringValue) else { return nil } return quotaStatus } override public func getClassForObjectKey(_ key: String!) -> AnyClass? { if key == Constants.StreamsKey { return VIMLiveStreams.self } if key == Constants.TimeKey { return VIMLiveTime.self } return nil } }
mit
d0bf695feea7306df5a9b34fcdd9f590
34.426667
81
0.681596
4.244409
false
false
false
false
jimmy54/iRime
iRime/Keyboard/tasty-imitation-keyboard/Model/KeyboardModel.swift
1
4913
// // KeyboardModel.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import Foundation var counter = 0 enum ShiftState { case disabled case enabled case locked func uppercase() -> Bool { switch self { case .disabled: return false case .enabled: return true case .locked: return true } } } class Keyboard { var pages: [Page] init() { self.pages = [] } func addKey(_ key: Key, row: Int, page: Int) { if self.pages.count <= page { for _ in self.pages.count...page { self.pages.append(Page()) } } self.pages[page].addKey(key, row: row) } } class Page { var rows: [[Key]] init() { self.rows = [] } func addKey(_ key: Key, row: Int) { if self.rows.count <= row { for _ in self.rows.count...row { self.rows.append([]) } } self.rows[row].append(key) } } class Key: Hashable { enum KeyType { case character case specialCharacter case shift case backspace case modeChange case keyboardChange case period case space case `return` case settings case other case switchInput// } var type: KeyType var uppercaseKeyCap: String? var lowercaseKeyCap: String? var uppercaseOutput: String? var lowercaseOutput: String? var toMode: Int? //if the key is a mode button, this indicates which page it links to var keyCode: CUnsignedShort? var isCharacter: Bool { get { switch self.type { case .character, .specialCharacter, .period: return true default: return false } } } var isSpecial: Bool { get { switch self.type { case .shift: return true case .backspace: return true case .modeChange: return true case .keyboardChange: return true case .return: return true case .settings: return true default: return false } } } var hasOutput: Bool { get { return (self.uppercaseOutput != nil) || (self.lowercaseOutput != nil) } } // TODO: this is kind of a hack var hashValue: Int init(_ type: KeyType) { self.type = type self.hashValue = counter counter += 1 } convenience init(_ key: Key) { self.init(key.type) self.uppercaseKeyCap = key.uppercaseKeyCap self.lowercaseKeyCap = key.lowercaseKeyCap self.uppercaseOutput = key.uppercaseOutput self.lowercaseOutput = key.lowercaseOutput self.toMode = key.toMode } func setLetter(_ letter: String) { self.lowercaseOutput = (letter as NSString).lowercased self.uppercaseOutput = (letter as NSString).uppercased self.lowercaseKeyCap = self.lowercaseOutput self.uppercaseKeyCap = self.uppercaseOutput } func outputForCase(_ uppercase: Bool) -> String { if uppercase { if self.uppercaseOutput != nil { return self.uppercaseOutput! } else if self.lowercaseOutput != nil { return self.lowercaseOutput! } else { return "" } } else { if self.lowercaseOutput != nil { return self.lowercaseOutput! } else if self.uppercaseOutput != nil { return self.uppercaseOutput! } else { return "" } } } func keyCapForCase(_ uppercase: Bool) -> String { if uppercase { if self.uppercaseKeyCap != nil { return self.uppercaseKeyCap! } else if self.lowercaseKeyCap != nil { return self.lowercaseKeyCap! } else { return "" } } else { if self.lowercaseKeyCap != nil { return self.lowercaseKeyCap! } else if self.uppercaseKeyCap != nil { return self.uppercaseKeyCap! } else { return "" } } } } func ==(lhs: Key, rhs: Key) -> Bool { return lhs.hashValue == rhs.hashValue }
gpl-3.0
b90f819b4d3ee52dbd8eb055c6070041
22.28436
89
0.487686
5.112383
false
false
false
false
kildevaeld/DStack
Pod/Classes/CoreStack.swift
1
905
// // CoreStack.swift // Pods // // Created by Rasmus Kildevæld on 02/10/15. // // import Foundation import CoreData class CoreDataStack { let persistentStoreCoordinator : NSPersistentStoreCoordinator let rootContext : NSManagedObjectContext let mainContext: NSManagedObjectContext let workerContext: NSManagedObjectContext init (persistentStoreCoordinator: NSPersistentStoreCoordinator) { self.persistentStoreCoordinator = persistentStoreCoordinator self.rootContext = NSManagedObjectContext(persistentStoreCoordinator: persistentStoreCoordinator) self.rootContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy self.mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType, parentContext: self.rootContext) self.workerContext = self.mainContext.createChildContext() } }
mit
723dd680d0086205a695c64695656b5c
31.321429
126
0.759956
6.457143
false
false
false
false
banxi1988/BXAppKit
BXForm/Controller/TwoStageCascadeSelectPickerController.swift
1
4604
// // TwoStageCascadeSelectPickerController.swift // Pods // // Created by Haizhen Lee on 16/6/14. // // import UIKit public protocol ChildPickerItem: CustomStringConvertible,Equatable{ } public protocol ParentPickerItem: CustomStringConvertible,Hashable{ } open class TwoStageCascadeSelectPickerController<T:ParentPickerItem,C:ChildPickerItem>:PickerController,UIPickerViewDataSource,UIPickerViewDelegate{ public typealias ParentChildDict = Dictionary<T,[C]> fileprivate var dict: ParentChildDict = [:] fileprivate var parents:[T] = [] open var parentCount:Int{ return parents.count } open func childCountAtSection(_ section:Int) -> Int{ return childrenAtSection(section).count } open func childrenAtSection(_ section:Int) -> [C]{ return dict[parentAtSection(section)]! } open func parentAtSection(_ section:Int) -> T { return parents[section] } open func childAtSection(_ section:Int,index:Int) -> C{ return childrenAtSection(section)[index] } open var rowHeight:CGFloat = 36{ didSet{ picker.reloadAllComponents() } } open var textColor = UIColor.darkText{ didSet{ picker.reloadAllComponents() } } open var font = UIFont.systemFont(ofSize: 14){ didSet{ picker.reloadAllComponents() } } open var onSelectOption:((T,C) -> Void)? public init(parents:[T],dict:ParentChildDict){ super.init(nibName: nil, bundle: nil) self.updateOptions(parents,dict:dict) } public init(){ super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() picker.delegate = self picker.dataSource = self picker.showsSelectionIndicator = true } open func selectOption(_ option:T,of item:C){ let index = parents.index { $0 == option } if let section = index{ let rowIndex = childrenAtSection(section).index {$0 == item } if let row = rowIndex { picker.selectRow(row, inComponent: section, animated: true) } } } open func updateOptions(_ parents:[T],dict:ParentChildDict){ self.parents = parents self.dict = dict if isViewLoaded{ picker.reloadAllComponents() } } var selectedSection:Int{ return picker.selectedRow(inComponent: 0) } // MARK: UIPickerViewDataSource open func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if parents.isEmpty || dict.isEmpty { return 0 } switch component{ case 0: return parents.count case 1: let parentRow = pickerView.selectedRow(inComponent: 0) let count = childCountAtSection(parentRow) return count default: return 0 } } // MARK: UIPickerViewDelegate open func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return rowHeight } open func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let option:CustomStringConvertible switch component{ case 0: option = parentAtSection(row) case 1: let section = pickerView.selectedRow(inComponent: 0) let children = childrenAtSection(section) if children.count <= row { return nil }else{ option = children[row] } default:return nil } let title = option.description let attributedText = NSAttributedString(string: title, attributes: [ NSAttributedStringKey.foregroundColor:textColor, NSAttributedStringKey.font:font ]) return attributedText } open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0{ pickerView.reloadComponent(1) // if childCountAtSection(1) > 0 { // pickerView.selectRow(0, inComponent: 1, animated: true) // } } } // MARK: Base Controller override open func onPickDone() { if parents.isEmpty || dict.isEmpty{ return } let parentRow = picker.selectedRow(inComponent: 0) let childRow = picker.selectedRow(inComponent: 1) let parent = parentAtSection(parentRow) let children = childrenAtSection(parentRow) if children.count <= childRow { return } let child = children[childRow] onSelectOption?(parent,child) } }
mit
9df801e150a630fccf10ab924a6017cd
24.436464
148
0.676368
4.500489
false
false
false
false
codefellows/sea-b23-iOS
corelocationdemo/corelocationdemo/ReminderTableViewController.swift
1
2898
// // ReminderTableViewController.swift // corelocationdemo // // Created by Bradley Johnson on 11/5/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit import CoreData class ReminderTableViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate { var managedObjectContext : NSManagedObjectContext! var fetchedResultsController: NSFetchedResultsController! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.managedObjectContext = appDelegate.managedObjectContext NSNotificationCenter.defaultCenter().addObserver(self, selector: "didGetCloudChanges:", name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: appDelegate.persistentStoreCoordinator) self.tableView.dataSource = self var fetchRequest = NSFetchRequest(entityName: "Reminder") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Reminders") self.fetchedResultsController.delegate = self var error : NSError? if !self.fetchedResultsController.performFetch(&error) { println("error!!") } // self.reminders = self.managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [Reminder] // if error != nil { // println(error?.localizedDescription) // } else { // self.tableView.reloadData() // } // Do any additional setup after loading the view. } func didGetCloudChanges( notification : NSNotification) { //self.managedObjectContext.performBlock { () -> Void in self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) //} } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.fetchedResultsController.fetchedObjects?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("REMINDER_CELL", forIndexPath: indexPath) as UITableViewCell let reminder = self.fetchedResultsController.fetchedObjects?[indexPath.row] as Reminder cell.textLabel.text = reminder.name return cell } // MARK: - NSFetchedResultsControllerDelegate func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.reloadData() } }
mit
002e1ef717d229dbc28afdb5e791d749
39.25
214
0.707039
6.0375
false
false
false
false
eBardX/XestiMonitors
Tests/Mock/MockApplication.swift
1
1089
// // MockApplication.swift // XestiMonitorsTests // // Created by J. G. Pusey on 2017-12-27. // // © 2017 J. G. Pusey (see LICENSE.md) // import UIKit @testable import XestiMonitors internal class MockApplication: ApplicationProtocol { init() { self.applicationState = .inactive #if os(iOS) self.backgroundRefreshStatus = .restricted #endif self.isProtectedDataAvailable = false if #available(iOS 10.0, tvOS 10.0, *) { self.preferredContentSizeCategory = .unspecified } else { self.preferredContentSizeCategory = .medium } #if os(iOS) self.statusBarFrame = .zero self.statusBarOrientation = .unknown #endif } var applicationState: UIApplicationState #if os(iOS) var backgroundRefreshStatus: UIBackgroundRefreshStatus #endif var isProtectedDataAvailable: Bool var preferredContentSizeCategory: UIContentSizeCategory #if os(iOS) var statusBarFrame: CGRect var statusBarOrientation: UIInterfaceOrientation #endif }
mit
5c9973fc690f68d851580e333add0c84
25.536585
60
0.664522
4.689655
false
false
false
false
Mindera/Alicerce
Tests/AlicerceTests/Shared/ModelDecodingTestCase.swift
1
1034
import XCTest @testable import Alicerce class ModelDecodingTestCase: XCTestCase { struct MockModel: Codable, Equatable { let foo: String } typealias ModelDecoding = Alicerce.ModelDecoding<MockModel, Data, URLResponse> func testJSON_WithSuccessDecoding_ShouldReturnModel() { let model = MockModel(foo: "bar") let data = try! JSONEncoder().encode(model) // swiftlint:disable:this force_try let response = URLResponse() XCTAssertEqual(try ModelDecoding.json().decode(data, response), model) } func testJSON_WithFailureDecoding_ShouldThrowDecodingError() { let data = Data("{}".utf8) let response = URLResponse() XCTAssertThrowsError(try ModelDecoding.json().decode(data, response)) { guard case DecodingError.keyNotFound(let codingKey, _) = $0 else { XCTFail("unexpected error: \($0)") return } XCTAssertEqual(codingKey.stringValue, "foo") } } }
mit
53e69ab99e821bff61be4022ec41d88f
27.722222
87
0.634429
4.92381
false
true
false
false
jonasman/TeslaSwift
Sources/TeslaSwift/Model/EnergySiteHistory.swift
1
2926
// // EnergySiteHistory.swift // TeslaSwift // // Created by Alec on 11/24/21. // Copyright © 2021 Joao Nunes. All rights reserved. // import Foundation // MARK: - EnergySiteHistory open class EnergySiteHistory: Codable { open var serialNumber: String open var period: Period open var timeSeries: [TimeSeries] enum CodingKeys: String, CodingKey { case serialNumber = "serial_number" case period case timeSeries = "time_series" } public enum Period: String, Codable { case day, week, month, year } // MARK: - TimeSeries open class TimeSeries: Codable { open var timestamp: Date open var solarEnergyExported: Double open var generatorEnergyExported: Double open var gridEnergyImported: Double open var gridServicesEnergyImported: Double open var gridServicesEnergyExported: Double open var gridEnergyExportedFromSolar: Double open var gridEnergyExportedFromGenerator: Double open var gridEnergyExportedFromBattery: Double open var batteryEnergyExported: Double open var batteryEnergyImportedFromGrid: Double open var batteryEnergyImportedFromSolar: Double open var batteryEnergyImportedFromGenerator: Double open var consumerEnergyImportedFromGrid: Double open var consumerEnergyImportedFromSolar: Double open var consumerEnergyImportedFromBattery: Double open var consumerEnergyImportedFromGenerator: Double enum CodingKeys: String, CodingKey { case timestamp case solarEnergyExported = "solar_energy_exported" case generatorEnergyExported = "generator_energy_exported" case gridEnergyImported = "grid_energy_imported" case gridServicesEnergyImported = "grid_services_energy_imported" case gridServicesEnergyExported = "grid_services_energy_exported" case gridEnergyExportedFromSolar = "grid_energy_exported_from_solar" case gridEnergyExportedFromGenerator = "grid_energy_exported_from_generator" case gridEnergyExportedFromBattery = "grid_energy_exported_from_battery" case batteryEnergyExported = "battery_energy_exported" case batteryEnergyImportedFromGrid = "battery_energy_imported_from_grid" case batteryEnergyImportedFromSolar = "battery_energy_imported_from_solar" case batteryEnergyImportedFromGenerator = "battery_energy_imported_from_generator" case consumerEnergyImportedFromGrid = "consumer_energy_imported_from_grid" case consumerEnergyImportedFromSolar = "consumer_energy_imported_from_solar" case consumerEnergyImportedFromBattery = "consumer_energy_imported_from_battery" case consumerEnergyImportedFromGenerator = "consumer_energy_imported_from_generator" } } }
mit
731388b088299fff98a89283939c1342
42.656716
96
0.708718
4.850746
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/What's New/Presenter/WhatIsNewScenePresenter.swift
1
4191
import WordPressFlux class WhatIsNewScenePresenter: ScenePresenter { var presentedViewController: UIViewController? private var subscription: Receipt? private var startPresenting: (() -> Void)? private let store: AnnouncementsStore private func shouldPresentWhatIsNew(on viewController: UIViewController) -> Bool { viewController is AppSettingsViewController || (AppRatingUtility.shared.didUpgradeVersion && UserDefaults.standard.announcementsVersionDisplayed != Bundle.main.shortVersionString() && self.store.announcements.first?.isLocalized == true) } var versionHasAnnouncements: Bool { store.versionHasAnnouncements } init(store: AnnouncementsStore) { self.store = store subscription = store.onChange { [weak self] in guard let self = self, !self.store.announcements.isEmpty else { return } self.startPresenting?() } } func present(on viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { defer { store.getAnnouncements() } startPresenting = { [weak viewController, weak self] in guard let self = self, let viewController = viewController, viewController.isViewOnScreen(), self.shouldPresentWhatIsNew(on: viewController) else { return } let controller = self.makeWhatIsNewViewController() self.trackAccess(from: viewController) viewController.present(controller, animated: animated) { UserDefaults.standard.announcementsVersionDisplayed = Bundle.main.shortVersionString() completion?() } } } // analytics private func trackAccess(from viewController: UIViewController) { if viewController is AppSettingsViewController { WPAnalytics.track(.featureAnnouncementShown, properties: ["source": "app_settings"]) } else { WPAnalytics.track(.featureAnnouncementShown, properties: ["source": "app_upgrade"]) } } } // MARK: - Dependencies private extension WhatIsNewScenePresenter { func makeWhatIsNewViewController() -> WhatIsNewViewController { return WhatIsNewViewController(whatIsNewViewFactory: makeWhatIsNewView, onContinue: { WPAnalytics.track(.featureAnnouncementButtonTapped, properties: ["button": "close_dialog"]) }) } func makeWhatIsNewView() -> WhatIsNewView { let viewTitles = WhatIsNewViewTitles(header: WhatIsNewStrings.title, version: WhatIsNewStrings.version, continueButtonTitle: WhatIsNewStrings.continueButtonTitle) return WhatIsNewView(viewTitles: viewTitles, dataSource: makeDataSource()) } func makeDataSource() -> AnnouncementsDataSource { return FeatureAnnouncementsDataSource(store: self.store, cellTypes: ["announcementCell": AnnouncementCell.self, "findOutMoreCell": FindOutMoreCell.self]) } enum WhatIsNewStrings { static let title = NSLocalizedString("What's New in WordPress", comment: "Title of the What's new page.") static let versionPrefix = NSLocalizedString("Version ", comment: "Description for the version label in the What's new page.") static let continueButtonTitle = NSLocalizedString("Continue", comment: "Title for the continue button in the What's New page.") static var version: String { Bundle.main.shortVersionString() != nil ? versionPrefix + Bundle.main.shortVersionString() : "" } } } private extension UserDefaults { static let announcementsVersionDisplayedKey = "announcementsVersionDisplayed" var announcementsVersionDisplayed: String? { get { string(forKey: UserDefaults.announcementsVersionDisplayedKey) } set { set(newValue, forKey: UserDefaults.announcementsVersionDisplayedKey) } } }
gpl-2.0
5e19b1eac95501c8fb38625e3b8fe6fa
36.088496
142
0.64734
5.428756
false
false
false
false
dshamany/CIToolbox
CIToolbox/MarketingView.swift
1
2796
// // MarketingView.swift // Clean Initiative Tool Box // // Created by Daniel Shamany on 3/2/17. // Copyright © 2017 Daniel Shamany. All rights reserved. // import UIKit class MarketingView: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { // VCArr is an array of UIViews that we itirate on using storyBoard IDs lazy var VCArr: [UIViewController] = { return [self.VCInstance(name: "FlyerView"), self.VCInstance(name: "BillView"), ] }() private func VCInstance(name: String) -> UIViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name) } override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self if let firstVC = VCArr.first { setViewControllers([firstVC], direction: .forward, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if self.view.window == nil { self.setValue(nil, forKey: "view") } } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{ guard let viewControllerIndex = VCArr.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return VCArr.last } guard VCArr.count > previousIndex else { return nil } return VCArr[previousIndex] } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{ guard let viewControllerIndex = VCArr.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 guard nextIndex < VCArr.count else { return VCArr.first } guard VCArr.count > nextIndex else { return nil } return VCArr[nextIndex] } public func presentationCount(for pageViewController: UIPageViewController) -> Int{ return VCArr.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int{ guard let firstViewController = viewControllers?.first, let firstViewControllerIndex = VCArr.index(of: firstViewController) else { return 0 } return firstViewControllerIndex } }
gpl-3.0
ff91c9bd80a791555acae5a05f7cca25
28.421053
155
0.617174
5.669371
false
false
false
false
jeffreybergier/FruitKey
FruitKey/FKTabBarController.swift
1
3185
// // FKTabBarController.swift // FruitKey // // Created by Jeffrey Bergier on 11/1/14. // // The MIT License (MIT) // // Copyright (c) 2014 Jeffrey Bergier // // 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 class FKTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "goToNextPage:") rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "goToNextPage:") leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(rightSwipeGestureRecognizer) self.view.addGestureRecognizer(leftSwipeGestureRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func goToNextPage(sender: UISwipeGestureRecognizer) { var selectedSegmentIndex = 0 var numberOfSegments = 0 if let viewControllers = self.viewControllers { numberOfSegments = viewControllers.count for i in 0..<viewControllers.count { if let selectedViewController = self.selectedViewController { if selectedViewController == viewControllers[i] as! UIViewController { selectedSegmentIndex = i } } } } if sender.direction == UISwipeGestureRecognizerDirection.Left { if selectedSegmentIndex + 1 < numberOfSegments { self.selectedIndex = selectedSegmentIndex + 1 } else { self.selectedIndex = 0 } } else { if selectedSegmentIndex - 1 >= 0 { self.selectedIndex = selectedSegmentIndex - 1 } else { self.selectedIndex = numberOfSegments - 1 } } } }
mit
ffd51ddfe17872faf70ebf9faedf4bdb
39.833333
105
0.678807
5.577933
false
false
false
false
sdhzwm/WMMatchbox
WMMatchbox/WMMatchbox/Classes/Friend(好友)/Controller/WMFirendController.swift
1
3222
// // WMFirendController.swift // WMMatchbox // // Created by 王蒙 on 15/7/21. // Copyright © 2015年 wm. All rights reserved. // import UIKit class WMFirendController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
c68461da263da578ab48e6bcdfd1bb11
32.842105
157
0.685537
5.495726
false
false
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/General/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallGridPulse.swift
66
2567
// // NVActivityIndicatorAnimationBallGridPulse.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/23/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallGridPulse: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations: [CFTimeInterval] = [0.72, 1.02, 1.28, 1.42, 1.45, 1.18, 0.87, 1.45, 1.06] let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [-0.06, 0.25, -0.17, 0.48, 0.31, 0.03, 0.46, 0.78, 0.45] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1] // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.5, 1] opacityAnimation.timingFunctions = [timingFunction, timingFunction] opacityAnimation.values = [1, 0.7, 1] // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.repeatCount = HUGE animation.removedOnCompletion = false // Draw circles for var i = 0; i < 3; i++ { for var j = 0; j < 3; j++ { let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j), y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), width: circleSize, height: circleSize) animation.duration = durations[3 * i + j] animation.beginTime = beginTime + beginTimes[3 * i + j] circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } } } }
apache-2.0
b8eec101703db1daba44fdf8d4893e92
41.081967
143
0.602649
4.633574
false
false
false
false
shajrawi/swift
test/attr/attr_objc.swift
1
95524
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s // RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t.ast // RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.ast // REQUIRES: objc_interop import Foundation class PlainClass {} struct PlainStruct {} enum PlainEnum {} protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}} enum ErrorEnum : Error { case failed } @objc class Class_ObjC1 {} protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}} protocol Protocol_Class2 : class {} @objc protocol Protocol_ObjC1 {} @objc protocol Protocol_ObjC2 {} //===--- Subjects of @objc attribute. @objc extension PlainStruct { } // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}} class FáncyName {} @objc (FancyName) extension FáncyName {} @objc var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var subject_getterSetter: Int { @objc get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} return 0 } @objc set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } } var subject_global_observingAccessorsVar1: Int = 0 { @objc willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} } @objc didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} } } class subject_getterSetter1 { var instanceVar1: Int { @objc get { // expected-error {{'@objc' getter for non-'@objc' property}} return 0 } } var instanceVar2: Int { get { return 0 } @objc set { // expected-error {{'@objc' setter for non-'@objc' property}} } } var instanceVar3: Int { @objc get { // expected-error {{'@objc' getter for non-'@objc' property}} return 0 } @objc set { // expected-error {{'@objc' setter for non-'@objc' property}} } } var observingAccessorsVar1: Int = 0 { @objc willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}} } @objc didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}} } } } class subject_staticVar1 { @objc class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} @objc class var staticVar2: Int { return 42 } } @objc func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}} @objc var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } } @objc func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}} @objc var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}} } @objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}} struct subject_struct { @objc var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } @objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}} struct subject_genericStruct<T> { @objc var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } @objc class subject_class1 { // no-error @objc var subject_instanceVar: Int // no-error @objc init() {} // no-error @objc func subject_instanceFunc() {} // no-error } @objc class subject_class2 : Protocol_Class1, PlainProtocol { // no-error } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class subject_genericClass<T> { @objc var subject_instanceVar: Int // no-error @objc init() {} // no-error @objc func subject_instanceFunc() {} // no_error } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}} class subject_genericClass2<T> : Class_ObjC1 { @objc var subject_instanceVar: Int // no-error @objc init(foo: Int) {} // no-error @objc func subject_instanceFunc() {} // no_error } extension subject_genericClass where T : Hashable { @objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}} } extension subject_genericClass { @objc var extProp: Int { return 0 } // expected-error{{extensions of generic classes cannot contain '@objc' members}} @objc func extFoo() {} // expected-error{{extensions of generic classes cannot contain '@objc' members}} } @objc enum subject_enum: Int { @objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement1 @objc(subject_enumElement2) case subject_enumElement2 @objc(subject_enumElement3) case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-30=}} @objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement5, subject_enumElement6 @nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} case subject_enumElement7 @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } enum subject_enum2 { @objc(subject_enum2Element1) case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-31=}} } @objc protocol subject_protocol1 { @objc var subject_instanceVar: Int { get } @objc func subject_instanceFunc() } @objc protocol subject_protocol2 {} // no-error // CHECK-LABEL: @objc protocol subject_protocol2 { @objc protocol subject_protocol3 {} // no-error // CHECK-LABEL: @objc protocol subject_protocol3 { @objc protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}} @objc protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}} @objc protocol subject_protocol6 : Protocol_ObjC1 {} protocol subject_containerProtocol1 { @objc var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } @objc protocol subject_containerObjCProtocol1 { func func_FunctionReturn1() -> PlainStruct // expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_FunctionParam1(a: PlainStruct) // expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_Variadic(_: AnyObject...) // expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}} // expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}} subscript(a: PlainStruct) -> Int { get } // expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} var varNonObjC1: PlainStruct { get } // expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} } @objc protocol subject_containerObjCProtocol2 { init(a: Int) @objc init(a: Double) func func1() -> Int @objc func func1_() -> Int var instanceVar1: Int { get set } @objc var instanceVar1_: Int { get set } subscript(i: Int) -> Int { get set } @objc subscript(i: String) -> Int { get set} } protocol nonObjCProtocol { @objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } func concreteContext1() { @objc class subject_inConcreteContext {} } class ConcreteContext2 { @objc class subject_inConcreteContext {} } class ConcreteContext3 { func dynamicSelf1() -> Self { return self } @objc func dynamicSelf1_() -> Self { return self } @objc func genericParams<T: NSObject>() -> [T] { return [] } // expected-error@-1{{method cannot be marked @objc because it has generic parameters}} @objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias AnotherNSCoding = NSCoding typealias MetaNSCoding1 = NSCoding.Protocol typealias MetaNSCoding2 = AnotherNSCoding.Protocol @objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias Composition = NSCopying & NSCoding @objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias NSCodingExistential = NSCoding.Type @objc func inoutFunc(a: inout Int) {} // expected-error@-1{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}} @objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} } func genericContext1<T>(_: T) { @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}} class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc init() {} // no-error } class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc var subject_instanceVar: Int = 0 // no-error } class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc func f() {} // no-error } } class GenericContext2<T> { @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} @objc func f() {} // no-error } class GenericContext3<T> { class MoreNested { @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}} class subject_inGenericContext {} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{5-11=}} class subject_inGenericContext2 : Class_ObjC1 {} @objc func f() {} // no-error } } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class ConcreteSubclassOfGeneric : GenericContext3<Int> {} extension ConcreteSubclassOfGeneric { @objc func foo() {} // okay } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}} class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {} extension ConcreteSubclassOfGeneric2 { @objc func foo() {} // okay } @objc(CustomNameForSubclassOfGeneric) // okay class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {} extension ConcreteSubclassOfGeneric3 { @objc func foo() {} // okay } class subject_subscriptIndexed1 { @objc subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed2 { @objc subscript(a: Int8) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed3 { @objc subscript(a: UInt8) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed1 { @objc subscript(a: String) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed2 { @objc subscript(a: Class_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed3 { @objc subscript(a: Class_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed4 { @objc subscript(a: Protocol_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed5 { @objc subscript(a: Protocol_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed6 { @objc subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed7 { @objc subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error get { return 0 } } } class subject_subscriptBridgedFloat { @objc subscript(a: Float32) -> Int { get { return 0 } } } class subject_subscriptGeneric<T> { @objc subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptInvalid1 { @objc class subscript(_ i: Int) -> AnyObject? { // expected-error@-1 {{class subscript cannot be marked @objc}} return nil } } class subject_subscriptInvalid2 { @objc subscript(a: PlainClass) -> Int { // expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid3 { @objc subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid4 { @objc subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{Swift structs cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid5 { @objc subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{enums cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid6 { @objc subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid7 { @objc subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid8 { @objc subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} get { return 0 } } } class subject_propertyInvalid1 { @objc let plainStruct = PlainStruct() // expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{Swift structs cannot be represented in Objective-C}} } //===--- Tests for @objc inference. @objc class infer_instanceFunc1 { // CHECK-LABEL: @objc class infer_instanceFunc1 { func func1() {} // CHECK-LABEL: @objc func func1() { @objc func func1_() {} // no-error func func2(a: Int) {} // CHECK-LABEL: @objc func func2(a: Int) { @objc func func2_(a: Int) {} // no-error func func3(a: Int) -> Int {} // CHECK-LABEL: @objc func func3(a: Int) -> Int { @objc func func3_(a: Int) -> Int {} // no-error func func4(a: Int, b: Double) {} // CHECK-LABEL: @objc func func4(a: Int, b: Double) { @objc func func4_(a: Int, b: Double) {} // no-error func func5(a: String) {} // CHECK-LABEL: @objc func func5(a: String) { @objc func func5_(a: String) {} // no-error func func6() -> String {} // CHECK-LABEL: @objc func func6() -> String { @objc func func6_() -> String {} // no-error func func7(a: PlainClass) {} // CHECK-LABEL: {{^}} func func7(a: PlainClass) { @objc func func7_(a: PlainClass) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func7m(a: PlainClass.Type) {} // CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) { @objc func func7m_(a: PlainClass.Type) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} func func8() -> PlainClass {} // CHECK-LABEL: {{^}} func func8() -> PlainClass { @objc func func8_() -> PlainClass {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func8m() -> PlainClass.Type {} // CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type { @objc func func8m_() -> PlainClass.Type {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} func func9(a: PlainStruct) {} // CHECK-LABEL: {{^}} func func9(a: PlainStruct) { @objc func func9_(a: PlainStruct) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func10() -> PlainStruct {} // CHECK-LABEL: {{^}} func func10() -> PlainStruct { @objc func func10_() -> PlainStruct {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func11(a: PlainEnum) {} // CHECK-LABEL: {{^}} func func11(a: PlainEnum) { @objc func func11_(a: PlainEnum) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} func func12(a: PlainProtocol) {} // CHECK-LABEL: {{^}} func func12(a: PlainProtocol) { @objc func func12_(a: PlainProtocol) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} func func13(a: Class_ObjC1) {} // CHECK-LABEL: @objc func func13(a: Class_ObjC1) { @objc func func13_(a: Class_ObjC1) {} // no-error func func14(a: Protocol_Class1) {} // CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) { @objc func func14_(a: Protocol_Class1) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} func func15(a: Protocol_ObjC1) {} // CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) { @objc func func15_(a: Protocol_ObjC1) {} // no-error func func16(a: AnyObject) {} // CHECK-LABEL: @objc func func16(a: AnyObject) { @objc func func16_(a: AnyObject) {} // no-error func func17(a: @escaping () -> ()) {} // CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) { @objc func func17_(a: @escaping () -> ()) {} func func18(a: @escaping (Int) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int) @objc func func18_(a: @escaping (Int) -> (), b: Int) {} func func19(a: @escaping (String) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) { @objc func func19_(a: @escaping (String) -> (), b: Int) {} func func_FunctionReturn1() -> () -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () { @objc func func_FunctionReturn1_() -> () -> () {} func func_FunctionReturn2() -> (Int) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () { @objc func func_FunctionReturn2_() -> (Int) -> () {} func func_FunctionReturn3() -> () -> Int {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int { @objc func func_FunctionReturn3_() -> () -> Int {} func func_FunctionReturn4() -> (String) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () { @objc func func_FunctionReturn4_() -> (String) -> () {} func func_FunctionReturn5() -> () -> String {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String { @objc func func_FunctionReturn5_() -> () -> String {} func func_ZeroParams1() {} // CHECK-LABEL: @objc func func_ZeroParams1() { @objc func func_ZeroParams1a() {} // no-error func func_OneParam1(a: Int) {} // CHECK-LABEL: @objc func func_OneParam1(a: Int) { @objc func func_OneParam1a(a: Int) {} // no-error func func_TupleStyle1(a: Int, b: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) { @objc func func_TupleStyle1a(a: Int, b: Int) {} func func_TupleStyle2(a: Int, b: Int, c: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) { @objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {} // Check that we produce diagnostics for every parameter and return type. @objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}} // expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}} @objc func func_UnnamedParam1(_: Int) {} // no-error @objc func func_UnnamedParam2(_: PlainStruct) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} @objc func func_varParam1(a: AnyObject) { var a = a let b = a; a = b } func func_varParam2(a: AnyObject) { var a = a let b = a; a = b } // CHECK-LABEL: @objc func func_varParam2(a: AnyObject) { } @objc class infer_constructor1 { // CHECK-LABEL: @objc class infer_constructor1 init() {} // CHECK: @objc init() init(a: Int) {} // CHECK: @objc init(a: Int) init(a: PlainStruct) {} // CHECK: {{^}} init(a: PlainStruct) init(malice: ()) {} // CHECK: @objc init(malice: ()) init(forMurder _: ()) {} // CHECK: @objc init(forMurder _: ()) } @objc class infer_destructor1 { // CHECK-LABEL: @objc class infer_destructor1 deinit {} // CHECK: @objc deinit } // @!objc class infer_destructor2 { // CHECK-LABEL: {{^}}class infer_destructor2 deinit {} // CHECK: @objc deinit } @objc class infer_instanceVar1 { // CHECK-LABEL: @objc class infer_instanceVar1 { init() {} var instanceVar1: Int // CHECK: @objc var instanceVar1: Int var (instanceVar2, instanceVar3): (Int, PlainProtocol) // CHECK: @objc var instanceVar2: Int // CHECK: {{^}} var instanceVar3: PlainProtocol @objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol) // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var intstanceVar4: Int { // CHECK: @objc var intstanceVar4: Int { get {} // CHECK-NEXT: @objc get {} } var intstanceVar5: Int { // CHECK: @objc var intstanceVar5: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } @objc var instanceVar5_: Int { // CHECK: @objc var instanceVar5_: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } var observingAccessorsVar1: Int { // CHECK: @objc @_hasStorage var observingAccessorsVar1: Int { willSet {} // CHECK-NEXT: {{^}} @objc get didSet {} // CHECK-NEXT: {{^}} @objc set } @objc var observingAccessorsVar1_: Int { // CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int { willSet {} // CHECK-NEXT: {{^}} @objc get didSet {} // CHECK-NEXT: {{^}} @objc set } var var_Int: Int // CHECK-LABEL: @objc var var_Int: Int var var_Bool: Bool // CHECK-LABEL: @objc var var_Bool: Bool var var_CBool: CBool // CHECK-LABEL: @objc var var_CBool: CBool var var_String: String // CHECK-LABEL: @objc var var_String: String var var_Float: Float var var_Double: Double // CHECK-LABEL: @objc var var_Float: Float // CHECK-LABEL: @objc var var_Double: Double var var_Char: Unicode.Scalar // CHECK-LABEL: @objc var var_Char: Unicode.Scalar //===--- Tuples. var var_tuple1: () // CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: () @objc var var_tuple1_: () // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple2: Void // CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void @objc var var_tuple2_: Void // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple3: (Int) // CHECK-LABEL: @objc var var_tuple3: (Int) @objc var var_tuple3_: (Int) // no-error var var_tuple4: (Int, Int) // CHECK-LABEL: {{^}} var var_tuple4: (Int, Int) @objc var var_tuple4_: (Int, Int) // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{tuples cannot be represented in Objective-C}} //===--- Stdlib integer types. var var_Int8: Int8 var var_Int16: Int16 var var_Int32: Int32 var var_Int64: Int64 // CHECK-LABEL: @objc var var_Int8: Int8 // CHECK-LABEL: @objc var var_Int16: Int16 // CHECK-LABEL: @objc var var_Int32: Int32 // CHECK-LABEL: @objc var var_Int64: Int64 var var_UInt8: UInt8 var var_UInt16: UInt16 var var_UInt32: UInt32 var var_UInt64: UInt64 // CHECK-LABEL: @objc var var_UInt8: UInt8 // CHECK-LABEL: @objc var var_UInt16: UInt16 // CHECK-LABEL: @objc var var_UInt32: UInt32 // CHECK-LABEL: @objc var var_UInt64: UInt64 var var_OpaquePointer: OpaquePointer // CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer var var_PlainClass: PlainClass // CHECK-LABEL: {{^}} var var_PlainClass: PlainClass @objc var var_PlainClass_: PlainClass // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} var var_PlainStruct: PlainStruct // CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct @objc var var_PlainStruct_: PlainStruct // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} var var_PlainEnum: PlainEnum // CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum @objc var var_PlainEnum_: PlainEnum // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} var var_PlainProtocol: PlainProtocol // CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol @objc var var_PlainProtocol_: PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_ClassObjC: Class_ObjC1 // CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1 @objc var var_ClassObjC_: Class_ObjC1 // no-error var var_ProtocolClass: Protocol_Class1 // CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1 @objc var var_ProtocolClass_: Protocol_Class1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_ProtocolObjC: Protocol_ObjC1 // CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1 @objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error var var_PlainClassMetatype: PlainClass.Type // CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type @objc var var_PlainClassMetatype_: PlainClass.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainStructMetatype: PlainStruct.Type // CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type @objc var var_PlainStructMetatype_: PlainStruct.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainEnumMetatype: PlainEnum.Type // CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type @objc var var_PlainEnumMetatype_: PlainEnum.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainExistentialMetatype: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type @objc var var_PlainExistentialMetatype_: PlainProtocol.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ClassObjCMetatype: Class_ObjC1.Type // CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type @objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error var var_ProtocolClassMetatype: Protocol_Class1.Type // CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type @objc var var_ProtocolClassMetatype_: Protocol_Class1.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type @objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type @objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error var var_AnyObject1: AnyObject var var_AnyObject2: AnyObject.Type // CHECK-LABEL: @objc var var_AnyObject1: AnyObject // CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type var var_Existential0: Any // CHECK-LABEL: @objc var var_Existential0: Any @objc var var_Existential0_: Any var var_Existential1: PlainProtocol // CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol @objc var var_Existential1_: PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential2: PlainProtocol & PlainProtocol // CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol @objc var var_Existential2_: PlainProtocol & PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential3: PlainProtocol & Protocol_Class1 // CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1 @objc var var_Existential3_: PlainProtocol & Protocol_Class1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential4: PlainProtocol & Protocol_ObjC1 // CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1 @objc var var_Existential4_: PlainProtocol & Protocol_ObjC1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential5: Protocol_Class1 // CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1 @objc var var_Existential5_: Protocol_Class1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential6: Protocol_Class1 & Protocol_Class2 // CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2 @objc var var_Existential6_: Protocol_Class1 & Protocol_Class2 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1 // CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1 @objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential8: Protocol_ObjC1 // CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1 @objc var var_Existential8_: Protocol_ObjC1 // no-error var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2 // CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2 @objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error var var_ExistentialMetatype0: Any.Type var var_ExistentialMetatype1: PlainProtocol.Type var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type var var_ExistentialMetatype5: (Protocol_Class1).Type var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type var var_ExistentialMetatype8: Protocol_ObjC1.Type var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type // CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> var var_UnsafeMutablePointer100: UnsafeMutableRawPointer var var_UnsafeMutablePointer101: UnsafeMutableRawPointer var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> // CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> // CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> // CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> // CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> // CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> // CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> // CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> // CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> var var_Optional1: Class_ObjC1? var var_Optional2: Protocol_ObjC1? var var_Optional3: Class_ObjC1.Type? var var_Optional4: Protocol_ObjC1.Type? var var_Optional5: AnyObject? var var_Optional6: AnyObject.Type? var var_Optional7: String? var var_Optional8: Protocol_ObjC1? var var_Optional9: Protocol_ObjC1.Type? var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)? var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type? var var_Optional12: OpaquePointer? var var_Optional13: UnsafeMutablePointer<Int>? var var_Optional14: UnsafeMutablePointer<Class_ObjC1>? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>? var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! var var_ImplicitlyUnwrappedOptional5: AnyObject! var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! var var_ImplicitlyUnwrappedOptional7: String! var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1! var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)! var var_Optional_fail1: PlainClass? var var_Optional_fail2: PlainClass.Type? var var_Optional_fail3: PlainClass! var var_Optional_fail4: PlainStruct? var var_Optional_fail5: PlainStruct.Type? var var_Optional_fail6: PlainEnum? var var_Optional_fail7: PlainEnum.Type? var var_Optional_fail8: PlainProtocol? var var_Optional_fail10: PlainProtocol? var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)? var var_Optional_fail12: Int? var var_Optional_fail13: Bool? var var_Optional_fail14: CBool? var var_Optional_fail20: AnyObject?? var var_Optional_fail21: AnyObject.Type?? var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type var var_Optional_fail23: NSRange? // a bridged struct imported from C // CHECK-NOT: @objc{{.*}}Optional_fail // CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> () var var_CFunctionPointer_1: @convention(c) () -> () // CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}} // CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} // <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} weak var var_Weak1: Class_ObjC1? weak var var_Weak2: Protocol_ObjC1? // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //weak var var_Weak3: Class_ObjC1.Type? //weak var var_Weak4: Protocol_ObjC1.Type? weak var var_Weak5: AnyObject? //weak var var_Weak6: AnyObject.Type? weak var var_Weak7: Protocol_ObjC1? weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)? // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)? weak var var_Weak_fail1: PlainClass? weak var var_Weak_bad2: PlainStruct? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} weak var var_Weak_bad3: PlainEnum? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} weak var var_Weak_bad4: String? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Weak_fail unowned var var_Unowned1: Class_ObjC1 unowned var var_Unowned2: Protocol_ObjC1 // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //unowned var var_Unowned3: Class_ObjC1.Type //unowned var var_Unowned4: Protocol_ObjC1.Type unowned var var_Unowned5: AnyObject //unowned var var_Unowned6: AnyObject.Type unowned var var_Unowned7: Protocol_ObjC1 unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2 // CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject // CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2 unowned var var_Unowned_fail1: PlainClass unowned var var_Unowned_bad2: PlainStruct // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} unowned var var_Unowned_bad3: PlainEnum // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} unowned var var_Unowned_bad4: String // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Unowned_fail var var_FunctionType1: () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> () var var_FunctionType2: (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> () var var_FunctionType3: (Int) -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int var var_FunctionType4: (Int, Double) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> () var var_FunctionType5: (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> () var var_FunctionType6: () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String var var_FunctionType7: (PlainClass) -> () // CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> () var var_FunctionType8: () -> PlainClass // CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass var var_FunctionType9: (PlainStruct) -> () // CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> () var var_FunctionType10: () -> PlainStruct // CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct var var_FunctionType11: (PlainEnum) -> () // CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> () var var_FunctionType12: (PlainProtocol) -> () // CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> () var var_FunctionType13: (Class_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> () var var_FunctionType14: (Protocol_Class1) -> () // CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> () var var_FunctionType15: (Protocol_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> () var var_FunctionType16: (AnyObject) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> () var var_FunctionType17: (() -> ()) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> () var var_FunctionType18: ((Int) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> () var var_FunctionType19: ((String) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> () var var_FunctionTypeReturn1: () -> () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> () @objc var var_FunctionTypeReturn1_: () -> () -> () // no-error var var_FunctionTypeReturn2: () -> (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> () @objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error var var_FunctionTypeReturn3: () -> () -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int @objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error var var_FunctionTypeReturn4: () -> (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> () @objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error var var_FunctionTypeReturn5: () -> () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String @objc var var_FunctionTypeReturn5_: () -> () -> String // no-error var var_BlockFunctionType1: @convention(block) () -> () // CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> () @objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error var var_ArrayType1: [AnyObject] // CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject] @objc var var_ArrayType1_: [AnyObject] // no-error var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] @objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error var var_ArrayType3: [PlainStruct] // CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct] @objc var var_ArrayType3_: [PlainStruct] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error // CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject] @objc var var_ArrayType4_: [(AnyObject) -> AnyObject] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType5: [Protocol_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1] @objc var var_ArrayType5_: [Protocol_ObjC1] // no-error var var_ArrayType6: [Class_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1] @objc var var_ArrayType6_: [Class_ObjC1] // no-error var var_ArrayType7: [PlainClass] // CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass] @objc var var_ArrayType7_: [PlainClass] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType8: [PlainProtocol] // CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol] @objc var var_ArrayType8_: [PlainProtocol] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol] // CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1] @objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2] // CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2] @objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2] // no-error var var_ArrayType11: [Any] // CHECK-LABEL: @objc var var_ArrayType11: [Any] @objc var var_ArrayType11_: [Any] var var_ArrayType13: [Any?] // CHECK-LABEL: {{^}} var var_ArrayType13: [Any?] @objc var var_ArrayType13_: [Any?] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType15: [AnyObject?] // CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?] @objc var var_ArrayType15_: [AnyObject?] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]] @objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error // CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]] @objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} } @objc class ObjCBase {} class infer_instanceVar2< GP_Unconstrained, GP_PlainClass : PlainClass, GP_PlainProtocol : PlainProtocol, GP_Class_ObjC : Class_ObjC1, GP_Protocol_Class : Protocol_Class1, GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase { // CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} { override init() {} var var_GP_Unconstrained: GP_Unconstrained // CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained @objc var var_GP_Unconstrained_: GP_Unconstrained // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainClass: GP_PlainClass // CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass @objc var var_GP_PlainClass_: GP_PlainClass // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainProtocol: GP_PlainProtocol // CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol @objc var var_GP_PlainProtocol_: GP_PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Class_ObjC: GP_Class_ObjC // CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC @objc var var_GP_Class_ObjC_: GP_Class_ObjC // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_Class: GP_Protocol_Class // CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class @objc var var_GP_Protocol_Class_: GP_Protocol_Class // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC // CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC @objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} func func_GP_Unconstrained(a: GP_Unconstrained) {} // CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) { @objc func func_GP_Unconstrained_(a: GP_Unconstrained) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} @objc func func_GP_Unconstrained_() -> GP_Unconstrained {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} @objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} } class infer_instanceVar3 : Class_ObjC1 { // CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 { var v1: Int = 0 // CHECK-LABEL: @objc @_hasInitialValue var v1: Int } @objc protocol infer_instanceVar4 { // CHECK-LABEL: @objc protocol infer_instanceVar4 { var v1: Int { get } // CHECK-LABEL: @objc var v1: Int { get } } // @!objc class infer_instanceVar5 { // CHECK-LABEL: {{^}}class infer_instanceVar5 { @objc var intstanceVar1: Int { // CHECK: @objc var intstanceVar1: Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc class infer_staticVar1 { // CHECK-LABEL: @objc class infer_staticVar1 { class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} // CHECK: @objc @_hasInitialValue class var staticVar1: Int } // @!objc class infer_subscript1 { // CHECK-LABEL: class infer_subscript1 @objc subscript(i: Int) -> Int { // CHECK: @objc subscript(i: Int) -> Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc protocol infer_throughConformanceProto1 { // CHECK-LABEL: @objc protocol infer_throughConformanceProto1 { func funcObjC1() var varObjC1: Int { get } var varObjC2: Int { get set } // CHECK: @objc func funcObjC1() // CHECK: @objc var varObjC1: Int { get } // CHECK: @objc var varObjC2: Int { get set } } class infer_class1 : PlainClass {} // CHECK-LABEL: {{^}}class infer_class1 : PlainClass { class infer_class2 : Class_ObjC1 {} // CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 { class infer_class3 : infer_class2 {} // CHECK-LABEL: @objc class infer_class3 : infer_class2 { class infer_class4 : Protocol_Class1 {} // CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 { class infer_class5 : Protocol_ObjC1 {} // CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 { // // If a protocol conforms to an @objc protocol, this does not infer @objc on // the protocol itself, or on the newly introduced requirements. Only the // inherited @objc requirements get @objc. // // Same rule applies to classes. // protocol infer_protocol1 { // CHECK-LABEL: {{^}}protocol infer_protocol1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol2 : Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol3 : Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } class C { // Don't crash. @objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} @IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} } //===--- //===--- @IBOutlet implies @objc //===--- class HasIBOutlet { // CHECK-LABEL: {{^}}class HasIBOutlet { init() {} @IBOutlet weak var goodOutlet: Class_ObjC1! // CHECK-LABEL: {{^}} @objc @IBOutlet @_implicitly_unwrapped_optional @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1! @IBOutlet var badOutlet: PlainStruct // expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}} // expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}} // expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}} // expected-note@-4 {{add '!' to form an implicitly unwrapped optional}} // CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct } //===--- //===--- @IBAction implies @objc //===--- // CHECK-LABEL: {{^}}class HasIBAction { class HasIBAction { @IBAction func goodAction(_ sender: AnyObject?) { } // CHECK: {{^}} @objc @IBAction func goodAction(_ sender: AnyObject?) { @IBAction func badAction(_ sender: PlainStruct?) { } // expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}} } //===--- //===--- @IBInspectable implies @objc //===--- // CHECK-LABEL: {{^}}class HasIBInspectable { class HasIBInspectable { @IBInspectable var goodProperty: AnyObject? // CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject? } //===--- //===--- @GKInspectable implies @objc //===--- // CHECK-LABEL: {{^}}class HasGKInspectable { class HasGKInspectable { @GKInspectable var goodProperty: AnyObject? // CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject? } //===--- //===--- @NSManaged implies @objc //===--- class HasNSManaged { // CHECK-LABEL: {{^}}class HasNSManaged { init() {} @NSManaged var goodManaged: Class_ObjC1 // CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 { // CHECK-NEXT: {{^}} @objc get // CHECK-NEXT: {{^}} @objc set // CHECK-NEXT: {{^}} } @NSManaged var badManaged: PlainStruct // expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // CHECK-LABEL: {{^}} @NSManaged dynamic var badManaged: PlainStruct { // CHECK-NEXT: {{^}} get // CHECK-NEXT: {{^}} set // CHECK-NEXT: {{^}} } } //===--- //===--- Pointer argument types //===--- @objc class TakesCPointers { // CHECK-LABEL: {{^}}@objc class TakesCPointers { func constUnsafeMutablePointer(p: UnsafePointer<Int>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) { func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) { func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) { func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {} // CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) { func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) { func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) { } // @objc with nullary names @objc(NSObjC2) class Class_ObjC2 { // CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2 @objc(initWithMalice) init(foo: ()) { } @objc(initWithIntent) init(bar _: ()) { } @objc(initForMurder) init() { } @objc(isFoo) func foo() -> Bool {} // CHECK-LABEL: @objc(isFoo) func foo() -> Bool { } @objc() // expected-error{{expected name within parentheses of @objc attribute}} class Class_ObjC3 { } // @objc with selector names extension PlainClass { // CHECK-LABEL: @objc(setFoo:) dynamic func @objc(setFoo:) func foo(b: Bool) { } // CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set @objc(setWithRed:green:blue:alpha:) func set(_: Float, green: Float, blue: Float, alpha: Float) { } // CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith @objc(createWithRed:green blue:alpha) class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { } // expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}} // expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}} // CHECK-LABEL: @objc(::) dynamic func badlyNamed @objc(::) func badlyNamed(_: Int, y: Int) {} } @objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}} class BadClass1 { } @objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}} protocol BadProto1 { } @objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}} enum BadEnum1: Int { case X } @objc enum BadEnum2: Int { @objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}} case X } class BadClass2 { @objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}} deinit { } @objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}} var badprop: Int = 5 @objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}} subscript (i: Int) -> Int { get { return i } } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam(x: Int) { } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam2(_: Int) { } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}} func noArgNamesTwoParams(_: Int, y: Int) { } @objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}} func oneArgNameTwoParams(_: Int, y: Int) { } @objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}} func oneArgNameNoParams() { } @objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}} init() { } var _prop = 5 @objc var prop: Int { @objc(property) get { return _prop } @objc(setProperty:) set { _prop = newValue } } var prop2: Int { @objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}} @objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}} } var prop3: Int { @objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}} } @objc subscript (c: Class_ObjC1) -> Class_ObjC1 { @objc(getAtClass:) get { return c } @objc(setAtClass:class:) set { } } } // Swift overrides that aren't also @objc overrides. class Super { @objc(renamedFoo) var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}} @objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}} } class Sub1 : Super { @objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}} override var foo: Int { get { return 5 } } override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}} } class Sub2 : Super { @objc override var foo: Int { get { return 5 } } } class Sub3 : Super { override var foo: Int { get { return 5 } } } class Sub4 : Super { @objc(renamedFoo) override var foo: Int { get { return 5 } } } class Sub5 : Super { @objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}} override var foo: Int { get { return 5 } } } enum NotObjCEnum { case X } struct NotObjCStruct {} // Closure arguments can only be @objc if their parameters and returns are. // CHECK-LABEL: @objc class ClosureArguments @objc class ClosureArguments { // CHECK: @objc func foo @objc func foo(f: (Int) -> ()) {} // CHECK: @objc func bar @objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func bas @objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zim @objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zang @objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} @objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func fooImplicit func fooImplicit(f: (Int) -> ()) {} // CHECK: {{^}} func barImplicit func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {} // CHECK: {{^}} func basImplicit func basImplicit(f: (NotObjCEnum) -> ()) {} // CHECK: {{^}} func zimImplicit func zimImplicit(f: () -> NotObjCStruct) {} // CHECK: {{^}} func zangImplicit func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // CHECK: {{^}} func zangZangImplicit func zangZangImplicit(f: (Int...) -> ()) {} } typealias GoodBlock = @convention(block) (Int) -> () typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}} @objc class AccessControl { // CHECK: @objc func foo func foo() {} // CHECK: {{^}} private func bar private func bar() {} // CHECK: @objc private func baz @objc private func baz() {} } //===--- Ban @objc +load methods class Load1 { // Okay: not @objc class func load() { } class func alloc() {} class func allocWithZone(_: Int) {} class func initialize() {} } @objc class Load2 { class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}} class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}} class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}} } @objc class Load3 { class var load: Load3 { get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}} set { } } @objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}} @objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} @objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}} } // Members of protocol extensions cannot be @objc extension PlainProtocol { @objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } extension Protocol_ObjC1 { @objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } extension Protocol_ObjC1 { // Don't infer @objc for extensions of @objc protocols. // CHECK: {{^}} var propertyOK: Int var propertyOK: Int { return 5 } } //===--- //===--- Error handling //===--- class ClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws @objc func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 @objc func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String @objc func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] @objc func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: @objc init(degrees: Double) throws @objc init(degrees: Double) throws { } // Errors @objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}} @objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}} @objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}} @objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { } // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{throwing function types cannot be represented in Objective-C}} @objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} @objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} @objc func fooWithErrorEnum1(x: ErrorEnum) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}} // CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum) func fooWithErrorEnum2(x: ErrorEnum) {} @objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { } // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}} // CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { } } // CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1" @objc class ImplicitClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws // CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 // CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>> func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) // CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { } // CHECK: @objc init(degrees: Double) throws // CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>> init(degrees: Double) throws { } // CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() } @objc func methodReturnsBridgedValueType2() throws -> NSRange { return NSRange() } // expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}} // CHECK: {{^}} @objc func methodReturnsError() throws -> Error func methodReturnsError() throws -> Error { return ErrorEnum.failed } // CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) { func add(x: Int) -> (Int) -> Int { return { x + $0 } } } } // CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1" @objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 { // CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int)) // CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { } } class ThrowsRedecl1 { @objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}} @objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}} @objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}} @objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}} @objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}} @objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}} @objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}} @objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}} @objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}} @objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}} @objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}} @objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}} } class ThrowsObjCName { @objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { } @objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { } @objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}} @objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}} // CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool @objc(method8:fn1:error:fn2:) func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } // CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool @objc(method9AndReturnError:s:fn1:fn2:) func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } } class SubclassThrowsObjCName : ThrowsObjCName { // CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } // CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } } @objc protocol ProtocolThrowsObjCName { @objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}} } class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName { @objc func doThing(_ x: String) throws -> String { return x } // okay } class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName { @objc func doThing(_ x: Int) throws -> String { return "" } // expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}} // expected-note@-2{{move 'doThing' to an extension to silence this warning}} // expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }} // expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}} } @objc class DictionaryTest { // CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } // CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } func func_dictionary2a(x: Dictionary<String, Int>) { } @objc func func_dictionary2b(x: Dictionary<String, Int>) { } } @objc extension PlainClass { // CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) { final func objc_ext_objc_okay(_: Int) { } final func objc_ext_objc_not_okay(_: PlainStruct) { } // expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { } } @objc class ObjC_Class1 : Hashable { func hash(into hasher: inout Hasher) {} } func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool { return true } // CHECK-LABEL: @objc class OperatorInClass @objc class OperatorInClass { // CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool { return true } // CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass @objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}} return lhs } } // CHECK: {{^}$}} @objc protocol OperatorInProtocol { static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}} } class AdoptsOperatorInProtocol : OperatorInProtocol { static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {} // expected-error@-1 {{operator methods cannot be declared @objc}} } //===--- @objc inference for witnesses @objc protocol InferFromProtocol { @objc(inferFromProtoMethod1:) optional func method1(value: Int) } // Infer when in the same declaration context. // CHECK-LABEL: ClassInfersFromProtocol1 class ClassInfersFromProtocol1 : InferFromProtocol{ // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } // Infer when in a different declaration context of the same class. // CHECK-LABEL: ClassInfersFromProtocol2a class ClassInfersFromProtocol2a { // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } extension ClassInfersFromProtocol2a : InferFromProtocol { } // Infer when in a different declaration context of the same class. class ClassInfersFromProtocol2b : InferFromProtocol { } // CHECK-LABEL: ClassInfersFromProtocol2b extension ClassInfersFromProtocol2b { // CHECK: {{^}} @objc dynamic func method1(value: Int) func method1(value: Int) { } } // Don't infer when there is a signature mismatch. // CHECK-LABEL: ClassInfersFromProtocol3 class ClassInfersFromProtocol3 : InferFromProtocol { } extension ClassInfersFromProtocol3 { // CHECK: {{^}} func method1(value: String) func method1(value: String) { } } // Inference for subclasses. class SuperclassImplementsProtocol : InferFromProtocol { } class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol { // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol { } extension SubclassInfersFromProtocol2 { // CHECK: {{^}} @objc dynamic func method1(value: Int) func method1(value: Int) { } } @objc class NeverReturningMethod { @objc func doesNotReturn() -> Never {} } // SR-5025 class User: NSObject { } @objc extension User { var name: String { get { return "No name" } set { // Nothing } } var other: String { unsafeAddress { // expected-error{{addressors are not allowed to be marked @objc}} } } } // 'dynamic' methods cannot be @inlinable. class BadClass { @inlinable @objc dynamic func badMethod1() {} // expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}} } @objc protocol ObjCProtocolWithWeakProperty { weak var weakProp: AnyObject? { get set } // okay } @objc protocol ObjCProtocolWithUnownedProperty { unowned var unownedProp: AnyObject { get set } // okay } // rdar://problem/46699152: errors about read/modify accessors being implicitly // marked @objc. @objc class MyObjCClass: NSObject {} @objc extension MyObjCClass { @objc static var objCVarInObjCExtension: Bool { get { return true } set {} } // CHECK: {{^}} @objc private dynamic func stillExposedToObjCDespiteBeingPrivate() private func stillExposedToObjCDespiteBeingPrivate() {} } @objc private extension MyObjCClass { // CHECK: {{^}} @objc dynamic func alsoExposedToObjCDespiteBeingPrivate() func alsoExposedToObjCDespiteBeingPrivate() {} } @objcMembers class VeryObjCClass: NSObject { // CHECK: {{^}} private func notExposedToObjC() private func notExposedToObjC() {} } // SR-9035 class SR_9035_C {} @objc protocol SR_9035_P { func throwingMethod1() throws -> Unmanaged<CFArray> // Ok func throwingMethod2() throws -> Unmanaged<SR_9035_C> // expected-error {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}} // expected-note@-1 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} }
apache-2.0
c310fd57fbc7d22cac353e9a5d947fd4
39.526941
350
0.703691
3.901564
false
false
false
false
wavecos/curso_ios_3
Playgrounds/Funciones.playground/section-1.swift
1
896
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" func imprimirSaludo() { println("hola a todos") } imprimirSaludo() func verificarHabilitacion(nombre : String, edad : Int) { if (edad > 18) { println("Hola \(nombre) tu puedes ir a votar en las elecciones") } else { println("hola \(nombre), eres menor de edad para estas elecciones") } } verificarHabilitacion("Juanelo", 32) verificarHabilitacion("Godines", 12) func notaFinal(nota1 : Int, nota2: Int, nota3: Int) -> Double { let final = Double(nota1 + nota2 + nota3) / 3 return final } var notaJuan = notaFinal(34, 56, 98) var notaPedro = notaFinal(54, 78, 81) println("La nota de Ana es \(notaFinal(12,54,82)) ") func destruirPais(pais : String = "Thailandia") { println("Lanzando misiles nucleares a \(pais)") } //destruirPais(pais: "Siria") destruirPais()
apache-2.0
b5c10cd9c2f65e39b57c44e4a168f7a5
18.06383
71
0.68192
2.682635
false
false
false
false
IngmarStein/swift
validation-test/Reflection/inherits_NSObject.swift
3
2257
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/inherits_NSObject // RUN: %target-run %target-swift-reflection-test %t/inherits_NSObject | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import Foundation import SwiftReflectionTest class InheritsNSObject : NSObject {} class ContainsInheritsNSObject : NSObject { var a: InheritsNSObject var _b: InheritsNSObject var b: InheritsNSObject { get { return _b } set (newVal) { _b = newVal } } override init() { a = InheritsNSObject() _b = InheritsNSObject() } } let inheritsNSObject = InheritsNSObject() reflect(object: inheritsNSObject) // CHECK-64: Reflecting an object. // CHECK-64: Type reference: // CHECK-64: (class inherits_NSObject.InheritsNSObject) // CHECK-64: Type info: // CHECK-64: (class_instance size=8 alignment=16 stride=16 num_extra_inhabitants=0) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_NSObject.InheritsNSObject) // CHECK-32: Type info: // CHECK-32: (class_instance size=4 alignment=16 stride=16 num_extra_inhabitants=0) let sc = ContainsInheritsNSObject() reflect(object: sc) // CHECK-64: Reflecting an object. // CHECK-64: Type reference: // CHECK-64: (class inherits_NSObject.ContainsInheritsNSObject) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-64-NEXT: (field name=a offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=_b offset=16 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_NSObject.ContainsInheritsNSObject) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=16 stride=16 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=a offset=4 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=_b offset=8 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown))) doneReflecting()
apache-2.0
25fc71ee5407aa1e1681561d1d34201c
31.242857
144
0.701817
3.404223
false
true
false
false
viWiD/Persist
Sources/Persist/Identifyable.swift
1
10076
// // Identifyable.swift // Pods // // Created by Nils Fischer on 04.04.16. // // import Foundation import CoreData import Evergreen import Freddy public protocol Identifyable: EntityRepresentable { static var identificationAttributeName: String { get } static var superentitySharingIdentification: Identifyable.Type? { get } } public extension Identifyable { public static var superentitySharingIdentification: Identifyable.Type? { return nil } } // MARK: - Stubbing /// - warning: Only call on `context`'s queue using `performBlock`. internal func stub(objectOfEntity entityType: Identifyable.Type, withIdentificationValue identificationValue: JSON, context: NSManagedObjectContext) throws -> NSManagedObject { let logger = Evergreen.getLogger("Persist.Stub") // retrieve identification value let primitiveIdentification = try primitiveIdentificationValue(ofEntity: entityType, fromJSON: identificationValue, context: context) // retrieve matching existing objects let identificationPredicate = NSPredicate(format: "%K = %@", entityType.identificationAttributeName, primitiveIdentification) let objects = try existingObjects(ofEntity: entityType, includingSuperentitySharingIdentification: true, matching: identificationPredicate, context: context) if objects.count > 0 { // found existing object if objects.count > 1 { logger.warning("Found multiple existing objects of entity \(entityType.entityName) with identification value \(identificationValue), choosing any: \(objects)") } var object = objects.first! logger.verbose("Found existing object of entity \(entityType.entityName) for representation: \(object)") // make sure the object is of the correct type, and not a stub of a superentity object = try ensureEntity(entityType.self, forObject: object) return object } else { // create object // TODO: option to disable stubbing logger.debug("Could not find object of entity \(entityType.entityName) with identification value \(identificationValue), creating one.") let object = createObject(ofEntity: entityType.self, withPrimitiveIdentificationValue: primitiveIdentification, context: context) return object } } /// - warning: Only call on `context`'s queue using `performBlock`. private func createObject(ofEntity entityType: Identifyable.Type, withPrimitiveIdentificationValue primitiveIdentificationValue: PrimitiveValue, context: NSManagedObjectContext) -> NSManagedObject { let object = NSEntityDescription.insertNewObjectForEntityForName(entityType.entityName, inManagedObjectContext: context) object.setValue(primitiveIdentificationValue, forKey: entityType.identificationAttributeName) return object } /// - warning: Only call on `context`'s queue using `performBlock`. private func existingObjects(ofEntity entityType: Identifyable.Type, includingSuperentitySharingIdentification: Bool, matching predicate: NSPredicate, context: NSManagedObjectContext) throws -> [NSManagedObject] { let logger = Evergreen.getLogger("Persist.Stub") guard let entity = NSEntityDescription.entityForName(entityType.entityName, inManagedObjectContext: context) else { throw FillError.UnknownEntity(named: entityType.entityName) } let identificationEntity: Identifyable.Type if let superentitySharingIdentification = entityType.superentitySharingIdentification where includingSuperentitySharingIdentification { guard let superentity = NSEntityDescription.entityForName(superentitySharingIdentification.entityName, inManagedObjectContext: context) else { throw FillError.UnknownEntity(named: superentitySharingIdentification.entityName) } guard entity.isSubentityOf(superentity) || entity.isKindOfEntity(superentity) else { throw FillError.NotSubentity(named: entity.name ?? "", ofEntityNamed: superentity.name ?? "") } // TODO: validate that superentity has the same identification property necessary? identificationEntity = superentitySharingIdentification logger.debug("\(entityType) shares identification with \(superentitySharingIdentification), using for fetch...", onceForKey: "notify_superentity_sharing_identification_\(entityType.entityName)") } else { identificationEntity = entityType } let fetchRequest = NSFetchRequest(entityName: identificationEntity.entityName) fetchRequest.includesSubentities = true // TODO: is this always good? fetchRequest.includesPendingChanges = true fetchRequest.predicate = predicate return try context.executeFetchRequest(fetchRequest) as! [NSManagedObject] // TODO: is this force cast safe and reasonable? } private extension NSEntityDescription { func isSubentityOf(entity: NSEntityDescription) -> Bool { guard let superentity = self.superentity else { return false } if superentity.isKindOfEntity(entity) { return true } return superentity.isSubentityOf(entity) } } /// - warning: Only call on `object.managedObjectContext`'s queue using `performBlock`. private func ensureEntity(entityType: EntityRepresentable.Type, forObject object: NSManagedObject) throws -> NSManagedObject { let logger = Evergreen.getLogger("Persist.Stub") guard let context = object.managedObjectContext else { throw FillError.ContextUnavailable } guard let entity = NSEntityDescription.entityForName(entityType.entityName, inManagedObjectContext: context) else { throw FillError.UnknownEntity(named: entityType.entityName) } if object.entity.isKindOfEntity(entity) { return object } else { logger.debug("Deleting \(object) to replace it with an object of entity \(entityType.entityName)...") guard entity.isSubentityOf(object.entity) else { throw FillError.NotSubentity(named: entity.name ?? "", ofEntityNamed: object.entity.name ?? "") } let replacement = NSEntityDescription.insertNewObjectForEntityForName(entityType.entityName, inManagedObjectContext: context) replacement.setValuesForKeysWithDictionary(object.dictionaryWithValuesForKeys(Array(object.entity.propertiesByName.keys))) context.deleteObject(object) logger.debug("Got replacement \(object).") return replacement } } // MARK: - Orphans /// - warning: Only call on `context`'s queue using `performBlock`. internal func deleteOrphans(ofEntity entityType: Persistable.Type, onlyKeeping objectsRepresentation: JSON, context: NSManagedObjectContext, scope: NSPredicate?) throws { let traceLogger = Evergreen.getLogger("Persist.Trace") traceLogger.verbose("Deleting orphans of \(entityType)...") let logger = Evergreen.getLogger("Persist.DeleteOrphans") // obtain identification values to keep let primitiveIdentificationValuesToKeep = try primitiveIdentificationValues(ofEntity: entityType, withRepresentation: objectsRepresentation, context: context) logger.verbose("Keeping objects with identification values \(primitiveIdentificationValuesToKeep).") // retrieve orphans var orphanPredicate = NSPredicate(format: "NOT %K IN %@", entityType.identificationAttributeName, primitiveIdentificationValuesToKeep) if let scope = scope { logger.debug("Limiting orphan deletion to scope \(scope).") orphanPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ scope, orphanPredicate ]) } let orphans = try existingObjects(ofEntity: entityType.self, includingSuperentitySharingIdentification: false, matching: orphanPredicate, context: context) // delete orphans orphans.forEach({ context.deleteObject($0) }) if orphans.count == 0 { logger.debug("No orphans to delete.") } else { logger.debug("Found and deleted \(orphans.count) orphans.") } } private func primitiveIdentificationValues(ofEntity entityType: Persistable.Type, withRepresentation objectsRepresentation: JSON, context: NSManagedObjectContext) throws -> [PrimitiveValue] { guard let identificationProperty = entityType.identificationProperty else { throw FillError.IdentificationPropertyNotFound(ofEntityNamed: entityType.entityName) } return try objectsRepresentation.map( identificationValueTransform: { identificationValue in try primitiveIdentificationValue(ofEntity: entityType.self, fromJSON: identificationValue, context: context) }, propertyValuesTransform: { propertyValues in guard let identificationValue = propertyValues[identificationProperty.key] else { throw FillError.IdentificationValueNotFound(key: identificationProperty.key) } return try primitiveIdentificationValue(ofEntity: entityType.self, fromJSON: identificationValue, context: context) } ) } private func primitiveIdentificationValue(ofEntity entityType: Identifyable.Type, fromJSON identificationValueJSON: JSON, context: NSManagedObjectContext) throws -> PrimitiveValue { guard let entity = NSEntityDescription.entityForName(entityType.entityName, inManagedObjectContext: context) else { throw FillError.UnknownEntity(named: entityType.entityName) } guard let identificationAttribute = entity.attributesByName[entityType.identificationAttributeName] else { throw FillError.IdentificationAttributeNotFound(named: entityType.identificationAttributeName, entityName: entityType.entityName) } let possibleIdentificationValue = try identificationValueJSON.transformedTo(identificationAttribute.attributeType) guard let identificationValue = possibleIdentificationValue else { throw FillError.InvalidIdentificationValue(possibleIdentificationValue) } return identificationValue }
mit
d0508c4b4d2a3e1f41950736d59ebfe3
46.084112
213
0.745335
5.365282
false
false
false
false
Cocoanetics/XLIFFix
App/Source/XLIFFParser.swift
1
1939
// // XLIFFParser.swift // XLIFFix // // Created by Oliver Drobnik on 02.11.15. // Copyright © 2015 Cocoanetics. All rights reserved. // import Foundation class XLIFFParser: NSObject, XMLParserDelegate { var currentFile: OriginalFile? var currentTransUnit: TransUnit? var currentString: String? internal var files: [OriginalFile] = [] init?(data: Data) { super.init() let parser = XMLParser(data: data) parser.delegate = self guard parser.parse() else { return nil } } // MARK: - NSXMLParserDelegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if (elementName == "file") { let newFile = OriginalFile() newFile.attributeDict = attributeDict files.append(newFile) currentFile = newFile } else if (elementName == "trans-unit") { guard let file = currentFile else { return } if file.transUnits == nil { file.transUnits = [] } currentTransUnit = TransUnit() currentTransUnit!.attributeDict = attributeDict file.transUnits!.append(currentTransUnit!) } // new element always starts a new string currentString = "" } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if (elementName == "file") { currentFile = nil } else if (elementName == "trans-unit") { currentTransUnit = nil } else if (elementName == "source") { currentTransUnit?.source = currentString } else if (elementName == "target") { currentTransUnit?.target = currentString } else if (elementName == "note") { currentTransUnit?.note = currentString } // end of element always stops string currentString = "" } func parser(_ parser: XMLParser, foundCharacters string: String) { currentString! += string } }
mit
879d7ee7cf75183986a9736d28464836
19.83871
168
0.675955
3.5625
false
false
false
false
crashoverride777/Swift-2-iAds-AdMob-CustomAds-Helper
Demos/UIKit/SwiftyAdsDemo/Scenes/Demo/Detail/Tab Bar/TabBarControllerAd.swift
2
2647
import UIKit final class TabBarControllerAd: UITabBarController { // MARK: - Properties private let swiftyAds: SwiftyAdsType private var bannerAd: SwiftyAdsBannerType? // MARK: - Initialization init(swiftyAds: SwiftyAdsType) { self.swiftyAds = swiftyAds super.init(nibName: nil, bundle: nil) tabBar.barTintColor = .white // Create tab view controllers let firstViewController = UIViewController() firstViewController.view.backgroundColor = .blue firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 0) let secondViewController = UIViewController() secondViewController.view.backgroundColor = .red secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 1) // Set view controllers viewControllers = [firstViewController, secondViewController] } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - De-Initialization deinit { print("Deinit TabBarControllerAd") } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() bannerAd = swiftyAds.makeBannerAd( in: self, adUnitIdType: .plist, position: .bottom(isUsingSafeArea: true), animation: .slide(duration: 1.5), onOpen: { print("SwiftyAds banner ad did open") }, onClose: { print("SwiftyAds banner ad did close") }, onError: { error in print("SwiftyAds banner ad error \(error)") }, onWillPresentScreen: { print("SwiftyAds banner ad was tapped and is about to present screen") }, onWillDismissScreen: { print("SwiftyAds banner ad screen is about to be dismissed") }, onDidDismissScreen: { print("SwiftyAds banner did dismiss screen") } ) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) bannerAd?.show(isLandscape: view.frame.width > view.frame.height) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] _ in self?.bannerAd?.show(isLandscape: size.width > size.height) }) } }
mit
f3e1aba1f63ffcfd3557c9feac7d90da
31.280488
112
0.602569
5.325956
false
false
false
false
terietor/GTTableView
Source/View Controllers/Async/AsyncTableViewController.swift
1
3621
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[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 open class AsyncTableViewController: TableViewController, AsyncDataSourceDelegate { open var shouldPerformPullToRefresh: Bool { return true } open override var dataSource: DataSourceType! { didSet { let errorMessage = "This TableView requires a AsyncDataSource." + "Maybe you should use TableViewController instead." + "Also you don't have to create this dataSource, just use sectionsForTableView" guard let _ = self.dataSource as? AsyncDataSource else { fatalError(errorMessage) } } } open override func viewDidLoad() { super.viewDidLoad() var dataSource = AsyncDataSource( tableView: self.tableView, sections: self.sectionsForTableView() ) dataSource.delegate = self defer { self.dataSource = dataSource } if self.shouldPerformPullToRefresh { self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget( self, action: #selector(refreshControlValueDidChange), for: .valueChanged ) self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull Me..") self.refreshControl?.beginRefreshing() self.refreshControl?.endRefreshing() dataSource.pullToRefreshDidEnd = { [weak self] in guard let weakSelf = self else { return } weakSelf.refreshControl?.attributedTitle = NSAttributedString(string: "Pull Me..") weakSelf.refreshControl?.endRefreshing() } } } /** This method will be called before "pull to refresh" calls `loadData` */ open func pullToRefreshWillStart() { } open func willLoadData() {} open func loadData(_ completed: @escaping () -> ()) { fatalError("Implementation is missing \(type(of: self))") } open func didLoadData() {} open func sectionsForTableView() -> [TableViewSectionType] { fatalError("Missing Implementation \(type(of: self))") } @objc private func refreshControlValueDidChange() { self.refreshControl?.attributedTitle = NSAttributedString(string: "Loading..") pullToRefreshWillStart() self.dataSource.reloadData() } }
mit
bd68de90a69cb5fbad13fe2f118a5626
34.5
109
0.652582
5.340708
false
false
false
false
mownier/photostream
Photostream/Modules/Follow List/Presenter/FollowListPresenter.swift
1
6194
// // FollowListPresenter.swift // Photostream // // Created by Mounir Ybanez on 17/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // protocol FollowListPresenterInterface: BaseModulePresenter, BaseModuleInteractable, BaseModuleDelegatable { var userId: String { set get } var limit: UInt { set get } var fetchType: FollowListFetchType { set get } var list: [FollowListDisplayData] { set get } var isMe: Bool { set get } func append(itemsOf data: [FollowListData]) func index(of userId: String) -> Int? } class FollowListPresenter: FollowListPresenterInterface { typealias ModuleView = FollowListScene typealias ModuleInteractor = FollowListInteractorInput typealias ModuleWireframe = FollowListWireframeInterface typealias ModuleDelegate = FollowListDelegate weak var delegate: ModuleDelegate? weak var view: ModuleView! var interactor: ModuleInteractor! var wireframe: ModuleWireframe! var userId: String = "" var limit: UInt = 20 var fetchType: FollowListFetchType = .following var list = [FollowListDisplayData]() var isMe: Bool = false func append(itemsOf data: [FollowListData]) { for entry in data { guard index(of: entry.userId) == nil else { return } var item = FollowListDisplayDataItem() item.avatarUrl = entry.avatarUrl item.displayName = entry.displayName item.isFollowing = entry.isFollowing item.isMe = entry.isMe item.userId = entry.userId list.append(item) } } func index(of userId: String) -> Int? { return list.index { displayData -> Bool in return displayData.userId == userId } } } extension FollowListPresenter: FollowListModuleInterface { var listCount: Int { return list.count } var navigationItemTitle: String { switch fetchType { case .followers: return "Followers" case .following: return "Following" } } func exit() { var property = WireframeExitProperty() property.controller = view.controller wireframe.exit(with: property) } func listItem(at index: Int) -> FollowListDisplayData? { guard list.isValid(index) else { return nil } return list[index] } func viewDidLoad() { initialLoad() } func initialLoad() { view.isLoadingViewHidden = false view.isEmptyViewHidden = true interactor.fetchNew(userId: userId, type: fetchType, limit: limit) } func refresh() { view.isRefreshingViewHidden = false view.isEmptyViewHidden = true interactor.fetchNew(userId: userId, type: fetchType, limit: limit) } func loadMore() { interactor.fetchNext(userId: userId, type: fetchType, limit: limit) } func toggleFollow(at index: Int) { guard let listItem = listItem(at: index) else { return } if listItem.isFollowing { unfollow(at: index) } else { follow(at: index) } } func follow(at index: Int) { guard var listItem = listItem(at: index) else { view.didFollow(with: "Can not follow user rignt now") return } listItem.isBusy = true list[index] = listItem view.reloadItem(at: index) interactor.follow(userId: listItem.userId) } func unfollow(at index: Int) { guard var listItem = listItem(at: index) else { view.didUnfollow(with: "Can not unfollow user rignt now") return } listItem.isBusy = true list[index] = listItem view.reloadItem(at: index) interactor.unfollow(userId: listItem.userId) } } extension FollowListPresenter: FollowListInteractorOutput { func didFetchNew(with data: [FollowListData]) { view.isLoadingViewHidden = true view.isRefreshingViewHidden = true list.removeAll() append(itemsOf: data) if list.count == 0 { view.isEmptyViewHidden = false } view.didRefresh(with: nil) view.reload() } func didFetchNext(with data: [FollowListData]) { view.didLoadMore(with: nil) guard data.count > 0 else { return } append(itemsOf: data) view.reload() } func didFetchNew(with error: UserServiceError) { view.isLoadingViewHidden = true view.isRefreshingViewHidden = true view.didRefresh(with: error.message) } func didFetchNext(with error: UserServiceError) { view.didLoadMore(with: error.message) } func didFollow(with error: UserServiceError?, userId: String) { if let index = index(of: userId) { var item = list[index] item.isBusy = false if error == nil { item.isFollowing = true } list[index] = item view.reloadItem(at: index) } view.didFollow(with: error?.message) if error == nil { delegate?.followListDidFollow(isMe: isMe) } } func didUnfollow(with error: UserServiceError?, userId: String) { if let index = index(of: userId) { var item = list[index] item.isBusy = false if error == nil { item.isFollowing = false } list[index] = item view.reloadItem(at: index) } view.didUnfollow(with: error?.message) if error == nil { delegate?.followListDidUnfollow(isMe: isMe) } } }
mit
1e8027be05e92d17a8a61dc26cffada7
25.021008
107
0.557726
4.857255
false
false
false
false
0x73/SugarRecord
library/CoreData/Base/iCloudCDStack.swift
1
15532
// // iCloudCDStack.swift // SugarRecord // // Created by Pedro Piñera Buendía on 12/10/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import CoreData /** * Struct with the needed information to initialize the iCloud stack */ public struct iCloudData { /// Is the full AppID (including the Team Prefix). It's needed to change tihs to match the Team Prefix found in the iOS Provisioning profile internal let iCloudAppID: String /// Is the name of the directory where the database will be stored in. It should always end with .nosync internal let iCloudDataDirectoryName: String = "Data.nosync" /// Is the name of the directory where the database change logs will be stored in internal let iCloudLogsDirectory: String = "Logs" /** Note: iCloudData = iCloud + DataDirectory iCloudLogs = iCloud + LogsDirectory */ /** Initializer for the struct :param: iCloudAppID iCloud app identifier :param: iCloudDataDirectoryName Directory of the database :param: iCloudLogsDirectory Directory of the database logs :returns: Initialized struct */ public init (iCloudAppID: String, iCloudDataDirectoryName: String?, iCloudLogsDirectory: String?) { self.iCloudAppID = iCloudAppID if (iCloudDataDirectoryName != nil) {self.iCloudDataDirectoryName = iCloudDataDirectoryName!} if (iCloudLogsDirectory != nil) {self.iCloudLogsDirectory = iCloudLogsDirectory!} } } /** * iCloud stack for SugarRecord */ public class iCloudCDStack: DefaultCDStack { //MARK: - Properties /// iCloud Data struct with the information private let icloudData: iCloudData? /// Notification center used for iCloud Notifications lazy var notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter() /** Initialize the CoreData stack :param: databaseURL NSURL with the database path :param: model NSManagedObjectModel with the database model :param: automigrating Bool Indicating if the migration has to be automatically executed :param: icloudData iCloudData information :returns: iCloudCDStack object */ public init(databaseURL: NSURL, model: NSManagedObjectModel?, automigrating: Bool, icloudData: iCloudData) { super.init(databaseURL: databaseURL, model: model, automigrating: automigrating) self.icloudData = icloudData self.automigrating = automigrating self.databasePath = databaseURL self.managedObjectModel = model self.migrationFailedClosure = {} self.name = "iCloudCoreDataStack" self.stackDescription = "Stack to connect your local storage with iCloud" } /** Initialize the CoreData default stack passing the database name and a flag indicating if the automigration has to be automatically executed :param: databaseName String with the database name :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseName: String, icloudData: iCloudData) { self.init(databaseURL: iCloudCDStack.databasePathURLFromName(databaseName), icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path in String format and a flag indicating if the automigration has to be automatically executed :param: databasePath String with the database path :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databasePath: String, icloudData: iCloudData) { self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path URL and a flag indicating if the automigration has to be automatically executed :param: databaseURL NSURL with the database path :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseURL: NSURL, icloudData: iCloudData) { self.init(databaseURL: databaseURL, model: nil, automigrating: true,icloudData: icloudData) } /** Initialize the CoreData default stack passing the database name, the database model object and a flag indicating if the automigration has to be automatically executed :param: databaseName String with the database name :param: model NSManagedObjectModel with the database model :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseName: String, model: NSManagedObjectModel, icloudData: iCloudData) { self.init(databaseURL: DefaultCDStack.databasePathURLFromName(databaseName), model: model, automigrating: true, icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path in String format, the database model object and a flag indicating if the automigration has to be automatically executed :param: databasePath String with the database path :param: model NSManagedObjectModel with the database model :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databasePath: String, model: NSManagedObjectModel, icloudData: iCloudData) { self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, model: model, automigrating: true, icloudData: icloudData) } /** Initialize the stacks components and the connections between them */ public override func initialize() { SugarRecordLogger.logLevelInfo.log("Initializing the stack: \(self.stackDescription)") createManagedObjecModelIfNeeded() persistentStoreCoordinator = createPersistentStoreCoordinator() addDatabase(foriCloud: true, self.dataBaseAddedClosure()) } /** Returns the closure to be execute once the database has been created */ override public func dataBaseAddedClosure() -> CompletionClosure { return { [weak self] (error) -> () in if self == nil { SugarRecordLogger.logLevelFatal.log("The stack was released whil trying to initialize it") return } else if error != nil { SugarRecordLogger.logLevelFatal.log("Something went wrong adding the database") return } self!.rootSavingContext = self!.createRootSavingContext(self!.persistentStoreCoordinator) self!.mainContext = self!.createMainContext(self!.rootSavingContext) self!.addObservers() self!.stackInitialized = true } } //MARK: - Contexts /** Creates a temporary root saving context to be used in background operations Note: This overriding is due to the fact that in this case the merge policy is different :param: persistentStoreCoordinator NSPersistentStoreCoordinator to be set as the persistent store coordinator of the created context :returns: Private NSManageObjectContext */ override internal func createRootSavingContext(persistentStoreCoordinator: NSPersistentStoreCoordinator?) -> NSManagedObjectContext { SugarRecordLogger.logLevelVerbose.log("Creating Root Saving context") var context: NSManagedObjectContext? if persistentStoreCoordinator == nil { SugarRecord.handle(NSError(domain: "The persistent store coordinator is not initialized", code: SugarRecordErrorCodes.CoreDataError.rawValue, userInfo: nil)) } context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context!.persistentStoreCoordinator = persistentStoreCoordinator! context!.addObserverToGetPermanentIDsBeforeSaving() context!.name = "Root saving context" context!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy SugarRecordLogger.logLevelVerbose.log("Created MAIN context") return context! } //MARK: - Database /** Add iCloud Database */ internal func addDatabase(foriCloud icloud: Bool, completionClosure: CompletionClosure) { /** * In case of not for iCloud */ if !icloud { self.addDatabase(completionClosure) return } /** * Database creation is an asynchronous process */ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] () -> Void in // Ensuring that the stack hasn't been released if self == nil { SugarRecordLogger.logLevelFatal.log("The stack was initialized while trying to add the database") return } // Checking that the PSC exists before adding the store if self!.persistentStoreCoordinator == nil { SugarRecord.handle(NSError()) } // Logging some data let fileManager: NSFileManager = NSFileManager() SugarRecordLogger.logLevelVerbose.log("Initializing iCloud with:") SugarRecordLogger.logLevelVerbose.log("iCloud App ID: \(self!.icloudData?.iCloudAppID)") SugarRecordLogger.logLevelVerbose.log("iCloud Data Directory: \(self!.icloudData?.iCloudDataDirectoryName)") SugarRecordLogger.logLevelVerbose.log("iCloud Logs Directory: \(self!.icloudData?.iCloudLogsDirectory)") //Getting the root path for iCloud let iCloudRootPath: NSURL? = fileManager.URLForUbiquityContainerIdentifier(self!.icloudData?.iCloudAppID) /** * If iCloud if accesible keep creating the PSC */ if iCloudRootPath != nil { let iCloudLogsPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudLogsDirectory))! let iCloudDataPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudDataDirectoryName))! // Creating data path in case of doesn't existing var error: NSError? if !fileManager.fileExistsAtPath(iCloudDataPath.path!) { fileManager.createDirectoryAtPath(iCloudDataPath.path!, withIntermediateDirectories: true, attributes: nil, error: &error) } if error != nil { completionClosure(error: error!) return } /// Getting the database path /// iCloudPath + iCloudDataPath + DatabaseName let path: String? = iCloudRootPath?.path?.stringByAppendingPathComponent((self?.icloudData?.iCloudDataDirectoryName)!).stringByAppendingPathComponent((self?.databasePath?.lastPathComponent)!) self!.databasePath = NSURL(fileURLWithPath: path!) // Adding store self!.persistentStoreCoordinator!.lock() error = nil var store: NSPersistentStore? = self!.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self!.databasePath, options: iCloudCDStack.icloudStoreOptions(contentNameKey: self!.icloudData!.iCloudAppID, contentURLKey: iCloudLogsPath), error: &error) self!.persistentStoreCoordinator!.unlock() self!.persistentStore = store! // Calling completion closure dispatch_async(dispatch_get_main_queue(), { () -> Void in completionClosure(error: nil) }) } /** * Otherwise use the local store */ else { self!.addDatabase(foriCloud: false, completionClosure: completionClosure) } }) } //MARK: - Database Helpers /** Returns the iCloud options to be used when the NSPersistentStore is initialized :returns: [NSObject: AnyObject] with the options */ internal class func icloudStoreOptions(#contentNameKey: String, contentURLKey: NSURL) -> [NSObject: AnyObject] { var options: [NSObject: AnyObject] = [NSObject: AnyObject] () options[NSMigratePersistentStoresAutomaticallyOption] = NSNumber(bool: true) options[NSInferMappingModelAutomaticallyOption] = NSNumber(bool: true) options[NSPersistentStoreUbiquitousContentNameKey] = contentNameKey options[NSPersistentStoreUbiquitousContentURLKey] = contentURLKey return options } //MARK: - Observers /** Add required observers to detect changes in psc's or contexts */ internal override func addObservers() { super.addObservers() SugarRecordLogger.logLevelVerbose.log("Adding observers to detect changes on iCloud") // Store will change notificationCenter.addObserver(self, selector: Selector("storesWillChange:"), name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: nil) // Store did change notificationCenter.addObserver(self, selector: Selector("storeDidChange:"), name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil) // Did import Ubiquituous Content notificationCenter.addObserver(self, selector: Selector("persistentStoreDidImportUbiquitousContentChanges:"), name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: nil) } /** Detects changes in the Ubiquituous Container (iCloud) and bring them to the stack contexts :param: notification Notification with these changes */ internal func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("Changes detected from iCloud. Merging them into the current CoreData stack") self.rootSavingContext!.performBlock { [weak self] () -> Void in if self == nil { SugarRecordLogger.logLevelWarn.log("The stack was released while trying to bring changes from the iCloud Container") return } self!.rootSavingContext!.mergeChangesFromContextDidSaveNotification(notification) self!.mainContext!.performBlock({ () -> Void in self!.mainContext!.mergeChangesFromContextDidSaveNotification(notification) }) } } /** Posted before the list of open persistent stores changes. :param: notification Notification with these changes */ internal func storesWillChange(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("Stores will change, saving pending changes before changing store") self.saveChanges() } /** Called when the store did change from the persistent store coordinator :param: notification Notification with the information */ internal func storeDidChange(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("The persistent store of the psc did change") // Nothing to do here } }
mit
2ed4067608faf3074f95c3bd451c58d4
40.63807
308
0.67624
5.622737
false
false
false
false
OUCHUNYU/MockCoreMotion
MockCoreMotionTests/MockCMMotionActivityManagerTests.swift
1
4949
// // MockCMMotionActivityManagerTests.swift // MockCoreMotion // // Created by Chunyu Ou on 3/26/17. // Copyright © 2017 Chunyu Ou. All rights reserved. // import XCTest import CoreMotion @testable import MockCoreMotion // TODO: Add more failure test cases class MockCMMotionActivityManagerTests: XCTestCase { var testMockCMMotionActivityManager: MockCMMotionActivityManager? override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. testMockCMMotionActivityManager = MockCMMotionActivityManager() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. MockCMMotionActivityManager.flushState(selfObject: testMockCMMotionActivityManager) super.tearDown() } func testIsActivityAvailable() { XCTAssertFalse(MockCMMotionActivityManager.isActivityAvailableCalled) XCTAssertFalse(MockCMMotionActivityManager.isActivityAvailable()) MockCMMotionActivityManager._isActivityAvailable = true XCTAssertTrue(MockCMMotionActivityManager.isActivityAvailable()) XCTAssertTrue(MockCMMotionActivityManager.isActivityAvailableCalled) } // TODO: testing error case func testQueryActivityStarting() { XCTAssertFalse(testMockCMMotionActivityManager!.queryActivityStartingCalled) XCTAssertNil(testMockCMMotionActivityManager?.queryActivityStartDate) XCTAssertNil(testMockCMMotionActivityManager?.queryActivityEndDate) XCTAssertNil(testMockCMMotionActivityManager?.queryActivityStartingHandlerError) XCTAssertNil(testMockCMMotionActivityManager?.historicalActivityData) let queryActivityStartingExpectation = expectation(description: "queryActivityStarting should return data") let testStartDate = Date() + (Date().timeIntervalSinceNow - 10000) let testEndDate = Date() let testActivityOne = MockCMMotionActivity() testActivityOne.walking = true testActivityOne.startDate = testStartDate let testHistoricalActivityData = [testActivityOne] var queryActivityStartingReturnedData: [CMMotionActivity]? testMockCMMotionActivityManager?.historicalActivityData = testHistoricalActivityData testMockCMMotionActivityManager?.queryActivityStarting(from: testStartDate, to: testEndDate, to: OperationQueue.main) { (data, error) in XCTAssertNil(error) queryActivityStartingReturnedData = data queryActivityStartingExpectation.fulfill() } XCTAssertTrue(testMockCMMotionActivityManager!.queryActivityStartingCalled) waitForExpectations(timeout: 2) { (error) in guard error == nil else { XCTFail("Something went wrong with expectaion") print("#testStartActivityUpdates error: \(error)") return } XCTAssertEqual(queryActivityStartingReturnedData!, testHistoricalActivityData) } } func testStartActivityUpdates() { let startActivityUpdatesExpectation = expectation(description: "motionActivityCollector should have 5 items") var motionActivityCollector = [CMMotionActivity]() func testHandler(_ data: CMMotionActivity?) { if data != nil { motionActivityCollector.append(data!) } if motionActivityCollector.count == 5 { startActivityUpdatesExpectation.fulfill() } } var testMotionActivities = [CMMotionActivity]() for _ in 1...5 { testMotionActivities.append(MockCMMotionActivity()) } XCTAssertFalse(testMockCMMotionActivityManager!.startActivityUpdatesCalled) testMockCMMotionActivityManager?.startActivityUpdates(to: OperationQueue.main, withHandler: testHandler) XCTAssertTrue(testMockCMMotionActivityManager!.startActivityUpdatesCalled) testMockCMMotionActivityManager?.updateActivity(with: testMotionActivities) waitForExpectations(timeout: 2) { (error) in guard error == nil else { XCTFail("Something went wrong with expectaion") print("#testStartActivityUpdates error: \(error)") return } XCTAssertEqual(testMotionActivities.count, motionActivityCollector.count) } } func testStopActivityUpdates() { XCTAssertFalse(testMockCMMotionActivityManager!.stopActivityUpdatesCalled) testMockCMMotionActivityManager?.stopActivityUpdates() XCTAssertTrue(testMockCMMotionActivityManager!.stopActivityUpdatesCalled) } }
mit
e93d11a52611246488c8635988e913fe
40.233333
127
0.691795
5.395856
false
true
false
false
malaonline/iOS
mala-ios/Tool/OperatorOverload.swift
1
1558
// // OperatorOverload.swift // mala-ios // // Created by Elors on 12/23/15. // Copyright © 2015 Mala Online. All rights reserved. // import UIKit /// Compare Tuple With NSIndexPath /// /// - parameter FirIndexPath: NSIndexPath Object (like {section:0, row:0}) /// - parameter SecIndexPath: Tuple (like (0,0)) /// /// - returns: Bool func ==(firIndexPath: IndexPath, secIndexPath: (section: Int, row: Int)) -> Bool { return firIndexPath.section == secIndexPath.section && firIndexPath.row == secIndexPath.row } /// Compare Custom Array With Empty Array /// /// - parameter FirArray: Custom Model Array /// - parameter SecArray: Empty Array /// /// - returns: Bool func !=(firArray: [[ClassScheduleDayModel]], secArray: [Any]) -> Bool { if firArray.count == 0 { return false } return true } /// Random Number /// /// - parameter range: range /// /// - returns: Int func randomInRange(_ range: Range<Int>) -> Int { let count = UInt32(range.upperBound - range.lowerBound) return Int(arc4random_uniform(count)) + range.lowerBound } func ==<T>(lhs: Listener<T>, rhs: Listener<T>) -> Bool { return lhs.name == rhs.name } // MARK: - Auto 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 } } func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } }
mit
fc869a20707ee07815a56ddd71fec6a5
21.565217
95
0.600514
3.399563
false
false
false
false
miller-ms/ViewAnimator
ViewAnimator/RotateAffineCell.swift
1
3277
// // RotateAffineCell.swift // ViewAnimator // // Created by William Miller DBA Miller Mobilesoft on 5/29/17. // // This application is intended to be a developer tool for evaluating the // options for creating an animation or transition using the UIView static // methods UIView.animate and UIView.transition. // Copyright © 2017 William Miller DBA Miller Mobilesoft // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // If you would like to reach the developer you may email me at // [email protected] or visit my website at // http://millermobilesoft.com // import UIKit class RotateAffineCell: UITableViewCell { // MARK: - controlls @IBOutlet weak var slider: UISlider! @IBOutlet weak var degreesLbl: UILabel! @IBOutlet weak var imageObj: UIImageView! var maximumFractionDigits = 0 var minimumFractionDigits = 0 var maximumIntegerDigits = 3 var minimumIntegerDigits = 1 var degrees = Float(0.0) { didSet { guard (degreesLbl != nil) && (slider != nil) && (imageObj != nil) else { return } let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = maximumFractionDigits formatter.minimumFractionDigits = minimumFractionDigits formatter.maximumIntegerDigits = maximumIntegerDigits formatter.minimumIntegerDigits = minimumIntegerDigits degreesLbl.text = formatter.string(from: NSNumber(value: degrees))! slider.value = degrees imageObj.transform = CGAffineTransform(rotationAngle: CGFloat(slider.value * Float.pi / 180)) print("Didset degrees \(degrees)") } } var radians: Float { get { return degrees * Float.pi / 180 } set { degrees = newValue * 180 / Float.pi } } var affine: CGAffineTransform { return CGAffineTransform(rotationAngle: CGFloat(degrees * Float.pi / 180)) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - Action Methods @IBAction func degreesChanged(_ sender: UISlider) { degrees = sender.value } }
gpl-3.0
82f3a376d888bc8a2954b3e7d8f860c5
29.333333
105
0.624542
5.001527
false
false
false
false
vickenliu/caculator
3pages/3pages/listsViewController.swift
1
4830
// // listsViewController.swift // 3pages // // Created by Vicken on 19/08/17. // Copyright © 2017 Vicken. All rights reserved. // import UIKit class listsViewController: UITableViewController { var lists: [AnyObject]? { didSet { print("i have set done") tableView.reloadData() } } let url = URL(string: "https://api.themoviedb.org/3/discover/movie?api_key=a9cdd0e23d8a5391db7174cf0ad20f5e&language=en-US&sort_by=popularity.desc&include_adult=true&include_video=false&page=1") override func viewDidLoad() { super.viewDidLoad() URLSession.shared.dataTask(with: url!) { (data, response, err) in if err != nil { print("fetching data error") return } guard let data = data else { return } do { let response = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as AnyObject let results = response["results"] as! NSArray self.lists = results as [AnyObject] print(results) } catch let jsonErr { print ("sterilize json error", jsonErr) } }.resume() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if let lists = lists { return lists.count } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) // Configure the cell... cell.textLabel?.text = lists?[indexPath.row]["title"] as? String return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "showDetail" { let detailVC = segue.destination as? detailViewController // if let cell = sender as? UITableViewCell { // if indexPath = tableView.indexPath(for: cell) { // detailVC?.list = lists[indexPath.row] // } // } guard let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else { return } guard let selectedList = lists?[indexPath.row] else { return } let list = List() list.title = selectedList["title"] as? String list.overview = selectedList["overview"] as? String list.release_date = selectedList["release_date"] as? String list.vote_average = selectedList["vote_average,"] as? Double detailVC?.list = list } } }
mit
90dc1bdc9e8aaba4dcd1da14a4fba3a0
35.037313
198
0.609443
4.998965
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-422/SafeRide/SafeRide/AppDelegate.swift
1
3816
// // AppDelegate.swift // SafeRide // // Created by Caleb Friden on 3/30/16. // Copyright © 2016 University of Oregon. All rights reserved. // import UIKit import GoogleMaps import SwiftDDP @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Meteor Setup Meteor.client.allowSelfSignedSSL = false // Connect to a server that uses a self signed ssl certificate Meteor.client.logLevel = .None let websocketURL = "wss://saferide.meteorapp.com/websocket" Meteor.connect(websocketURL) { } // Override point for customization after application launch. if let userRole = NSUserDefaults.standardUserDefaults().objectForKey("userRole") { let role = userRole as! String if (role == "rider") { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) self.window?.rootViewController = storyboard.instantiateInitialViewController() } else if (role == "employee") { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewControllerWithIdentifier("employeeNavigationController") self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() } } else { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewControllerWithIdentifier("homeViewController") self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() } GMSServices.provideAPIKey("AIzaSyCPHhAPneKcheJLtYeyX6yn2U7KxuN9qz4") return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
1119ed04e2534729efe90d6b9a46e334
48.545455
285
0.703277
5.457797
false
false
false
false
danielsaidi/KeyboardKit
Sources/KeyboardKit/Input/KeyboardInputSet.swift
1
932
// // KeyboardInputSet.swift // KeyboardKit // // Created by Daniel Saidi on 2020-07-03. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Foundation /** A keyboard input set represents the input parts of a system keyboard, the center lighter input keys. */ public class KeyboardInputSet: Equatable { public init(rows: [KeyboardInputRow]) { self.rows = rows } public let rows: [KeyboardInputRow] public static func == (lhs: KeyboardInputSet, rhs: KeyboardInputSet) -> Bool { lhs.rows == rhs.rows } } /** This input set can be used in alphabetic keyboards. */ public class AlphabeticKeyboardInputSet: KeyboardInputSet {} /** This input set can used in numeric keyboards. */ public class NumericKeyboardInputSet: KeyboardInputSet {} /** This input set can be used in symbolic keyboards. */ public class SymbolicKeyboardInputSet: KeyboardInputSet {}
mit
42a2670f12b5b46c58225e8dd274fb66
21.707317
82
0.701396
4.231818
false
false
false
false
valentinbercot/VBPerfectArchitecture
Sources/VBPerfectRessourceRouter.swift
1
1831
// // VBPerfectRessourceRouter.swift // VBPerfectArchitecture // // Created by Valentin Bercot on 12/02/2017. // // import PerfectHTTP /** An implementation of `VBPerfectRouter`. This router should be use to manage ressource routes (not an action route). If you want to manage an executable route see `VBPerfectExecuteRouter`. - authors: Valentin Bercot */ public class VBPerfectRessourceRouter: VBPerfectRouter { /** The `routes` id. This id is used in some routes and also for children routers. */ internal let id: String public let endpoint: String public let routes: Routes /** - parameters: - endpoint: the generated routes endpoint. - id: the generated routes id. - controller: the controller which will handle http request to theses routes. - parent: the routes parent. */ public init(endpoint: String, id: String, controller: VBPerfectRessourceController, parent: VBPerfectRessourceRouter? = nil) { self.id = id if parent != nil { self.endpoint = "\(parent!.endpoint)/{\(parent!.id)}/\(endpoint)" } else { self.endpoint = endpoint } var routes = Routes() routes.add(method: .get, uri: "/\(self.endpoint)", handler: controller.handleList) routes.add(method: .get, uri: "/\(self.endpoint)/{\(self.id)}", handler: controller.handleRetrieve) routes.add(method: .post, uri: "/\(self.endpoint)", handler: controller.handleCreate) routes.add(method: .put, uri: "/\(self.endpoint)/{\(self.id)}", handler: controller.handleUpdate) routes.add(method: .delete, uri: "/\(self.endpoint)/{\(self.id)}", handler: controller.handleDelete) self.routes = routes } }
apache-2.0
a52b9af94bf001ccf039d016bf90fffb
30.568966
128
0.626434
4.170843
false
false
false
false
BlenderSleuth/Unlokit
Unlokit/Nodes/Tools/Nodes/BombToolNode.swift
1
3640
// // BombToolNode.swift // Unlokit // // Created by Ben Sutherland on 13/01/2017. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit class BombToolNode: ToolNode { // Particles var fuse: SKEmitterNode! var explode = SKEmitterNode(fileNamed: "BombExplode")! var exploded = false var radius: CGFloat = 200 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) type = .bomb } override func setupPhysics(shadowed isShadowed: Bool) { super.setupPhysics(shadowed: isShadowed) physicsBody?.categoryBitMask = Category.bombTool physicsBody?.contactTestBitMask = Category.bounds | Category.mtlBlock | Category.bncBlock | Category.gluBlock | Category.breakBlock | Category.tools } func setupFuse(scene: GameScene) { fuse = childNode(withName: "fuse")?.children.first as! SKEmitterNode fuse.targetNode = scene } override func smash(scene: GameScene) { explode(scene: scene, at: self.position) } override func remove() { // Hide fuse behind bomb while particles dissipate fuse.position = CGPoint.zero fuse.particleAlpha = 0 fuse.move(toParent: scene!) let action = SKAction.sequence([SKAction.wait(forDuration: 0.7), SKAction.removeFromParent()]) fuse.run(action) super.remove() } func explode(scene: GameScene, at point: CGPoint) { // Check if this is the first explosion if parent == nil || exploded { return } exploded = true let regionRect = CGRect(origin: CGPoint(x: -radius, y: -radius), size: CGSize(width: radius * 2, height: radius * 2)) let regionPath = CGPath(ellipseIn: regionRect, transform: nil) let region = SKRegion(path: regionPath) self.position = point var breakables = [Breakable]() // Shatter all breakables in radius scene.enumerateChildNodes(withName: "//breakable*") { node, _ in // Protect self guard node != self else { return } if let breakable = (node as? Breakable) { let position = self.convert(node.position, from: node.parent!) if region.contains(position) { breakables.append(breakable) } } } // Shatter objects outside of loop for breakable in breakables { breakable.shatter(scene: scene) } // Play sound scene.run(SoundFX.sharedInstance["explosion"]!) let explode = SKEmitterNode(fileNamed: "BombExplode")! explode.position = scene.convert(position, from: self.parent!) scene.addChild(explode) removeFromParent() } func explode(scene: GameScene) { guard let parent = parent else { return } position = scene.convert(self.position, from: parent) explode(scene: scene, at: position) } func countDown(scene: GameScene, at point: CGPoint, side: Side) { var countDown = 3 let label = SKLabelNode(text: "\(countDown)") label.fontName = neuropolFont label.fontSize = 64 label.verticalAlignmentMode = .center label.zPosition = 100 //label.position = position addChild(label) let wait = SKAction.wait(forDuration: 1) let block = SKAction.run { countDown -= 1 label.text = "\(countDown)" } let sequence = SKAction.sequence([wait, block]) let repeatAction = SKAction.repeat(sequence, count: countDown) run(repeatAction) { label.removeFromParent() if let glueBlock = self.parent as? GlueBlockNode { glueBlock.remove(for: side) } let position: CGPoint if let block = self.parent as? GlueBlockNode { position = scene.convert(side.position, from: block) } else { position = point } self.move(toParent: scene) self.explode(scene: scene, at: position) } } }
gpl-3.0
b15ed7034ba1d61988612ede41631cf9
25.179856
119
0.685903
3.465714
false
false
false
false
thombles/Flyweight
Flyweight/Managers/NoticeManager.swift
1
7034
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // 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 CoreData class NoticeManager { let session: Session init(session: Session) { self.session = session } func getNotice(id: Int64?, server: String? = nil) -> NoticeMO? { guard let id = id else { return nil } let server = server ?? session.account.server let query = NoticeMO.fetchRequest() as! NSFetchRequest<NoticeMO> query.predicate = NSPredicate(format: "server = %@ AND statusNetId = %ld", server, id) let results = session.fetch(request: query) return results.first } /// New way, using the parsed ActivityStreams XML objects func processNoticeEntries(sourceServer: String, entries: [ASEntry], idOverride: Int64? = nil) -> [NoticeMO] { var ret: [NoticeMO] = [] for entry in entries { guard let statusNetId = idOverride ?? entry.statusNetNoticeId else { continue } // If that notice is already in our DB skip creating a new one if let existing = getNotice(id: statusNetId, server: sourceServer) { // TODO possibly update things? Can they change? // To deal with repeated notices already having been processed in the same batch, // we need to include them inline again in the returned notices. // This will give screwy results if a server gives us more results than we asked for // Trust the server impl for the moment ret.append(existing) continue } // Make sure we have all the common data we care about first guard let tag = entry.id, let htmlContent = entry.htmlContent, let htmlLink = entry.htmlLink, let published = entry.published, let updated = entry.updated, let author = entry.author, let conversationUrl = entry.conversationUrl, let conversationNumber = entry.conversationNumber, let conversationThread = entry.conversationThread else // not actually a big deal but common { continue } // Process author (User object in core data) // Get either an existing or new user based on the DTO // If we can't parse the user then we can't use this notice guard let user = session.userManager.processFeedAuthor(sourceServer: sourceServer, author: author) else { continue } // Must be a better way to organise this but it'll do for now // Ensure we have all the data for the specific subtype _before_ we commit to making the new NoticeMO if entry.isReply { guard entry.inReplyToNoticeUrl != nil && entry.inReplyToNoticeRef != nil else { continue } } if entry.isFavourite { guard entry.object?.statusNetNoticeId != nil && entry.object?.htmlLink != nil else { continue } } var repeatedNotice: NoticeMO? = nil if entry.isRepeat { if let object = entry.object, let repeatedId = entry.repeatOfNoticeId { repeatedNotice = processNoticeEntries(sourceServer: sourceServer, entries: [object], idOverride: repeatedId).first } // It's okay if the repeated notice goes into the DB but we hit a parse error for the containing one below guard repeatedNotice != nil else { continue } } if entry.isDelete { // TODO either purge the old one from the DB or mark it hidden } let new = NSEntityDescription.insertNewObject(forEntityName: "Notice", into: session.moc) as! NoticeMO // As yet unused, sadly. Put in sentinel values so numbers will be hidden in UI. new.faveNum = -1 new.repeatNum = -1 // Fill in all the info we have new.server = sourceServer new.statusNetId = statusNetId new.tag = tag new.htmlContent = htmlContent new.htmlLink = htmlLink new.published = published as NSDate new.lastUpdated = updated as NSDate new.conversationUrl = conversationUrl new.conversationId = conversationNumber new.conversationThread = conversationThread new.client = entry.client ?? "" // kind of optional new.user = user new.isOwnPost = entry.isPost || entry.isComment new.isReply = entry.isReply new.isRepeat = entry.isRepeat new.isFavourite = entry.isFavourite new.isDelete = entry.isDelete // Store extra data depending on the type of notice it was // If anything is missing this is an inconsistent notice and we should just ignore the whole thing if entry.isReply { guard let repliedTag = entry.inReplyToNoticeRef, let repliedUrl = entry.inReplyToNoticeRef else { continue } new.inReplyToNoticeTag = repliedTag new.inReplyToNoticeUrl = repliedUrl } if entry.isFavourite { guard let favouritedId = entry.object?.statusNetNoticeId, let favouritedHtmlLink = entry.object?.htmlLink else { continue } new.favouritedStatusNetId = favouritedId new.favouritedHtmlLink = favouritedHtmlLink } // The feed recursively embeds the repeated entry so we can recursively parse it too if entry.isRepeat { // If it's a repeat this will definitely have been set above new.repeatedNotice = repeatedNotice } session.persist() NSLog("Created new object with server \(new.server) and id \(new.statusNetId)") ret.append(new) } return ret } }
apache-2.0
07b719ffd380304efc01d5886e5893b6
41.890244
134
0.574353
5.202663
false
false
false
false
sharkspeed/dororis
languages/swift/guide/18-error-handling.swift
1
5562
// 18. Error Handling // first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. // use the NSError class in Cocoa and Objective-C // 18.1 Representing and Throwing Errors // Swift 中的 errors 通过 确认 Error protocol 来表示. 这个 空 协议表明该类型可以用来处理错误 error handling. // 枚举类型很适合为一个组相关错误类型建模 enum VendingMachineError: Error { case invalidSelection case insufficienFunds(coinsNeeded: Int) case outOfStock } // 用 throw 抛出错误 // throw VendingMachineError.insufficienFunds(coinNeeded: 5) // 18.2 Handling Errors // 错误处理方法: 1. correcting the problem 2. trying an alternative approach 3. informing the user of the failure. // Swift 中有 4 种处理手段 // 1. 向上传递 error: 将错误传给调用这个方法的地方 // 2. do-catch 语句处理错误 // 3. 将错误作为 optional value 处理 // 4. assert 不会有错误出现 // 首先要确认错误发生的位置 使用 try 或者 try? try! before a piece of code that calls a function, method, or initializer that can throw an error // 18.2.1 Propagating Errors Using Throwing Functions // 给 function method initializer 参数 后边 加上 throw 来表示它们会有可能出错 A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow (->). // 只有 throwing function 可以抛出错误 struct Item { var price: Int var count: Int } class VendingMachine { var inventory = [ "Candy Bar": Item(price: 12, count: 7), "Chips": Item(price: 10, count: 4), "Pretzels": Item(price: 7, count: 11) ] var coinsDeposited = 0 func vend(itemNamed name: String) throws { guard let item = inventory[name] else { // uses guard statements to exit the method early and throw appropriate errors if any of the requirements for purchasing a snack aren’t met throw VendingMachineError.invalidSelection } guard item.count > 0 else { throw VendingMachineError.outOfStock } guard item.price <= coinsDeposited else { // 物品价格高出拥有资金 throw VendingMachineError.insufficienFunds(coinNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price var newItem = item newItem.count -= 1 inventory[name] = newItem print("Dispensing \(name)") } } // A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. // 调用这个 throwing function 的方法 要么 do-catch 处理 要么转化错误为 try try? try! 要么继续抛出错误 let favoriteSnacks = [ "Alice": "Chiips", "Bob": "Licorice", "Eve": "Pretzels", ] func buyFavoriteSnack(person: String, VendingMachine: VendingMachine) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try VendingMachine.vend(itemNamed: snackName) } // 初始化抛出错误和函数类似 struct PurchasedSnack { let name: String init(name: String, VendingMachine: VendingMachine) throws { try VendingMachine.vend(itemNamed: name) self.name = name } } // 18.2.2 Handling Errors Using Do-Catch // do { // try expression // statements // } catch pattern 1 { // statements // } catch pattern 2 where condition { // statements // } // https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html#//apple_ref/doc/uid/TP40014097-CH36-ID419 // 不需要处理所有的错误 不做处理的错误会传递到附近的作用域。 但必须在作用域里处理 用 do-catch 或 throwing function var vendingMachine = VendingMachine() vendingMachine.coinsDeposited = 8 do { try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine) } catch VendingMachineError.invalidSelection { print("Invalid Selection.") } catch VendingMachineError.outOfStock { print("Out of Stock.") } catch VendingMachineError.insufficienFunds(let coinsNeeded) { print("insufficienFunds. Please insert an additional \(coinsNeeded) coins.") } // 出错就跳到对应的 catch 语句中 // 18.2.3 Converting Errors to Optional Values // use try? to handle an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil // error => nil // func someThrowingFunction() throws -> Int { // // ... // } // let x = try? someThrowingFunction() // let y: Int? // do { // y = try someThrowingFunction() // } catch { // y = nil // } // Using try? lets you write concise error handling code when you want to handle all errors in the same way. // 用同样的方法处理错误 // 18.2.4 Disabling Error Propagation // 如果你知道一个 throwing function 不会抛出错误 你可以用 try! 阻止错误抛出。 一旦有错误,就造成 runtime error // 18.3 Specifying Cleanup Actions // defer 用来在代码执行退出前,执行一些操作 // the code in the first defer statement executes after code in the second, and so on. func processFile(filename: String) throws { if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { // ... } // close is called here. } }
bsd-2-clause
22b08acb31b814f12317f013673d51a2
27.153409
220
0.69237
3.79036
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch19/19.3.1NSArray类.playground/section-1.swift
1
889
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] import Foundation let weeksArray = ["星期一","星期二", "星期三", "星期四", "星期五", "星期六","星期日"] var weeksNames:NSArray = NSArray(array: weeksArray) NSLog("星期名字") NSLog("==== ====") for var i = 0; i < weeksNames.count; i++ { var obj : AnyObject = weeksNames.objectAtIndex(i) var day = obj as NSString NSLog("%i %@", i, day) } for item : AnyObject in weeksNames { var day = item as NSString NSLog("%@", day) }
gpl-2.0
f0c644f46e3b7e3add712af3c6268de0
25.62963
64
0.652295
2.672862
false
false
false
false
weijentu/ResearchKit
samples/ORKSample/ORKSample/ResearchContainerSegue.swift
9
2569
/* Copyright (c) 2015, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit class ResearchContainerSegue: UIStoryboardSegue { override func perform() { let controllerToReplace = sourceViewController.childViewControllers.first let destinationControllerView = destinationViewController.view destinationControllerView.translatesAutoresizingMaskIntoConstraints = true destinationControllerView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] destinationControllerView.frame = sourceViewController.view.bounds controllerToReplace?.willMoveToParentViewController(nil) sourceViewController.addChildViewController(destinationViewController) sourceViewController.view.addSubview(destinationControllerView) controllerToReplace?.view.removeFromSuperview() destinationViewController.didMoveToParentViewController(sourceViewController) controllerToReplace?.removeFromParentViewController() } }
bsd-3-clause
2fc23de8fc38c22bfd41f4d077b82054
48.403846
86
0.794862
5.799097
false
false
false
false
RemyDCF/tpg-offline
tpg offline Notification/NotificationViewController.swift
1
5467
// // NotificationViewController.swift // tpg offline Notification // // Created by Rémy Da Costa Faro on 14/07/2018. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit import UserNotifications import UserNotificationsUI import MapKit class NotificationViewController: UIViewController, UNNotificationContentExtension { @IBOutlet var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self } func didReceive(_ notification: UNNotification) { guard let mapView = self.mapView else { return } mapView.removeAnnotations(mapView.annotations) let regionRadius: CLLocationDistance = 2000 if notification.request.content.categoryIdentifier == "departureNotification", let x = notification.request.content.userInfo["x"] as? Double, let y = notification.request.content.userInfo["y"] as? Double, let stopName = notification.request.content.userInfo["stopName"] as? String { let coordinate = CLLocationCoordinate2D(latitude: x, longitude: y) let coordinateRegion = MKCoordinateRegion.init(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) mapView.setRegion(coordinateRegion, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = stopName mapView.addAnnotation(annotation) } else if notification.request.content.categoryIdentifier == "goNotification", let arrivalX = notification.request.content.userInfo["arrivalX"] as? Double, let arrivalY = notification.request.content.userInfo["arrivalY"] as? Double, let arrivalName = notification.request.content.userInfo["arrivalName"] as? String { if let departureX = notification.request.content.userInfo["departureX"] as? Double, let departureY = notification.request.content.userInfo["departureY"] as? Double, let departureName = notification.request.content.userInfo["departureName"] as? String { let arrivalCoordinates = CLLocationCoordinate2D(latitude: arrivalX, longitude: arrivalY) let departureCoordinates = CLLocationCoordinate2D(latitude: departureX, longitude: departureY) let arrivalPlacemark = MKPlacemark(coordinate: arrivalCoordinates, addressDictionary: nil) let departurePlacemark = MKPlacemark(coordinate: departureCoordinates, addressDictionary: nil) let arrivalMapItem = MKMapItem(placemark: arrivalPlacemark) let departureMapItem = MKMapItem(placemark: departurePlacemark) let arrivalAnnotation = MKPointAnnotation() arrivalAnnotation.coordinate = arrivalCoordinates arrivalAnnotation.title = arrivalName let departureAnnotation = MKPointAnnotation() departureAnnotation.coordinate = departureCoordinates departureAnnotation.title = departureName self.mapView.showAnnotations([arrivalAnnotation, departureAnnotation], animated: true ) let directionRequest = MKDirections.Request() directionRequest.source = arrivalMapItem directionRequest.destination = departureMapItem directionRequest.transportType = .walking let directions = MKDirections(request: directionRequest) directions.calculate { (response, _) -> Void in guard let response = response else { let coordinates = [arrivalCoordinates, departureCoordinates] let geodesic = MKPolyline(coordinates: coordinates, count: coordinates.count) mapView.addOverlay(geodesic) return } let route = response.routes[0] self.mapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads) let rect = route.polyline.boundingMapRect self.mapView.setRegion(MKCoordinateRegion.init(rect), animated: true) } } else { let coordinate = CLLocationCoordinate2D(latitude: arrivalX, longitude: arrivalY) let coordinateRegion = MKCoordinateRegion.init(center: coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) mapView.setRegion(coordinateRegion, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = arrivalName mapView.addAnnotation(annotation) } } } } extension NotificationViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { guard let polyline = overlay as? MKPolyline else { return MKOverlayRenderer() } let polylineRenderer = MKPolylineRenderer(overlay: polyline) polylineRenderer.strokeColor = .black polylineRenderer.lineWidth = 2 return polylineRenderer } }
mit
6aff8a1a161277e47062f66f327790e1
40.393939
84
0.644217
5.881593
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/BusDetails/BusDetailsViewController.swift
1
2870
import UIKit import ChameleonFramework class BusDetailsViewController: UIViewController { @IBOutlet weak var busImage: UIImageView! @IBOutlet weak var manufacturerImage: UIImageView! @IBOutlet weak var manufacturerText: UILabel! @IBOutlet weak var modelText: UILabel! @IBOutlet weak var licensePlateImage: UIImageView! @IBOutlet weak var licensePlateText: UILabel! @IBOutlet weak var fuelImage: UIImageView! @IBOutlet weak var fuelText: UILabel! @IBOutlet weak var colorImage: UIImageView! @IBOutlet weak var colorText: UILabel! @IBOutlet weak var specifications: UILabel! var vehicleId: Int init(vehicleId: Int) { self.vehicleId = vehicleId super.init(nibName: "BusDetailsViewController", bundle: nil) } public required init?(coder aDecoder: NSCoder) { vehicleId = 0 super.init(coder: aDecoder) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let navController = self.navigationController { navController.navigationBar.barTintColor = Theme.orange } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if vehicleId == 0 { fatalError("vehicleId == 0") } title = L10n.BusDetails.titleFormatted(vehicleId) parseData() } func parseData() { let tintColor: UIColor if let bus = Buses.getBus(id: vehicleId) { let vehicle = bus.vehicle tintColor = vehicle.color == 2 ? FlatOrange() : vehicle.getColor() busImage.image = UIImage(named: vehicle.code) manufacturerText.text = vehicle.manufacturer modelText.text = vehicle.model licensePlateText.text = "\(bus.licensePlate!) #\(vehicleId)" fuelText.text = vehicle.getFuelString() colorText.text = vehicle.getColorString() } else { Log.error("Vehicle \(vehicleId) does not exist") tintColor = FlatOrange() busImage.image = Asset.unknownBus.image manufacturerText.text = L10n.General.unknown modelText.text = L10n.General.unknown licensePlateText.text = L10n.General.unknown fuelText.text = L10n.General.unknown colorText.text = L10n.General.unknown } if let navController = self.navigationController { navController.navigationBar.barTintColor = tintColor } manufacturerImage.tint(with: tintColor) licensePlateImage.tint(with: tintColor) fuelImage.tint(with: tintColor) colorImage.tint(with: tintColor) specifications.textColor = tintColor } }
gpl-3.0
7f628c7f6e4b25831cfab03189d7b79d
27.7
79
0.626481
5.115865
false
false
false
false
markohlebar/Fontana
Spreadit/Controller/DonationStore.swift
1
4165
// // DonationStore.swift // Spreadit // // Created by Marko Hlebar on 06/02/2016. // Copyright © 2016 Marko Hlebar. All rights reserved. // import UIKit import StoreKit let DonationStoreDidUpdateProductsNotification = "DonationStoreDidUpdateProductsNotification" let DonationStoreDidStartPurchaseNotification = "DonationStoreDidStartPurchaseNotification" let DonationStoreDidFinishPurchaseNotification = "DonationStoreDidFinishPurchaseNotification" enum DonationError: ErrorType{ case NoProductsAvailable case NotAValidProduct } class DonationStore: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver { static let defaultStore = DonationStore() private var productsRequest: SKProductsRequest? private var products: [SKProduct]? private var buyCompletionHandler: (Donation -> Void)? override init() { super.init() SKPaymentQueue.defaultQueue().addTransactionObserver(self) } func loadProducts() { self.productsRequest = SKProductsRequest(productIdentifiers: Donation.allValues()) self.productsRequest?.delegate = self self.productsRequest?.start() } func formattedPrice(donation: Donation) throws -> String? { if products?.count == 0 { throw DonationError.NoProductsAvailable } if let aProduct = product(donation) { let numberFormatter = NSNumberFormatter() numberFormatter.formatterBehavior = .Behavior10_4 numberFormatter.numberStyle = .CurrencyStyle numberFormatter.locale = aProduct.priceLocale if let price = numberFormatter.stringFromNumber(aProduct.price) { return donation.description + "\n" + price } else { return nil } } else { throw DonationError.NotAValidProduct } } func buy(donation: Donation, completion:((donation: Donation) -> Void)?) throws { if let aProduct = product(donation) { let payment = SKPayment(product: aProduct) SKPaymentQueue.defaultQueue().addPayment(payment) self.buyCompletionHandler = completion NSNotificationCenter.defaultCenter().postNotificationName(DonationStoreDidStartPurchaseNotification, object: nil) } else { throw DonationError.NotAValidProduct } } internal func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { self.products = response.products NSNotificationCenter.defaultCenter().postNotificationName(DonationStoreDidUpdateProductsNotification, object: nil) } private func product(donation: Donation) -> SKProduct? { let productIdentifier = donation.rawValue return (self.products?.filter { product -> Bool in return product.productIdentifier == productIdentifier }.first) } private func handlePurchase(transaction: SKPaymentTransaction) { let productIdentifier = transaction.payment.productIdentifier if let completionHandler = self.buyCompletionHandler, let donation = Donation(rawValue: productIdentifier) { completionHandler(donation) } finishPurchase(transaction) } private func finishPurchase(transaction: SKPaymentTransaction) { SKPaymentQueue.defaultQueue().finishTransaction(transaction) NSNotificationCenter.defaultCenter().postNotificationName(DonationStoreDidFinishPurchaseNotification, object: nil) } internal func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .Purchased: handlePurchase(transaction) case .Failed: finishPurchase(transaction) case .Restored: finishPurchase(transaction) default: break } } } }
agpl-3.0
0511c2c3d89c8c02d282f3d48b812817
34.288136
125
0.668828
5.898017
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXInstallment.swift
1
2504
import Foundation /// :nodoc: open class PXInstallment: NSObject, Codable { open var issuer: PXIssuer? open var payerCosts: [PXPayerCost] = [] open var paymentMethodId: String? open var paymentTypeId: String? public init(issuer: PXIssuer?, payerCosts: [PXPayerCost], paymentMethodId: String?, paymentTypeId: String?) { self.issuer = issuer self.payerCosts = payerCosts self.paymentMethodId = paymentMethodId self.paymentTypeId = paymentTypeId } public enum PXInstallmentKeys: String, CodingKey { case issuer = "issuer" case payerCosts = "payer_costs" case paymentMethodId = "payment_method_id" case paymentTypeId = "payment_type_id" } public required convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PXInstallmentKeys.self) let issuer: PXIssuer? = try container.decodeIfPresent(PXIssuer.self, forKey: .issuer) let payerCosts: [PXPayerCost] = try container.decodeIfPresent([PXPayerCost].self, forKey: .payerCosts) ?? [] let paymentMethodId: String? = try container.decodeIfPresent(String.self, forKey: .paymentMethodId) let paymentTypeId: String? = try container.decodeIfPresent(String.self, forKey: .paymentTypeId) self.init(issuer: issuer, payerCosts: payerCosts, paymentMethodId: paymentMethodId, paymentTypeId: paymentTypeId) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PXInstallmentKeys.self) try container.encodeIfPresent(self.issuer, forKey: .issuer) try container.encodeIfPresent(self.payerCosts, forKey: .payerCosts) try container.encodeIfPresent(self.paymentMethodId, forKey: .paymentMethodId) try container.encodeIfPresent(self.paymentTypeId, forKey: .paymentTypeId) } open func toJSONString() throws -> String? { let encoder = JSONEncoder() let data = try encoder.encode(self) return String(data: data, encoding: .utf8) } open func toJSON() throws -> Data { let encoder = JSONEncoder() return try encoder.encode(self) } open class func fromJSONToPXInstallment(data: Data) throws -> PXInstallment { return try JSONDecoder().decode(PXInstallment.self, from: data) } open class func fromJSON(data: Data) throws -> [PXInstallment] { return try JSONDecoder().decode([PXInstallment].self, from: data) } }
mit
18b1f2169ab65e7b7a37a2421a6d8951
41.440678
121
0.694888
4.424028
false
false
false
false
TomBin647/swift-
DrawingBoard/ViewController.swift
1
7363
// // ViewController.swift // DrawingBoard // // Created by ZhangAo on 15-2-15. // Copyright (c) 2015年 zhangao. All rights reserved. // import UIKit class ViewController: UIViewController { var brushes = [PencilBrush(), LineBrush(), DashLineBrush(), RectangleBrush(), EllipseBrush(), EraserBrush()] @IBOutlet var board: Board! @IBOutlet var topView: UIView! @IBOutlet var toolbar: UIToolbar! @IBOutlet var undoButton: UIButton! @IBOutlet var redoButton: UIButton! var toolbarEditingItems: [UIBarButtonItem]? var currentSettingsView: UIView? @IBOutlet var topViewConstraintY: NSLayoutConstraint! @IBOutlet var toolbarConstraintBottom: NSLayoutConstraint! @IBOutlet var toolbarConstraintHeight: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.board.brush = brushes[0] self.toolbarEditingItems = [ UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "完成", style:.Plain, target: self, action: "endSetting") ] self.toolbarItems = self.toolbar.items self.setupBrushSettingsView() self.setupBackgroundSettingsView() self.board.drawingStateChangedBlock = {(state: DrawingState) -> () in if state != .Moved { UIView.beginAnimations(nil, context: nil) if state == .Began { self.topViewConstraintY.constant = -self.topView.frame.size.height self.toolbarConstraintBottom.constant = -self.toolbar.frame.size.height self.topView.layoutIfNeeded() self.toolbar.layoutIfNeeded() self.undoButton.alpha = 0 self.redoButton.alpha = 0 } else if state == .Ended { UIView.setAnimationDelay(1.0) self.topViewConstraintY.constant = 0 self.toolbarConstraintBottom.constant = 0 self.topView.layoutIfNeeded() self.toolbar.layoutIfNeeded() self.undoButton.alpha = 1 self.redoButton.alpha = 1 } UIView.commitAnimations() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupBrushSettingsView() { let brushSettingsView = UINib(nibName: "PaintingBrushSettingsView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! PaintingBrushSettingsView self.addConstraintsToToolbarForSettingsView(brushSettingsView) brushSettingsView.hidden = true brushSettingsView.tag = 1 brushSettingsView.backgroundColor = self.board.strokeColor brushSettingsView.strokeWidthChangedBlock = { [unowned self] (strokeWidth: CGFloat) -> Void in self.board.strokeWidth = strokeWidth } brushSettingsView.strokeColorChangedBlock = { [unowned self] (strokeColor: UIColor) -> Void in self.board.strokeColor = strokeColor } } func setupBackgroundSettingsView() { let backgroundSettingsVC = UINib(nibName: "BackgroundSettingsVC", bundle: nil).instantiateWithOwner(nil, options: nil).first as! BackgroundSettingsVC self.addConstraintsToToolbarForSettingsView(backgroundSettingsVC.view) backgroundSettingsVC.view.hidden = true backgroundSettingsVC.view.tag = 2 backgroundSettingsVC.setBackgroundColor(self.board.backgroundColor!) self.addChildViewController(backgroundSettingsVC) backgroundSettingsVC.backgroundImageChangedBlock = { [unowned self] (backgroundImage: UIImage) in self.board.backgroundColor = UIColor(patternImage: backgroundImage) } backgroundSettingsVC.backgroundColorChangedBlock = { [unowned self] (backgroundColor: UIColor) in self.board.backgroundColor = backgroundColor } } func addConstraintsToToolbarForSettingsView(view: UIView) { view.setTranslatesAutoresizingMaskIntoConstraints(false) self.toolbar.addSubview(view) self.toolbar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[settingsView]-0-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["settingsView" : view])) self.toolbar.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[settingsView(==height)]", options: .DirectionLeadingToTrailing, metrics: ["height" : view.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height], views: ["settingsView" : view])) } func updateToolbarForSettingsView() { self.toolbarConstraintHeight.constant = self.currentSettingsView!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 44 self.toolbar.setItems(self.toolbarEditingItems, animated: true) UIView.beginAnimations(nil, context: nil) self.toolbar.layoutIfNeeded() UIView.commitAnimations() self.toolbar.bringSubviewToFront(self.currentSettingsView!) } func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) { if let err = error { UIAlertView(title: "错误", message: err.localizedDescription, delegate: nil, cancelButtonTitle: "确定").show() } else { UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "确定").show() } } @IBAction func switchBrush(sender: UISegmentedControl) { assert(sender.tag < self.brushes.count, "!!!") self.board.brush = self.brushes[sender.selectedSegmentIndex] } @IBAction func undo(sender: UIButton) { self.board.undo() } @IBAction func redo(sneder: UIButton) { self.board.redo() } @IBAction func paintingBrushSettings() { self.currentSettingsView = self.toolbar.viewWithTag(1) self.currentSettingsView?.hidden = false self.updateToolbarForSettingsView() } @IBAction func backgroundSettings() { self.currentSettingsView = self.toolbar.viewWithTag(2) self.currentSettingsView?.hidden = false self.updateToolbarForSettingsView() } @IBAction func saveToAlbum() { UIImageWriteToSavedPhotosAlbum(self.board.takeImage(), self, "image:didFinishSavingWithError:contextInfo:", nil) } @IBAction func endSetting() { self.toolbarConstraintHeight.constant = 44 self.toolbar.setItems(self.toolbarItems, animated: true) UIView.beginAnimations(nil, context: nil) self.toolbar.layoutIfNeeded() UIView.commitAnimations() self.currentSettingsView?.hidden = true } }
mit
12911732d5b8b209f81856ef6d8b8831
36.22335
164
0.636438
5.306078
false
false
false
false
onevcat/APNGKit
Source/APNGKit/APNGKitError.swift
1
3554
// // APNGKitError.swift // // // Created by Wang Wei on 2021/10/05. // import Foundation import ImageIO /// The errors can be thrown or returned by APIs in APNGKit. /// /// Each member in this type represents a type of reason for error during different image decoding or displaying phase. /// Check the detail reason to know the details. In most cases, you are only care about one or two types of error, and /// leave others falling to a default handling. public enum APNGKitError: Error { /// Errors happening during decoding the image data. case decoderError(DecoderError) /// Errors happening during creating the image. case imageError(ImageError) /// Other errors happening inside system and not directly related to APNGKit. case internalError(Error) } extension APNGKitError { /// Errors happening during decoding the image data. public enum DecoderError { case fileHandleCreatingFailed(URL, Error) case fileHandleOperationFailed(FileHandle, Error) case wrongChunkData(name: String, data: Data) case fileFormatError case corruptedData(atOffset: UInt64?) case chunkNameNotMatched(expected: [Character], actual: [Character]) case invalidNumberOfFrames(value: Int) case invalidChecksum case lackOfChunk([Character]) case wrongSequenceNumber(expected: Int, got: Int) case imageDataNotFound case frameDataNotFound(expectedSequence: Int) case invalidFrameImageData(data: Data, frameIndex: Int) case frameImageCreatingFailed(source: CGImageSource, frameIndex: Int) case outputImageCreatingFailed(frameIndex: Int) case canvasCreatingFailed case multipleAnimationControlChunk case invalidRenderer } /// Errors happening during creating the image. public enum ImageError { case resourceNotFound(name: String, bundle: Bundle) case normalImageDataLoaded(data: Data, scale: CGFloat) } } extension APNGKitError { /// Returns the image data as a normal image if the error happens during creating image object. /// /// When the image cannot be loaded as an APNG, but can be represented as a normal image, this returns its data and /// a scale for the image. public var normalImageData: (Data, CGFloat)? { guard case .imageError(.normalImageDataLoaded(let data, let scale)) = self else { return nil } return (data, scale) } } extension Error { /// Converts `self` to an `APNGKitError` if it is. /// /// This is identical as `self as? APNGKitError`. public var apngError: APNGKitError? { self as? APNGKitError } } extension APNGKitError { var shouldRevertToNormalImage: Bool { switch self { case .decoderError(let reason): switch reason { case .chunkNameNotMatched(let expected, let actual): let isCgBI = expected == IHDR.name && actual == ["C", "g", "B", "I"] if isCgBI { printLog("`CgBI` chunk found. It seems that the input image is compressed by Xcode and not supported by APNGKit. Consider to rename it to `apng` to prevent compressing.") } return isCgBI case .lackOfChunk(let name): return name == acTL.name default: return false } case .imageError: return false case .internalError: return false } } }
mit
94e056c0fc6c617117ca339391b5caa0
34.89899
190
0.654192
4.694848
false
false
false
false
johnlui/Swift-MMP
Frameworks/Pitaya/Source/JSONNeverDie/JSONND.swift
1
5203
// The MIT License (MIT) // Copyright (c) 2015 JohnLui <[email protected]> https://github.com/johnlui // 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. // // JSONND.swift // JSONNeverDie // // Created by 吕文翰 on 15/10/7. // import Foundation public struct JSONND { public static var debug = false public var data: Any! public init(string: String, encoding: String.Encoding = String.Encoding.utf8) { do { if let data = string.data(using: encoding) { let d = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) self.data = d as AnyObject! } } catch let error as NSError { let e = NSError(domain: "JSONNeverDie.JSONParseError", code: error.code, userInfo: error.userInfo) if JSONND.debug { NSLog(e.localizedDescription) } } } fileprivate init(any: AnyObject) { let j: JSONND = [any] self.data = j.arrayValue.first?.data } internal init(JSONdata: AnyObject!) { self.data = JSONdata } public init() { self.init(JSONdata: nil) } public init(dictionary: [String: Any]) { self.init(any: dictionary as AnyObject) } public init(array: [Any]) { self.init(any: array as AnyObject) } public subscript (index: String) -> JSONND { if let jsonDictionary = self.data as? Dictionary<String, AnyObject> { if let value = jsonDictionary[index] { return JSONND(JSONdata: value) } else { if JSONND.debug { NSLog("JSONNeverDie: No such key '\(index)'") } } } return JSONND(JSONdata: nil) } public var RAW: String? { get { if let _ = self.data { do { let d = try JSONSerialization.data(withJSONObject: self.data, options: .prettyPrinted) return NSString(data: d, encoding: String.Encoding.utf8.rawValue) as String? } catch { return nil } // can not test Errors here. // It seems that NSJSONSerialization.dataWithJSONObject() method dose not support do-try-catch in Swift 2 now. } return nil } } public var RAWValue: String { get { return self.RAW ?? "" } } public var int: Int? { get { if let number = self.data as? NSNumber { return number.intValue } if let number = self.data as? NSString { return number.integerValue } return nil } } public var intValue: Int { get { return self.int ?? 0 } } public var double: Double? { get { if let number = self.data as? NSNumber { return number.doubleValue } if let number = self.data as? NSString { return number.doubleValue } return nil } } public var doubleValue: Double { get { return self.double ?? 0.0 } } public var string: String? { get { return self.data as? String } } public var stringValue: String { get { return self.string ?? "" } } public var bool: Bool? { get { return self.data as? Bool } } public var boolValue: Bool { get { return self.bool ?? false } } public var array: [JSONND]? { get { if let _ = self.data { if let arr = self.data as? Array<AnyObject> { var result = Array<JSONND>() for i in arr { result.append(JSONND(JSONdata: i)) } return result } return nil } return nil } } public var arrayValue: [JSONND] { get { return self.array ?? [] } } }
mit
227ebb6baeaec9e01fb89e112583a087
29.751479
126
0.554936
4.631907
false
false
false
false
lmboricua/treehouse
VendingMachineStarter/Pods/Hue/Source/iOS/UIImage+Hue.swift
2
5596
import UIKit class CountedColor { let color: UIColor let count: Int init(color: UIColor, count: Int) { self.color = color self.count = count } } extension UIImage { fileprivate func resize(_ newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 2) draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } public func colors(_ scaleDownSize: CGSize? = nil) -> (background: UIColor, primary: UIColor, secondary: UIColor, detail: UIColor) { let cgImage: CGImage if let scaleDownSize = scaleDownSize { cgImage = resize(scaleDownSize).cgImage! } else { let ratio = size.width / size.height let r_width: CGFloat = 250 cgImage = resize(CGSize(width: r_width, height: r_width / ratio)).cgImage! } let width = cgImage.width let height = cgImage.height let bytesPerPixel = 4 let bytesPerRow = width * bytesPerPixel let bitsPerComponent = 8 let randomColorsThreshold = Int(CGFloat(height) * 0.01) let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let colorSpace = CGColorSpaceCreateDeviceRGB() let raw = malloc(bytesPerRow * height) let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue let context = CGContext(data: raw, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let data = UnsafePointer<UInt8>(context?.data?.assumingMemoryBound(to: UInt8.self)) let imageBackgroundColors = NSCountedSet(capacity: height) let imageColors = NSCountedSet(capacity: width * height) let sortComparator: (CountedColor, CountedColor) -> Bool = { (a, b) -> Bool in return a.count <= b.count } for x in 0..<width { for y in 0..<height { let pixel = ((width * y) + x) * bytesPerPixel let color = UIColor( red: CGFloat((data?[pixel+1])!) / 255, green: CGFloat((data?[pixel+2])!) / 255, blue: CGFloat((data?[pixel+3])!) / 255, alpha: 1 ) if x >= 5 && x <= 10 { imageBackgroundColors.add(color) } imageColors.add(color) } } var sortedColors = [CountedColor]() for color in imageBackgroundColors { guard let color = color as? UIColor else { continue } let colorCount = imageBackgroundColors.count(for: color) if randomColorsThreshold <= colorCount { sortedColors.append(CountedColor(color: color, count: colorCount)) } } sortedColors.sort(by: sortComparator) var proposedEdgeColor = CountedColor(color: blackColor, count: 1) if let first = sortedColors.first { proposedEdgeColor = first } if proposedEdgeColor.color.isBlackOrWhite && !sortedColors.isEmpty { for countedColor in sortedColors where CGFloat(countedColor.count / proposedEdgeColor.count) > 0.3 { if !countedColor.color.isBlackOrWhite { proposedEdgeColor = countedColor break } } } let imageBackgroundColor = proposedEdgeColor.color let isDarkBackgound = imageBackgroundColor.isDark sortedColors.removeAll() for imageColor in imageColors { guard let imageColor = imageColor as? UIColor else { continue } let color = imageColor.colorWithMinimumSaturation(minSaturation: 0.15) if color.isDark == !isDarkBackgound { let colorCount = imageColors.count(for: color) sortedColors.append(CountedColor(color: color, count: colorCount)) } } sortedColors.sort(by: sortComparator) var primaryColor, secondaryColor, detailColor: UIColor? for countedColor in sortedColors { let color = countedColor.color if primaryColor == nil && color.isContrastingWith(imageBackgroundColor) { primaryColor = color } else if secondaryColor == nil && primaryColor != nil && primaryColor!.isDistinctFrom(color) && color.isContrastingWith(imageBackgroundColor) { secondaryColor = color } else if secondaryColor != nil && (secondaryColor!.isDistinctFrom(color) && primaryColor!.isDistinctFrom(color) && color.isContrastingWith(imageBackgroundColor)) { detailColor = color break } } free(raw) return ( imageBackgroundColor, primaryColor ?? (isDarkBackgound ? whiteColor : blackColor), secondaryColor ?? (isDarkBackgound ? whiteColor : blackColor), detailColor ?? (isDarkBackgound ? whiteColor : blackColor)) } public func color(at point: CGPoint) -> UIColor? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) guard let imgRef = cgImage, let dataProvider = imgRef.dataProvider, let dataCopy = dataProvider.data, let data = CFDataGetBytePtr(dataCopy), rect.contains(point) else { return nil } let pixelInfo = (Int(size.width) * Int(point.y) + Int(point.x)) * 4 let red = CGFloat(data[pixelInfo]) / 255.0 let green = CGFloat(data[pixelInfo + 1]) / 255.0 let blue = CGFloat(data[pixelInfo + 2]) / 255.0 let alpha = CGFloat(data[pixelInfo + 3]) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
apache-2.0
a03e3e39337821f86f552deff9b53448
32.309524
173
0.656898
4.44127
false
false
false
false
anas10/AASquaresLoading
AASquaresLoadingDemo/AASquaresLoadingDemo/ViewController.swift
1
2090
// // ViewController.swift // AASquaresLoadingDemo // // Created by Anas Ait Ali on 27/02/15. // Copyright (c) 2015 Anas AIT ALI. All rights reserved. // import UIKit import AASquaresLoading class ViewController: UIViewController { @IBOutlet weak var topLeft: AASquaresLoading! @IBOutlet weak var topRight: UIView! @IBOutlet weak var bottomRight: UIView! @IBOutlet weak var bottomCenter: UIView! @IBOutlet weak var bottomLeft: UIView! var topRightSquare : AASquaresLoading! var bottomRightSquare : AASquaresLoading! var bottomCenterSquare : AASquaresLoading! var bottomLeftSquare : AASquaresLoading! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. topRightSquare = AASquaresLoading(target: self.topRight, size: 40) topRightSquare.backgroundColor = UIColor.black.withAlphaComponent(0.4) topRightSquare.color = UIColor.white topRightSquare.start() bottomRightSquare = AASquaresLoading(target: self.bottomRight) bottomRightSquare.backgroundColor = nil bottomRightSquare.color = UIColor.yellow bottomRightSquare.start(4.0) self.bottomCenter.squareLoading.start(0.0) self.bottomCenter.squareLoading.backgroundColor = UIColor.red self.bottomCenter.squareLoading.color = UIColor.white self.bottomCenter.squareLoading.setSquareSize(120) self.bottomCenter.squareLoading.stop(8.0) bottomLeftSquare = AASquaresLoading(target: self.bottomLeft) bottomLeftSquare.color = UIColor.black bottomLeftSquare.backgroundColor = UIColor.clear bottomLeftSquare.start() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.topRightSquare.setNeedsLayout() self.bottomRightSquare.setNeedsLayout() self.bottomLeftSquare.setNeedsLayout() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var prefersStatusBarHidden : Bool { return true } }
mit
dc7809e0476bc4bd076643306aea2bc2
28.857143
76
0.74689
4.623894
false
false
false
false
Stamates/30-Days-of-Swift
src/Day 14 - UI Table View/Day14/TableViewController.swift
2
4853
// // TableViewController.swift // Day14 // // Created by Justin Mitchel on 11/18/14. // Copyright (c) 2014 Coding For Entrepreneurs. All rights reserved. // import UIKit class TableViewController: UITableViewController, UIAlertViewDelegate { let items = ["Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna","Justin", "Carli", "Tim", "John", "Jenna", "Scott"] override func viewDidLoad() { super.viewDidLoad() let headerView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 200)) headerView.backgroundColor = UIColor.redColor() // headerView.addSubview(<#view: UIView#>) self.tableView.tableHeaderView = headerView // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellID", forIndexPath: indexPath) as UITableViewCell // arrayName[indexNumber] == result // Configure the cell... cell.textLabel!.text = "\(indexPath.row + 1) - \(items[indexPath.row])" return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println(indexPath.row) let message = "Hello \(items[indexPath.row])!" let alertView = UIAlertView(title: "Hello there!", message: message, delegate: self, cancelButtonTitle: "Thanks!") alertView.show() } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
apache-2.0
b5b7cf95b145bf46f56c8c09c07e743a
43.522936
782
0.659798
4.539757
false
false
false
false
Marquis103/VirtualTourist
CoreDataStack.swift
1
2275
// // CoreDataStack.swift // MemeMe // // Created by Marquis Dennis on 2/2/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import Foundation import CoreData class CoreDataStack : NSObject { static let sharedInstance = CoreDataStack() static let moduleName = "pinPhotos" struct Constants { struct EntityNames { static let PhotoEntityName = "Photo" static let PinEntityName = "Pin" } } //save managed context if changes exist func saveMainContext() { handleManagedObjectContextOperations { () -> Void in if self.managedObjectContext.hasChanges { do { try self.managedObjectContext.save() } catch { let saveError = error as NSError print("There was an error saving main managed object context! \(saveError)") } } } } lazy var persistentStoreCoordinator:NSPersistentStoreCoordinator = { //location of the managed object model persisted on disk let modelURL = NSBundle.mainBundle().URLForResource(moduleName, withExtension: "momd")! //instantiate the persistent store coordinator let coordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel(contentsOfURL: modelURL)!) //application documents directory where user files are stored let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last! //location on disk of the actual persistent store let persistentStoreURL = applicationDocumentsDirectory.URLByAppendingPathComponent("\(moduleName).sqlite") //add the persistent store to the persistent store coordinator do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: persistentStoreURL, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption : true]) } catch { fatalError("Persistent store error! \(error)") } return coordinator }() //create managed object context lazy var managedObjectContext:NSManagedObjectContext = { let managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator return managedObjectContext }() }
mit
1a0000529adc26dc004d42c3da016d08
31.042254
139
0.764292
5.121622
false
false
false
false
nodes-vapor/sugar
Sources/Sugar/Helpers/Future.swift
1
1899
import Vapor public extension Future { func `try`(_ callback: @escaping (Expectation) throws -> Void) -> Future<T> { return map { try callback($0) return $0 } } func flatTry(_ callback: @escaping (Expectation) throws -> Future<Void>) -> Future<T> { return flatMap { expectation in try callback(expectation).map { _ in expectation } } } } public extension Future where Expectation: OptionalType { func `nil`(or error: @autoclosure @escaping () -> Error) -> Future<Void> { return map(to: Void.self) { optional in guard optional.wrapped == nil else { throw error() } } } } public extension Future where Expectation: Equatable { func equal( _ expected: Expectation, or error: @autoclosure @escaping () -> Error ) -> Future<Void> { return map(to: Void.self) { value in guard value == expected else { throw error() } } } } public func syncFlatten<T>(futures: [LazyFuture<T>], on worker: Worker) -> Future<[T]> { let promise = worker.eventLoop.newPromise([T].self) var results: [T] = [] var iterator = futures.makeIterator() func handle(_ future: LazyFuture<T>) { do { try future().do { res in results.append(res) if let next = iterator.next() { handle(next) } else { promise.succeed(result: results) } }.catch { error in promise.fail(error: error) } } catch { promise.fail(error: error) } } if let first = iterator.next() { handle(first) } else { promise.succeed(result: results) } return promise.futureResult }
mit
cd91d092c4ecf35833e3a43262be3211
25.746479
91
0.518694
4.468235
false
false
false
false
JamieScanlon/AugmentKit
AugmentKit/Renderer/Render Modules/ComputeModule.swift
1
9386
// // ComputeModule.swift // AugmentKit // // MIT License // // Copyright (c) 2019 JamieScanlon // // 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 simd import AugmentKitShader // MARK: - ComputeModule /// A module to perform a compute function protocol ComputeModule: ShaderModule { associatedtype Out // // Bootstrap // /// After this function is called, The Compute Pass Desciptors, Textures, Buffers, Compute Pipeline State Descriptors should all be set up. func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<Out>?) -> ThreadGroup? // // Per Frame Updates // /// Update and dispatch the command encoder. At the end of this method it is expected that `dispatchThreads` or dispatchThreadgroups` is called. func dispatch(withComputePass computePass: ComputePass<Out>?, sharedModules: [SharedRenderModule]?) } /// A `ComputePass` that is part of a render pipeline and used to prepare data for subsequent draw calls protocol PreRenderComputeModule: ComputeModule where Self.Out == PrecalculatedParameters { // // Per Frame Updates // /// Update the buffer(s) data from information about the render func prepareToDraw(withAllEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, computePass: ComputePass<Out>, renderPass: RenderPass?) } extension PreRenderComputeModule { // MARK: Util func getRGB(from colorTemperature: CGFloat) -> SIMD3<Float> { let temp = Float(colorTemperature) / 100 var red: Float = 127 var green: Float = 127 var blue: Float = 127 if temp <= 66 { red = 255 green = temp green = 99.4708025861 * log(green) - 161.1195681661 if temp <= 19 { blue = 0 } else { blue = temp - 10 blue = 138.5177312231 * log(blue) - 305.0447927307 } } else { red = temp - 60 red = 329.698727446 * pow(red, -0.1332047592) green = temp - 60 green = 288.1221695283 * pow(green, -0.0755148492 ) blue = 255 } let clamped = clamp(SIMD3<Float>(red, green, blue), min: 0, max: 255) / 255 return SIMD3<Float>(clamped.x, clamped.y, clamped.z) } } // // Type Erasure // private class _AnyComputeModuleBase<Out>: ComputeModule { init() { guard type(of: self) != _AnyComputeModuleBase.self else { fatalError("_AnyComputeModuleBase<Out> instances can not be created; create a subclass instance instead") } } var moduleIdentifier: String { fatalError("Must override") } var state: ShaderModuleState { fatalError("Must override") } var renderLayer: Int { fatalError("Must override") } var errors: [AKError] { get { fatalError("Must override") } set { fatalError("Must override") } } var sharedModuleIdentifiers: [String]? { fatalError("Must override") } func initializeBuffers(withDevice: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) { fatalError("Must override") } func updateBufferState(withBufferIndex: Int) { fatalError("Must override") } func frameEncodingComplete(renderPasses: [RenderPass]) { fatalError("Must override") } func recordNewError(_ akError: AKError) { fatalError("Must override") } func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<Out>?) -> ThreadGroup? { fatalError("Must override") } func dispatch(withComputePass computePass: ComputePass<Out>?, sharedModules: [SharedRenderModule]?) { fatalError("Must override") } } private final class _AnyComputeModuleBox<Concrete: ComputeModule>: _AnyComputeModuleBase<Concrete.Out> { // variable used since we're calling mutating functions var concrete: Concrete init(_ concrete: Concrete) { self.concrete = concrete } // MARK: Trampoline variables and functions forward along to base override var moduleIdentifier: String { return concrete.moduleIdentifier } override var state: ShaderModuleState { return concrete.state } override var renderLayer: Int { return concrete.renderLayer } override var errors: [AKError] { get { return concrete.errors } set { concrete.errors = newValue } } override var sharedModuleIdentifiers: [String]? { return concrete.sharedModuleIdentifiers } override func initializeBuffers(withDevice device: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) { concrete.initializeBuffers(withDevice: device, maxInFlightFrames: maxInFlightFrames, maxInstances: maxInstances) } override func updateBufferState(withBufferIndex bufferIndex: Int) { concrete.updateBufferState(withBufferIndex: bufferIndex) } override func frameEncodingComplete(renderPasses: [RenderPass]) { concrete.frameEncodingComplete(renderPasses: renderPasses) } override func recordNewError(_ akError: AKError) { concrete.recordNewError(akError) } override func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<Out>?) -> ThreadGroup? { concrete.loadPipeline(withMetalLibrary: metalLibrary, renderDestination: renderDestination, textureBundle: textureBundle, forComputePass: computePass) } override func dispatch(withComputePass computePass: ComputePass<Out>?, sharedModules: [SharedRenderModule]?) { concrete.dispatch(withComputePass: computePass, sharedModules: sharedModules) } } /** A type erased `ComputeModule` */ final class AnyComputeModule<Out>: ComputeModule { private let box: _AnyComputeModuleBase<Out> /** Initializer takes a concrete implementation */ init<Concrete: ComputeModule>(_ concrete: Concrete) where Concrete.Out == Out { box = _AnyComputeModuleBox(concrete) } var moduleIdentifier: String { return box.moduleIdentifier } var state: ShaderModuleState { return box.state } var renderLayer: Int { return box.renderLayer } var errors: [AKError] { get { return box.errors } set { box.errors = newValue } } var sharedModuleIdentifiers: [String]? { return box.sharedModuleIdentifiers } func initializeBuffers(withDevice device: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) { box.initializeBuffers(withDevice: device, maxInFlightFrames: maxInFlightFrames, maxInstances: maxInstances) } func updateBufferState(withBufferIndex bufferIndex: Int) { box.updateBufferState(withBufferIndex: bufferIndex) } func frameEncodingComplete(renderPasses: [RenderPass]) { box.frameEncodingComplete(renderPasses: renderPasses) } func recordNewError(_ akError: AKError) { box.recordNewError(akError) } func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<Out>?) -> ThreadGroup? { return box.loadPipeline(withMetalLibrary: metalLibrary, renderDestination: renderDestination, textureBundle: textureBundle, forComputePass: computePass) } func dispatch(withComputePass computePass: ComputePass<Out>?, sharedModules: [SharedRenderModule]?) { box.dispatch(withComputePass: computePass, sharedModules: sharedModules) } }
mit
7a8aafda910be2d109d97d6bba68b91c
31.703833
225
0.669614
4.685971
false
false
false
false
1aurabrown/eidolon
Kiosk/Admin/ChooseAuctionViewController.swift
1
1757
import UIKit class ChooseAuctionViewController: UIViewController { var auctions: [Sale]! override func viewDidLoad() { super.viewDidLoad() stackScrollView.backgroundColor = UIColor.whiteColor() stackScrollView.bottomMarginHeight = CGFloat(NSNotFound) stackScrollView.updateConstraints() let endpoint: ArtsyAPI = ArtsyAPI.ActiveAuctions XAppRequest(endpoint, method: .GET, parameters: endpoint.defaultParameters).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Sale.self) .subscribeNext({ [weak self] (activeSales) -> Void in self!.auctions = activeSales as [Sale] for i in 0 ..< countElements(self!.auctions) { let sale = self!.auctions[i] let button = ARFlatButton() button.setTitle(" \(sale.name) - #\(sale.artworkCount)", forState: .Normal) button.setTitleColor(UIColor.blackColor(), forState: .Normal) button.tag = i button.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (_) in let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(sale.id, forKey: "KioskAuctionID") defaults.synchronize() exit(1) } self!.stackScrollView.addSubview(button, withTopMargin: "12", sideMargin: "0") button.constrainHeight("50") } }) } @IBOutlet weak var stackScrollView: ORStackView! @IBAction func backButtonTapped(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } }
mit
f7e8d0fce06acafa51c6afc03fa796b5
38.931818
151
0.596471
5.63141
false
false
false
false
CombineCommunity/CombineExt
Tests/PartitionTests.swift
1
1518
// // WithLatestFrom.swift // CombineExtTests // // Created by Shai Mishali on 24/10/2019. // Copyright © 2020 Combine Community. All rights reserved. // #if !os(watchOS) import XCTest import Combine import CombineExt @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) class PartitionTests: XCTestCase { var source = PassthroughRelay<Int>() var evenSub: AnyCancellable! var oddSub: AnyCancellable! override func setUp() { source = .init() evenSub = nil oddSub = nil } func testPartitionBothMatch() { let (evens, odds) = source.partition { $0 % 2 == 0 } var evenValues = [Int]() var oddValues = [Int]() evenSub = evens .sink(receiveValue: { evenValues.append($0) }) oddSub = odds .sink(receiveValue: { oddValues.append($0) }) (0...10).forEach { source.accept($0) } XCTAssertEqual([1, 3, 5, 7, 9], oddValues) XCTAssertEqual([0, 2, 4, 6, 8, 10], evenValues) } func testPartitionOneSideMatch() { let (all, none) = source.partition { $0 <= 10 } var allValues = [Int]() var noneValues = [Int]() evenSub = all .sink(receiveValue: { allValues.append($0) }) oddSub = none .sink(receiveValue: { noneValues.append($0) }) (0...10).forEach { source.accept($0) } XCTAssertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], allValues) XCTAssertTrue(noneValues.isEmpty) } } #endif
mit
9cd69bf9888ebd2554fd59978f5e7f8e
24.283333
69
0.574819
3.620525
false
true
false
false
kfix/MacPin
modules/Linenoise/Terminal.swift
1
9038
/* Copyright (c) 2017, Andy Best <andybest.net at gmail dot com> Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com> Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation internal struct Terminal { static func isTTY(_ fileHandle: Int32) -> Bool { let rv = isatty(fileHandle) return rv == 1 } // MARK: Raw Mode static func withRawMode(_ fileHandle: Int32, body: () throws -> ()) throws { if !isTTY(fileHandle) { throw LinenoiseError.notATTY } var originalTermios: termios = termios() defer { // Disable raw mode _ = tcsetattr(fileHandle, TCSAFLUSH, &originalTermios) } if tcgetattr(fileHandle, &originalTermios) == -1 { throw LinenoiseError.generalError("Could not get term attributes") } var raw = originalTermios #if os(Linux) || os(FreeBSD) raw.c_iflag &= ~UInt32(BRKINT | ICRNL | INPCK | ISTRIP | IXON) raw.c_oflag &= ~UInt32(OPOST) raw.c_cflag |= UInt32(CS8) raw.c_lflag &= ~UInt32(ECHO | ICANON | IEXTEN | ISIG) #else raw.c_iflag &= ~UInt(BRKINT | ICRNL | INPCK | ISTRIP | IXON) /* raw.c_oflag &= ~UInt(OPOST) MP: commented out because we want post-processed output from the TTY so that ONLCR works */ raw.c_oflag |= UInt(ONLCR) // MP: translate newline to carriage-return+newline ( this is default - but making it explicit ) raw.c_cflag |= UInt(CS8) raw.c_lflag &= ~UInt(ECHO | ICANON | IEXTEN | ISIG) #endif // VMIN = 16 raw.c_cc.16 = 1 if tcsetattr(fileHandle, Int32(TCSAFLUSH), &raw) < 0 { throw LinenoiseError.generalError("Could not set raw mode") } // Run the body try body() } // MARK: - Colors enum ColorSupport { case standard case twoFiftySix } // Colour tables from https://jonasjacek.github.io/colors/ // Format: (r, g, b) static let colors: [(Int, Int, Int)] = [ // Standard (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128), (192, 192, 192), // High intensity (128, 128, 128), (255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255), // 256 color extended (0, 0, 0), (0, 0, 95), (0, 0, 135), (0, 0, 175), (0, 0, 215), (0, 0, 255), (0, 95, 0), (0, 95, 95), (0, 95, 135), (0, 95, 175), (0, 95, 215), (0, 95, 255), (0, 135, 0), (0, 135, 95), (0, 135, 135), (0, 135, 175), (0, 135, 215), (0, 135, 255), (0, 175, 0), (0, 175, 95), (0, 175, 135), (0, 175, 175), (0, 175, 215), (0, 175, 255), (0, 215, 0), (0, 215, 95), (0, 215, 135), (0, 215, 175), (0, 215, 215), (0, 215, 255), (0, 255, 0), (0, 255, 95), (0, 255, 135), (0, 255, 175), (0, 255, 215), (0, 255, 255), (95, 0, 0), (95, 0, 95), (95, 0, 135), (95, 0, 175), (95, 0, 215), (95, 0, 255), (95, 95, 0), (95, 95, 95), (95, 95, 135), (95, 95, 175), (95, 95, 215), (95, 95, 255), (95, 135, 0), (95, 135, 95), (95, 135, 135), (95, 135, 175), (95, 135, 215), (95, 135, 255), (95, 175, 0), (95, 175, 95), (95, 175, 135), (95, 175, 175), (95, 175, 215), (95, 175, 255), (95, 215, 0), (95, 215, 95), (95, 215, 135), (95, 215, 175), (95, 215, 215), (95, 215, 255), (95, 255, 0), (95, 255, 95), (95, 255, 135), (95, 255, 175), (95, 255, 215), (95, 255, 255), (135, 0, 0), (135, 0, 95), (135, 0, 135), (135, 0, 175), (135, 0, 215), (135, 0, 255), (135, 95, 0), (135, 95, 95), (135, 95, 135), (135, 95, 175), (135, 95, 215), (135, 95, 255), (135, 135, 0), (135, 135, 95), (135, 135, 135), (135, 135, 175), (135, 135, 215), (135, 135, 255), (135, 175, 0), (135, 175, 95), (135, 175, 135), (135, 175, 175), (135, 175, 215), (135, 175, 255), (135, 215, 0), (135, 215, 95), (135, 215, 135), (135, 215, 175), (135, 215, 215), (135, 215, 255), (135, 255, 0), (135, 255, 95), (135, 255, 135), (135, 255, 175), (135, 255, 215), (135, 255, 255), (175, 0, 0), (175, 0, 95), (175, 0, 135), (175, 0, 175), (175, 0, 215), (175, 0, 255), (175, 95, 0), (175, 95, 95), (175, 95, 135), (175, 95, 175), (175, 95, 215), (175, 95, 255), (175, 135, 0), (175, 135, 95), (175, 135, 135), (175, 135, 175), (175, 135, 215), (175, 135, 255), (175, 175, 0), (175, 175, 95), (175, 175, 135), (175, 175, 175), (175, 175, 215), (175, 175, 255), (175, 215, 0), (175, 215, 95), (175, 215, 135), (175, 215, 175), (175, 215, 215), (175, 215, 255), (175, 255, 0), (175, 255, 95), (175, 255, 135), (175, 255, 175), (175, 255, 215), (175, 255, 255), (215, 0, 0), (215, 0, 95), (215, 0, 135), (215, 0, 175), (215, 0, 215), (215, 0, 255), (215, 95, 0), (215, 95, 95), (215, 95, 135), (215, 95, 175), (215, 95, 215), (215, 95, 255), (215, 135, 0), (215, 135, 95), (215, 135, 135), (215, 135, 175), (215, 135, 215), (215, 135, 255), (215, 175, 0), (215, 175, 95), (215, 175, 135), (215, 175, 175), (215, 175, 215), (215, 175, 255), (215, 215, 0), (215, 215, 95), (215, 215, 135), (215, 215, 175), (215, 215, 215), (215, 215, 255), (215, 255, 0), (215, 255, 95), (215, 255, 135), (215, 255, 175), (215, 255, 215), (215, 255, 255), (255, 0, 0), (255, 0, 95), (255, 0, 135), (255, 0, 175), (255, 0, 215), (255, 0, 255), (255, 95, 0), (255, 95, 95), (255, 95, 135), (255, 95, 175), (255, 95, 215), (255, 95, 255), (255, 135, 0), (255, 135, 95), (255, 135, 135), (255, 135, 175), (255, 135, 215), (255, 135, 255), (255, 175, 0), (255, 175, 95), (255, 175, 135), (255, 175, 175), (255, 175, 215), (255, 175, 255), (255, 215, 0), (255, 215, 95), (255, 215, 135), (255, 215, 175), (255, 215, 215), (255, 215, 255), (255, 255, 0), (255, 255, 95), (255, 255, 135), (255, 255, 175), (255, 255, 215), (255, 255, 255), (8, 8, 8), (18, 18, 18), (28, 28, 28), (38, 38, 38), (48, 48, 48), (58, 58, 58), (68, 68, 68), (78, 78, 78), (88, 88, 88), (98, 98, 98), (108, 108, 108), (118, 118, 118), (128, 128, 128), (138, 138, 138), (148, 148, 148), (158, 158, 158), (168, 168, 168), (178, 178, 178), (188, 188, 188), (198, 198, 198), (208, 208, 208), (218, 218, 218), (228, 228, 228), (238, 238, 238) ] static func termColorSupport(termVar: String) -> ColorSupport { // A rather dumb way of detecting colour support if termVar.contains("256") { return .twoFiftySix } return .standard } static func closestColor(to targetColor: (Int, Int, Int), withColorSupport colorSupport: ColorSupport) -> Int { let colorTable: [(Int, Int, Int)] switch colorSupport { case .standard: colorTable = Array(colors[0..<8]) case .twoFiftySix: colorTable = colors } let distances = colorTable.map { sqrt(pow(Double($0.0 - targetColor.0), 2) + pow(Double($0.1 - targetColor.1), 2) + pow(Double($0.2 - targetColor.2), 2)) } var closest = Double.greatestFiniteMagnitude var closestIdx = 0 for i in 0..<distances.count { if distances[i] < closest { closest = distances[i] closestIdx = i } } return closestIdx } }
gpl-3.0
d3e4cfbb7b8aa8b0face915f5bbb754e
49.49162
135
0.528435
3.05958
false
false
false
false
pmhicks/Spindle-Player
Spindle Player/MusicPlayer.swift
1
6894
// Spindle Player // Copyright (C) 2015 Mike Hicks // // 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 Cocoa private enum PlayerState: String, Printable { case Unloaded = "Unloaded" case Loaded = "Loaded" case FailedLoad = "FailedLoad" case Error = "Error" case Playing = "Playing" case Stopped = "Stopped" case Paused = "Paused" var description : String { get { return self.rawValue } } } class MusicPlayer { private var ap:AudioPlayer? private let context:xmp_context private var state:PlayerState { didSet { println("StateChange Old: \(oldValue) New: \(state)") } } var volume:Float { didSet { if volume > 1.0 { volume = 1.0 } if volume < 0.0 { volume = 0.0 } ap?.volume = volume } } init(volume:Float) { self.volume = volume self.state = .Unloaded self.context = xmp_create_context() let cfg = SpindleConfig.sharedInstance let center = NSNotificationCenter.defaultCenter() center.addObserverForName(SpindleConfig.kQueueFinished, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] _ in if let s = self { if s.state == .Playing { xmp_stop_module(s.context) s.ap = nil s.state = .Stopped center.postNotificationName(SpindleConfig.kSongFinished, object: nil) } } } } deinit { println("deinit MusicPlayer") xmp_stop_module(context) ap = nil sendEndNotification() if !(state == .Unloaded || state == .FailedLoad) { println("releasing XMP") xmp_end_player(context) xmp_release_module(context) } xmp_free_context(context) } func load(url:NSURL) -> (module:ModuleInfo?, success:Bool, error:String) { var xstruct = xmp_test_info() if !url.fileURL { self.state = .FailedLoad return (nil, false, "URL is not a file") } let filename = url.fileSystemRepresentation let loadResult = Int(xmp_load_module(context, filename)) if loadResult != 0 { //let err = lastError() self.state = .FailedLoad let message:String = { switch loadResult { case -3: return "Unrecognized Module Format" case -4: return "Error Loading Module (corrupt file?)" default: return "XMP code \(loadResult)" } }() return (nil, false, message) } var rawinfo = xmp_module_info() xmp_get_module_info(context, &rawinfo) let info = ModuleInfo(info: rawinfo) state = .Loaded return (info, true, "") } func load(item:PlayListItem) -> (module:ModuleInfo?, success:Bool, error:String) { let status = load(item.url) if status.success { item.title = status.module?.name ?? "" item.lengthSeconds = status.module?.durationSeconds ?? 0 } return status } func play() { switch self.state { case .Unloaded, .FailedLoad, .Error: return case .Playing: return case .Paused: ap?.unpause() self.state = .Playing return case .Loaded, .Stopped: let start = xmp_start_player(context, 44100, 0) //println("xmp start status: \(start)") if start != 0 { self.state = .Error musicPlayerError("XMP start failed: \(start)") return } ap = AudioPlayer(context: context, volume: volume) ap?.initPlayer() ap?.play() self.state = .Playing } } func pause() { switch self.state { case .Playing: ap?.pause() self.state = .Paused case .Paused: ap?.unpause() self.state = .Playing default: break } } func endPlayer() { println("End Player") let cfg = SpindleConfig.sharedInstance // let center = NSNotificationCenter.defaultCenter() //center.removeObserver(SpindleConfig.kNotificationSongFinished) self.stop() } func stop() { switch self.state { case .Playing, .Paused: self.state = .Stopped xmp_stop_module(context) ap = nil sendEndNotification() default: break } } private func sendEndNotification() { let center = NSNotificationCenter.defaultCenter() center.postNotificationName(SpindleConfig.kTimeChanged, object: NSNumber(integer: 0)) center.postNotificationName(SpindleConfig.kPositionChanged, object: NSNumber(integer: 0)) } func nextPosition() { xmp_next_position(context) } func previousPosition() { xmp_prev_position(context) } //return false if not playing func seek(seconds:Int) -> Bool { if self.state == .Playing || self.state == .Paused { xmp_seek_time(context, Int32(seconds * 1000)) return true } return false } private func musicPlayerError(msg:String) { let alert = NSAlert() alert.messageText = "Music Player Error" alert.informativeText = msg alert.runModal() } }
mit
9dd5858bf976055e90de1188ea2d7a4d
29.10917
132
0.55367
4.629953
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/4-4 ResponderChain/Scenario 2/ResponderChainDemo/ResponderChainDemo/ViewController.swift
4
1524
// // ViewController.swift // ResponderChainDemo // // Created by Nicholas Outram on 15/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit extension UIResponder { func switchState(_ t : Int) -> Bool? { guard let me = self as? UIView else { return nil } for v in me.subviews { if let sw = v as? UISwitch, v.tag == t { return sw.isOn } } return false } func printNextRepsonderAsString() { var result : String = "\(type(of: self)) got a touch event." if let nr = self.next { result += " The next responder is " + type(of: nr).description() } else { result += " This class has no next responder" } print(result) } } class ViewController: UIViewController { @IBOutlet weak var passUpSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.printNextRepsonderAsString() if passUpSwitch.isOn { //Pass up the responder chain super.touchesBegan(touches, with: event) } } }
mit
eadf7b85245ffb908fd076a188f2ff14
23.967213
80
0.572554
4.587349
false
false
false
false
khizkhiz/swift
stdlib/private/StdlibUnittest/RaceTest.swift
2
16659
//===--- RaceTest.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This file implements support for race tests. /// /// Race test harness executes the given operation in multiple threads over a /// set of shared data, trying to ensure that executions overlap in time. /// /// The name "race test" does not imply that the race actually happens in the /// harness or in the operation being tested. The harness contains all the /// necessary synchronization for its own data, and for publishing test data to /// threads. But if the operation under test is, in fact, racy, it should be /// easier to discover the bug in this environment. /// /// Every execution of a race test is called a trial. During a single trial /// the operation under test is executed multiple times in each thread over /// different data items (`RaceData` instances). Different threads process /// data in different order. Choosing an appropriate balance between the /// number of threads and data items, the harness uses the birthday paradox to /// increase the probability of "collisions" between threads. /// /// After performing the operation under test, the thread should observe the /// data in a test-dependent way to detect if presence of other concurrent /// actions disturbed the result. The observation should be as short as /// possible, and the results should be returned as `Observation`. Evaluation /// (cross-checking) of observations is deferred until the end of the trial. /// //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivatePthreadExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) import Glibc #endif #if _runtime(_ObjC) import ObjectiveC #else func autoreleasepool(@noescape code: () -> Void) { // Native runtime does not have autorelease pools. Execute the code // directly. code() } #endif /// Race tests that need a fresh set of data for every trial should implement /// this protocol. /// /// All racing threads execute the same operation, `thread1`. /// /// Types conforming to this protocol should be structs. (The type /// should be a struct to reduce unnecessary reference counting during /// the test.) The types should be stateless. public protocol RaceTestWithPerTrialData { /// Input for threads. /// /// This type should be a class. (The harness will not pass struct instances /// between threads correctly.) associatedtype RaceData : AnyObject /// Type of thread-local data. /// /// Thread-local data is newly created for every trial. associatedtype ThreadLocalData /// Results of the observation made after performing an operation. associatedtype Observation init() /// Creates a fresh instance of `RaceData`. func makeRaceData() -> RaceData /// Creates a fresh instance of `ThreadLocalData`. func makeThreadLocalData() -> ThreadLocalData /// Performs the operation under test and makes an observation. func thread1( raceData: RaceData, _ threadLocalData: inout ThreadLocalData) -> Observation /// Evaluates the observations made by all threads for a particular instance /// of `RaceData`. func evaluateObservations( observations: [Observation], _ sink: (RaceTestObservationEvaluation) -> Void) } /// The result of evaluating observations. /// /// Case payloads can carry test-specific data. Results will be grouped /// according to it. public enum RaceTestObservationEvaluation : Equatable, CustomStringConvertible { /// Normal 'pass'. case pass /// An unusual 'pass'. case passInteresting(String) /// A failure. case failure case failureInteresting(String) public var description: String { switch self { case .pass: return "Pass" case .passInteresting(let s): return "Pass(\(s))" case .failure: return "Failure" case .failureInteresting(let s): return "Failure(\(s))" } } } public func == ( lhs: RaceTestObservationEvaluation, rhs: RaceTestObservationEvaluation ) -> Bool { switch (lhs, rhs) { case (.pass, .pass), (.failure, .failure): return true case (.passInteresting(let s1), .passInteresting(let s2)): return s1 == s2 default: return false } } /// An observation result that consists of one `UInt`. public struct Observation1UInt : Equatable, CustomStringConvertible { public var data1: UInt public init(_ data1: UInt) { self.data1 = data1 } public var description: String { return "(\(data1))" } } public func == (lhs: Observation1UInt, rhs: Observation1UInt) -> Bool { return lhs.data1 == rhs.data1 } /// An observation result that consists of four `UInt`s. public struct Observation4UInt : Equatable, CustomStringConvertible { public var data1: UInt public var data2: UInt public var data3: UInt public var data4: UInt public init(_ data1: UInt, _ data2: UInt, _ data3: UInt, _ data4: UInt) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4))" } } public func == (lhs: Observation4UInt, rhs: Observation4UInt) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 } /// An observation result that consists of three `Int`s. public struct Observation3Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public init(_ data1: Int, _ data2: Int, _ data3: Int) { self.data1 = data1 self.data2 = data2 self.data3 = data3 } public var description: String { return "(\(data1), \(data2), \(data3))" } } public func == (lhs: Observation3Int, rhs: Observation3Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 } /// An observation result that consists of four `Int`s. public struct Observation4Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public init(_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4))" } } public func == (lhs: Observation4Int, rhs: Observation4Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 } /// An observation result that consists of five `Int`s. public struct Observation5Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public var data5: Int public init( _ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int ) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 self.data5 = data5 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4), \(data5))" } } public func == (lhs: Observation5Int, rhs: Observation5Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 && lhs.data5 == rhs.data5 } /// An observation result that consists of nine `Int`s. public struct Observation9Int : Equatable, CustomStringConvertible { public var data1: Int public var data2: Int public var data3: Int public var data4: Int public var data5: Int public var data6: Int public var data7: Int public var data8: Int public var data9: Int public init( _ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int, _ data6: Int, _ data7: Int, _ data8: Int, _ data9: Int ) { self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data4 = data4 self.data5 = data5 self.data6 = data6 self.data7 = data7 self.data8 = data8 self.data9 = data9 } public var description: String { return "(\(data1), \(data2), \(data3), \(data4), \(data5), \(data6), \(data7), \(data8), \(data9))" } } public func == (lhs: Observation9Int, rhs: Observation9Int) -> Bool { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4 == rhs.data4 && lhs.data5 == rhs.data5 && lhs.data6 == rhs.data6 && lhs.data7 == rhs.data7 && lhs.data8 == rhs.data8 && lhs.data9 == rhs.data9 } /// A helper that is useful to implement /// `RaceTestWithPerTrialData.evaluateObservations()` in race tests. public func evaluateObservationsAllEqual<T : Equatable>(observations: [T]) -> RaceTestObservationEvaluation { let first = observations.first! for x in observations { if x != first { return .failure } } return .pass } struct _RaceTestAggregatedEvaluations : CustomStringConvertible { var passCount: Int = 0 var passInterestingCount = [String: Int]() var failureCount: Int = 0 var failureInterestingCount = [String: Int]() init() {} mutating func addEvaluation(evaluation: RaceTestObservationEvaluation) { switch evaluation { case .pass: passCount += 1 case .passInteresting(let s): if passInterestingCount[s] == nil { passInterestingCount[s] = 0 } passInterestingCount[s] = passInterestingCount[s]! + 1 case .failure: failureCount += 1 case .failureInteresting(let s): if failureInterestingCount[s] == nil { failureInterestingCount[s] = 0 } failureInterestingCount[s] = failureInterestingCount[s]! + 1 } } var isFailed: Bool { return failureCount != 0 || !failureInterestingCount.isEmpty } var description: String { var result = "" result += "Pass: \(passCount) times\n" for desc in passInterestingCount.keys.sorted() { let count = passInterestingCount[desc]! result += "Pass \(desc): \(count) times\n" } result += "Failure: \(failureCount) times\n" for desc in failureInterestingCount.keys.sorted() { let count = failureInterestingCount[desc]! result += "Failure \(desc): \(count) times\n" } return result } } // FIXME: protect this class against false sharing. class _RaceTestWorkerState<RT : RaceTestWithPerTrialData> { // FIXME: protect every element of 'raceData' against false sharing. var raceData: [RT.RaceData] = [] var raceDataShuffle: [Int] = [] var observations: [RT.Observation] = [] } class _RaceTestSharedState<RT : RaceTestWithPerTrialData> { var racingThreadCount: Int var trialBarrier: _stdlib_Barrier var trialSpinBarrier: _stdlib_AtomicInt = _stdlib_AtomicInt() var raceData: [RT.RaceData] = [] var workerStates: [_RaceTestWorkerState<RT>] = [] var aggregatedEvaluations: _RaceTestAggregatedEvaluations = _RaceTestAggregatedEvaluations() init(racingThreadCount: Int) { self.racingThreadCount = racingThreadCount self.trialBarrier = _stdlib_Barrier(threadCount: racingThreadCount + 1) self.workerStates.reserveCapacity(racingThreadCount) for _ in 0..<racingThreadCount { self.workerStates.append(_RaceTestWorkerState<RT>()) } } } func _masterThreadOneTrial<RT : RaceTestWithPerTrialData>( sharedState: _RaceTestSharedState<RT> ) { let racingThreadCount = sharedState.racingThreadCount let raceDataCount = racingThreadCount * racingThreadCount let rt = RT() sharedState.raceData.removeAll(keepingCapacity: true) sharedState.raceData.append(contentsOf: (0..<raceDataCount).lazy.map { i in rt.makeRaceData() }) let identityShuffle = Array(0..<sharedState.raceData.count) sharedState.workerStates.removeAll(keepingCapacity: true) sharedState.workerStates.append(contentsOf: (0..<racingThreadCount).lazy.map { i in let workerState = _RaceTestWorkerState<RT>() // Shuffle the data so that threads process it in different order. let shuffle = randomShuffle(identityShuffle) workerState.raceData = scatter(sharedState.raceData, shuffle) workerState.raceDataShuffle = shuffle workerState.observations = [] workerState.observations.reserveCapacity(sharedState.raceData.count) return workerState }) sharedState.trialSpinBarrier.store(0) sharedState.trialBarrier.wait() // Race happens. sharedState.trialBarrier.wait() // Collect and compare results. for i in 0..<racingThreadCount { let shuffle = sharedState.workerStates[i].raceDataShuffle sharedState.workerStates[i].raceData = gather(sharedState.workerStates[i].raceData, shuffle) sharedState.workerStates[i].observations = gather(sharedState.workerStates[i].observations, shuffle) } if true { // FIXME: why doesn't the bracket syntax work? // <rdar://problem/18305718> Array sugar syntax does not work when used // with associated types var observations: [RT.Observation] = [] observations.reserveCapacity(racingThreadCount) for i in 0..<raceDataCount { for j in 0..<racingThreadCount { observations.append(sharedState.workerStates[j].observations[i]) } let sink = { sharedState.aggregatedEvaluations.addEvaluation($0) } rt.evaluateObservations(observations, sink) observations.removeAll(keepingCapacity: true) } } } func _workerThreadOneTrial<RT : RaceTestWithPerTrialData>( tid: Int, _ sharedState: _RaceTestSharedState<RT> ) { sharedState.trialBarrier.wait() let racingThreadCount = sharedState.racingThreadCount let workerState = sharedState.workerStates[tid] let rt = RT() var threadLocalData = rt.makeThreadLocalData() if true { let trialSpinBarrier = sharedState.trialSpinBarrier trialSpinBarrier.fetchAndAdd(1) while trialSpinBarrier.load() < racingThreadCount {} } // Perform racy operations. // Warning: do not add any synchronization in this loop, including // any implicit reference counting of shared data. for raceData in workerState.raceData { workerState.observations.append(rt.thread1(raceData, &threadLocalData)) } sharedState.trialBarrier.wait() } public func runRaceTest<RT : RaceTestWithPerTrialData>( _: RT.Type, trials: Int, threads: Int? = nil ) { let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency()) let sharedState = _RaceTestSharedState<RT>(racingThreadCount: racingThreadCount) let masterThreadBody: () -> Void = { () -> Void in for _ in 0..<trials { autoreleasepool { _masterThreadOneTrial(sharedState) } } } let racingThreadBody: (Int) -> Void = { (tid: Int) -> Void in for _ in 0..<trials { _workerThreadOneTrial(tid, sharedState) } } var allTids = [pthread_t]() // Create the master thread. if true { let (ret, tid) = _stdlib_pthread_create_block( nil, masterThreadBody, ()) expectEqual(0, ret) allTids.append(tid!) } // Create racing threads. for i in 0..<racingThreadCount { let (ret, tid) = _stdlib_pthread_create_block( nil, racingThreadBody, i) expectEqual(0, ret) allTids.append(tid!) } // Join all threads. for tid in allTids { let (ret, _) = _stdlib_pthread_join(tid, Void.self) expectEqual(0, ret) } let aggregatedEvaluations = sharedState.aggregatedEvaluations expectFalse(aggregatedEvaluations.isFailed) print(aggregatedEvaluations) } internal func _divideRoundUp(lhs: Int, _ rhs: Int) -> Int { return (lhs + rhs) / rhs } public func runRaceTest<RT : RaceTestWithPerTrialData>( test: RT.Type, operations: Int, threads: Int? = nil ) { let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency()) // Each trial runs threads^2 operations. let operationsPerTrial = racingThreadCount * racingThreadCount let trials = _divideRoundUp(operations, operationsPerTrial) runRaceTest(test, trials: trials, threads: threads) } public func consumeCPU(units amountOfWork: Int) { for _ in 0..<amountOfWork { let scale = 16 for _ in 0..<scale { _blackHole(42) } } }
apache-2.0
d65c41e34d15a25d87334915e185db61
28.073298
103
0.679393
4.137854
false
true
false
false
randymarsh77/crystal
Sources/Crystal/audiostreamplayer.swift
1
1479
import AudioToolbox import Cast import Foundation import Scope import Streams public class AudioStreamPlayer { public var stream: SynchronizedDataStream var subscription: Scope public init() { self.stream = SynchronizedDataStream() let player = AQPlayer() let parse = try! AFSUtility.CreateCustomAudioStreamParser( onStreamReady: { (_, asbd, cookieData) in try! player.initialize(asbd: asbd, cookieData: cookieData) }, onPackets: player.playPackets!) self.subscription = self.stream.addSubscriber() { (data: Data) -> Void in try! parse(data) } } } public class V2AudioStreamPlayer { public var stream: WriteableStream<AudioData> public init() { var isInitialized = false let s = Streams.Stream<AudioData>() let player = AQPlayer() _ = s.subscribe { (data: AudioData) -> Void in if (!isInitialized) { let p = UnsafeMutablePointer<AudioStreamBasicDescription>.allocate(capacity: 1) p.initialize(to: data.description) try! player.initialize(asbd: p, cookieData: nil) isInitialized = true } data.data.withUnsafeBytes() { player.playPackets!(UInt32(data.data.count), data.packetInfo?.count ?? 0, $0.baseAddress!, data.packetInfo?.descriptions, AsPointer(data.startTime)) } } stream = WriteableStream(s) } } public func AsPointer<T>(_ obj: T?) -> UnsafePointer<T>? { if (obj == nil) { return nil } let p = UnsafeMutablePointer<T>.allocate(capacity: 1) p.initialize(to: obj!) return Cast(p) }
mit
e4dce4faf8703b2c801cd5776ffad81f
23.245902
152
0.710615
3.353741
false
false
false
false
Draveness/RbSwift
Sources/Stat.swift
2
9106
// // Stat.swift // RbSwift // // Created by draveness on 22/04/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation // from <sys/stat.h> (not in Foundation) /* File mode */ /* Read, write, execute/search by owner */ private let S_IRWXU: Int = 0o000700 /* [XSI] RWX mask for owner */ private let S_IRUSR: Int = 0o000400 /* [XSI] R for owner */ private let S_IWUSR: Int = 0o000200 /* [XSI] W for owner */ private let S_IXUSR: Int = 0o000100 /* [XSI] X for owner */ /* Read, write, execute/search by group */ private let S_IRWXG: Int = 0o000070 /* [XSI] RWX mask for group */ private let S_IRGRP: Int = 0o000040 /* [XSI] R for group */ private let S_IWGRP: Int = 0o000020 /* [XSI] W for group */ private let S_IXGRP: Int = 0o000010 /* [XSI] X for group */ /* Read, write, execute/search by others */ private let S_IRWXO: Int = 0o000007 /* [XSI] RWX mask for other */ private let S_IROTH: Int = 0o000004 /* [XSI] R for other */ private let S_IWOTH: Int = 0o000002 /* [XSI] W for other */ private let S_IXOTH: Int = 0o000001 /* [XSI] X for other */ public class Stat { private var info = stat() /// Creates a `Stat` instance with `fstat` located in Darwin library. /// Internal uses `fstat` to extract `Stat` information from specific file /// descriptor. /// /// - Parameter fileno: A file number public init(_ fileno: Int) { fstat(fileno.to_i32, &info) } /// Creates a `Stat` instance with `stat` located in Darwin library. /// Internal uses `stat` to extract `Stat` information from specific path. /// /// - Parameter path: A file path. public init(_ path: String) { stat(path, &info) } /// Returns the last access time for this file as an object of class `Date`. public var atime: Date { return Date(timespec: info.st_atimespec) } /// Returns the birth time for stat. public var birthtime: Date { return Date(timespec: info.st_birthtimespec) } /// Returns the native file system’s block size. public var blksize: Int { return info.st_blksize.to_i } /// Returns the number of native file system blocks allocated for this file. public var blocks: Int { return info.st_blocks.to_i } /// Returns the change time for stat (that is, the time directory information about the file /// was changed, not the file itself). public var ctime: Date { return Date(timespec: info.st_ctimespec) } /// Returns an integer representing the device on which stat resides. public var dev: Int { return info.st_dev.to_i } /// Returns the numeric group id of the owner of stat. public var gid: Int { return info.st_gid.to_i } /// Returns true if the effective group id of the process is the same as the group id /// of stat. public var isGroupOwned: Bool { let egid = gid_t(getegid()) var groups = [gid_t](repeating: 0, count: 1000) let gcount = getgroups(groups.count.to_i32, &groups) for index in 0..<gcount.to_i { if groups[index] == egid { return true } } return false } /// Returns the inode number for stat. public var ino: Int { return info.st_ino.to_i } /// Returns an integer representing the permission bits of stat. public var mode: Int { return info.st_mode.to_i } /// Returns the modification time of stat. public var mtime: Date { return Date(timespec: info.st_mtimespec) } /// Returns the number of hard links to stat. public var nlink: Int { return info.st_nlink.to_i } /// Returns true if the effective user id of the process is the same as the owner /// of stat. public var isOwned: Bool { return geteuid() == info.st_uid } /// Returns an integer representing the device type on which stat resides. public var rdev: Int { return info.st_rdev.to_i } /// Returns the size of stat in bytes. public var size: Int { return info.st_size.to_i } /// Returns the numeric user id of the owner of stat. public var uid: Int { return info.st_uid.to_i } /// Returns true if stat is a zero-length file; false otherwise. public var isZero: Bool { return info.st_size == 0 } } private let S_ISUID: Int = 0o004000 /* [XSI] set user id on execution */ private let S_ISGID: Int = 0o002000 /* [XSI] set group id on execution */ private let S_ISVTX: Int = 0o001000 /* [XSI] directory restrcted delete */ private let S_IFMT : Int = 0o170000 /* [XSI] type of file mask */ private let S_IFIFO: Int = 0o010000 /* [XSI] named pipe (fifo) */ private let S_IFCHR: Int = 0o020000 /* [XSI] character special */ private let S_IFDIR: Int = 0o040000 /* [XSI] directory */ private let S_IFBLK: Int = 0o060000 /* [XSI] block special */ private let S_IFREG: Int = 0o100000 /* [XSI] regular */ private let S_IFLNK: Int = 0o120000 /* [XSI] symbolic link */ private let S_IFSOCK:Int = 0o140000 /* [XSI] socket */ // MARK: - File type extension Stat { /// Returns true if stat has the set-group-id permission bit set, false if it /// doesn’t or if the operating system doesn’t support this feature. public var isSetgid: Bool { return mode & S_ISGID != 0 } /// Returns true if stat has the set-user-id permission bit set, false if it /// doesn’t or if the operating system doesn’t support this feature. public var isSetuid: Bool { return mode & S_ISUID != 0 } /// Returns true if stat has its sticky bit set, false if it doesn’t or if the /// operating system doesn’t support this feature. public var isSticky: Bool { return mode & S_ISVTX != 0 } /// Returns true if the file is a block device, false if it isn’t or if the /// operating system doesn’t support this feature. public var isBlockDev: Bool { return mode & S_IFMT == S_IFBLK } /// Returns true if the file is a character device, false if it isn’t or if the /// operating system doesn’t support this feature. public var isCharDev: Bool { return mode & S_IFMT == S_IFCHR } /// Returns true if stat is a regular file (not a device file, pipe, socket, etc.). public var isFile: Bool { return mode & S_IFMT == S_IFREG } /// Returns true if the named file is a directory, or a symlink that points at a /// directory, and false otherwise. public var isDirectory: Bool { return mode & S_IFMT == S_IFDIR } /// Returns true if the operating system supports pipes and stat is a pipe; false /// otherwise. public var isPipe: Bool { return mode & S_IFMT == S_IFIFO } /// Returns true if stat is a socket, false if it isn’t or if the operating system /// doesn’t support this feature. public var isSocket: Bool { return mode & S_IFMT == S_IFSOCK } /// Returns true if stat is a symbolic link, false if it isn’t or if the operating /// system doesn’t support this feature. public var isSymlink: Bool { return mode & S_IFMT == S_IFLNK } /// Identifies the type of the named file; the return string is one of "file", "directory", /// "characterSpecial", "blockSpecial", "fifo", "link", "socket", or "unknown". public var ftype: String { return isFile ? "file" : isDirectory ? "directory" : isCharDev ? "characterSpecial" : isBlockDev ? "blockSpecial" : isPipe ? "fifo" : isSymlink ? "link" : isSocket ? "socket" : "unknown" } } extension Stat: CustomStringConvertible { /// A textual representation of this instance. /// /// Instead of accessing this property directly, convert an instance of any /// type to a string by using the `String(describing:)` initializer. For /// example: /// /// struct Point: CustomStringConvertible { /// let x: Int, y: Int /// /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(describing: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `description` property. public var description: String { return inspect } /// Produce a nicely formatted description of stat. public var inspect: String { return "<Stat dev=\(dev), ino=\(ino), mode=\(mode), nlink=\(nlink), uid=\(uid), gid=\(gid), rdev=\(rdev), size=\(size), blksize=\(blksize), blocks=\(blocks), atime=\(atime), mtime=\(mtime), ctime=\(ctime), birthtime=\(birthtime)>" } }
mit
d46ea9ba1f73c29bae4f97dac68dff43
32.736059
238
0.600441
3.675577
false
false
false
false
FirebaseExtended/firestore-codelab-extended-swift
FriendlyEats/Restaurants/NewReviewViewController.swift
1
2898
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseFirestore import FirebaseAuth class NewReviewViewController: UIViewController, UITextFieldDelegate { static func fromStoryboard(_ storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil), forRestaurant restaurant: Restaurant) -> NewReviewViewController { let controller = storyboard.instantiateViewController(withIdentifier: "NewReviewViewController") as! NewReviewViewController controller.restaurant = restaurant return controller } /// The restaurant being reviewed. This must be set when the controller is created. private var restaurant: Restaurant! @IBOutlet var doneButton: UIBarButtonItem! @IBOutlet var ratingView: RatingView! { didSet { ratingView.addTarget(self, action: #selector(ratingDidChange(_:)), for: .valueChanged) } } @IBOutlet var reviewTextField: UITextField! { didSet { reviewTextField.addTarget(self, action: #selector(textFieldTextDidChange(_:)), for: .editingChanged) } } override func viewDidLoad() { super.viewDidLoad() doneButton.isEnabled = false reviewTextField.delegate = self } @IBAction func cancelButtonPressed(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func doneButtonPressed(_ sender: Any) { // TODO: handle user not logged in. guard let user = Auth.auth().currentUser.flatMap(User.init) else { return } let review = Review(restaurantID: restaurant.documentID, restaurantName: restaurant.name, rating: ratingView.rating!, userInfo: user, text: reviewTextField.text!, date: Date(), yumCount: 0) // TODO: Write the review to Firestore. } @objc func ratingDidChange(_ sender: Any) { updateSubmitButton() } func textFieldIsEmpty() -> Bool { guard let text = reviewTextField.text else { return true } return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } func updateSubmitButton() { doneButton.isEnabled = (ratingView.rating != nil && !textFieldIsEmpty()) } @objc func textFieldTextDidChange(_ sender: Any) { updateSubmitButton() } }
apache-2.0
98544cdff4c91807670f5e278ae44f0f
31.931818
128
0.687026
4.782178
false
false
false
false
wuleijun/Zeus
Zeus/Views/RJExpandableTableView.swift
1
6491
// // RJExpandableTableView.swift // RJExpandableTableView // // Created by 吴蕾君 on 16/5/12. // Copyright © 2016年 rayjuneWu. All rights reserved. // import UIKit public protocol RJExpandableTableViewDataSource: UITableViewDataSource { func tableView(tableView: RJExpandableTableView, canExpandInSection section: Int) -> Bool func tableView(tableView: RJExpandableTableView, expandingCellForSection section: Int) -> RJExpandingTableViewCell func tableView(tableView: RJExpandableTableView, needsToDownloadDataForExpandSection section: Int) -> Bool } public protocol RJExpandableTableViewDelegate: UITableViewDelegate { func tableView(tableView: RJExpandableTableView, downloadDataForExpandableSection section: Int) } public class RJExpandableTableView: UITableView { lazy var canExpandedSections = [Int]() lazy var expandedSections = [Int]() lazy var downloadingSections = [Int]() public override var delegate: UITableViewDelegate? { get{ return super.delegate } set{ super.delegate = self expandDelegate = newValue as? RJExpandableTableViewDelegate } } public override var dataSource: UITableViewDataSource? { get{ return super.dataSource } set{ super.dataSource = self guard newValue is RJExpandableTableViewDataSource else { fatalError("Must has a datasource conforms to protocol 'RJExpandableTableViewDataSource'") } expandDataSource = newValue as! RJExpandableTableViewDataSource } } private weak var expandDataSource: RJExpandableTableViewDataSource! private weak var expandDelegate: RJExpandableTableViewDelegate! // MARK: Public public func expandSection(section: Int, animated: Bool) { guard !expandedSections.contains(section) else { return } if let downloadingIndex = downloadingSections.indexOf(section) { downloadingSections.removeAtIndex(downloadingIndex) } deselectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: section), animated: false) expandedSections.append(section) reloadData() } public func collapseSection(section: Int, animated: Bool) { if let index = expandedSections.indexOf(section) { expandedSections.removeAtIndex(index) } reloadData() } public func cancelDownloadInSection(section: Int) { guard let index = downloadingSections.indexOf(section) else { return } downloadingSections.removeAtIndex(index) reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: section)], withRowAnimation: .Automatic) } public func canExpandSection(section: Int) -> Bool { return canExpandedSections.contains(section) } public func isSectionExpand(section: Int) -> Bool { return true } // MARK: Private Helper private func canExpand(section:Int) -> Bool { return expandDataSource.tableView(self, canExpandInSection: section) } private func needsToDownload(section: Int) -> Bool { return expandDataSource.tableView(self, needsToDownloadDataForExpandSection: section) } private func downloadData(inSection section: Int) { downloadingSections.append(section) expandDelegate?.tableView(self, downloadDataForExpandableSection: section) reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: section)], withRowAnimation: .Automatic) } } // MARK: TableView DataSource extension RJExpandableTableView : UITableViewDataSource { public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return expandDataSource.numberOfSectionsInTableView!(tableView) } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if canExpand(section) { canExpandedSections.append(section) if expandedSections.contains(section) { return expandDataSource.tableView(self, numberOfRowsInSection: section) + 1 }else{ return 1 } }else{ return expandDataSource.tableView(self, numberOfRowsInSection: section) } } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = indexPath.section if canExpand(section) { if indexPath.row == 0 { let expandCell = expandDataSource.tableView(self, expandingCellForSection: section) if downloadingSections.contains(section) { expandCell.setLoading(true) }else{ expandCell.setLoading(false) if (expandedSections.contains(section)) { expandCell.setExpandStatus(RJExpandStatus.Expanded, animated: false) } else { expandCell.setExpandStatus(RJExpandStatus.Collapsed, animated: false) } } return expandCell as! UITableViewCell }else{ return expandDataSource.tableView(self, cellForRowAtIndexPath: indexPath) } }else{ return expandDataSource.tableView(self, cellForRowAtIndexPath: indexPath) } } } // MARK: TableView Delegate extension RJExpandableTableView : UITableViewDelegate { public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return expandDelegate.tableView!(tableView, heightForRowAtIndexPath: indexPath) } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section if canExpand(section) { if indexPath.row == 0 { if expandedSections.contains(section) { collapseSection(section, animated: true) }else{ if needsToDownload(section) { downloadData(inSection: section) }else{ expandSection(section, animated: true) } } } } } }
mit
9ba0aef7549bf034b2e906a944a46967
35.217877
118
0.641623
5.563948
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CheckoutDiscountCodeRemovePayload.swift
1
5778
// // CheckoutDiscountCodeRemovePayload.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Return type for `checkoutDiscountCodeRemove` mutation. open class CheckoutDiscountCodeRemovePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CheckoutDiscountCodeRemovePayload /// The updated checkout object. @discardableResult open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutDiscountCodeRemovePayloadQuery { let subquery = CheckoutQuery() subfields(subquery) addField(field: "checkout", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @discardableResult open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutDiscountCodeRemovePayloadQuery { let subquery = CheckoutUserErrorQuery() subfields(subquery) addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") @discardableResult open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutDiscountCodeRemovePayloadQuery { let subquery = UserErrorQuery() subfields(subquery) addField(field: "userErrors", aliasSuffix: alias, subfields: subquery) return self } } /// Return type for `checkoutDiscountCodeRemove` mutation. open class CheckoutDiscountCodeRemovePayload: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CheckoutDiscountCodeRemovePayloadQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "checkout": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CheckoutDiscountCodeRemovePayload.self, field: fieldName, value: fieldValue) } return try Checkout(fields: value) case "checkoutUserErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutDiscountCodeRemovePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try CheckoutUserError(fields: $0) } case "userErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutDiscountCodeRemovePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try UserError(fields: $0) } default: throw SchemaViolationError(type: CheckoutDiscountCodeRemovePayload.self, field: fieldName, value: fieldValue) } } /// The updated checkout object. open var checkout: Storefront.Checkout? { return internalGetCheckout() } func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? { return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout? } /// The list of errors that occurred from executing the mutation. open var checkoutUserErrors: [Storefront.CheckoutUserError] { return internalGetCheckoutUserErrors() } func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] { return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError] } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") open var userErrors: [Storefront.UserError] { return internalGetUserErrors() } func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] { return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError] } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "checkout": if let value = internalGetCheckout() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "checkoutUserErrors": internalGetCheckoutUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "userErrors": internalGetUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } default: break } } return response } } }
mit
f2a25e7becdbe53706f3aaf3b43d8ba4
36.519481
143
0.733645
4.28
false
false
false
false
ReactiveX/RxSwift
RxExample/RxExample/Examples/GitHubSignup/UsingDriver/GithubSignupViewModel2.swift
2
4211
// // GithubSignupViewModel2.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa /** This is example where view model is mutable. Some consider this to be MVVM, some consider this to be Presenter, or some other name. In the end, it doesn't matter. If you want to take a look at example using "immutable VMs", take a look at `TableViewWithEditingCommands` example. This uses Driver builder for sequences. Please note that there is no explicit state, outputs are defined using inputs and dependencies. Please note that there is no dispose bag, because no subscription is being made. */ class GithubSignupViewModel2 { // outputs { // let validatedUsername: Driver<ValidationResult> let validatedPassword: Driver<ValidationResult> let validatedPasswordRepeated: Driver<ValidationResult> // Is signup button enabled let signupEnabled: Driver<Bool> // Has user signed in let signedIn: Driver<Bool> // Is signing process in progress let signingIn: Driver<Bool> // } init( input: ( username: Driver<String>, password: Driver<String>, repeatedPassword: Driver<String>, loginTaps: Signal<()> ), dependency: ( API: GitHubAPI, validationService: GitHubValidationService, wireframe: Wireframe ) ) { let API = dependency.API let validationService = dependency.validationService let wireframe = dependency.wireframe /** Notice how no subscribe call is being made. Everything is just a definition. Pure transformation of input sequences to output sequences. When using `Driver`, underlying observable sequence elements are shared because driver automagically adds "shareReplay(1)" under the hood. .observe(on:MainScheduler.instance) .catchAndReturn(.Failed(message: "Error contacting server")) ... are squashed into single `.asDriver(onErrorJustReturn: .Failed(message: "Error contacting server"))` */ validatedUsername = input.username .flatMapLatest { username in return validationService.validateUsername(username) .asDriver(onErrorJustReturn: .failed(message: "Error contacting server")) } validatedPassword = input.password .map { password in return validationService.validatePassword(password) } validatedPasswordRepeated = Driver.combineLatest(input.password, input.repeatedPassword, resultSelector: validationService.validateRepeatedPassword) let signingIn = ActivityIndicator() self.signingIn = signingIn.asDriver() let usernameAndPassword = Driver.combineLatest(input.username, input.password) { (username: $0, password: $1) } signedIn = input.loginTaps.withLatestFrom(usernameAndPassword) .flatMapLatest { pair in return API.signup(pair.username, password: pair.password) .trackActivity(signingIn) .asDriver(onErrorJustReturn: false) } .flatMapLatest { loggedIn -> Driver<Bool> in let message = loggedIn ? "Mock: Signed in to GitHub." : "Mock: Sign in to GitHub failed" return wireframe.promptFor(message, cancelAction: "OK", actions: []) // propagate original value .map { _ in loggedIn } .asDriver(onErrorJustReturn: false) } signupEnabled = Driver.combineLatest( validatedUsername, validatedPassword, validatedPasswordRepeated, signingIn ) { username, password, repeatPassword, signingIn in username.isValid && password.isValid && repeatPassword.isValid && !signingIn } .distinctUntilChanged() } }
mit
220d1f8c5f1ffd684281c511f8398db9
33.227642
156
0.621378
5.568783
false
true
false
false