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
daniel-beard/simlang_xcode_plugin
simlang_xcode_plugin/simlang.swift
1
4106
#!/usr/bin/env xcrun swift // // main.swift // simlang_swift // // Created by Daniel Beard on 9/22/14. // Copyright (c) 2014 DanielBeard. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2014 Daniel Beard // // 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 func printUsage() { println("simlang_swift v1.0") println("Author: Daniel Beard") println("Usage:") println() println("simlang {languageCode}") println("simlang es-MX") println("simlang ru") } func runTask(launchPath: String, arguments: Array<String>, printOutput: Bool) { let task = NSTask() task.launchPath = launchPath task.arguments = arguments let pipe = NSPipe() task.standardOutput = pipe task.standardError = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)! if printOutput { println(output) } } func changeLanguageFor(fileAtPath: String, languageCode: String) { let plistBuddyPath = "/usr/libexec/PlistBuddy" if NSFileManager.defaultManager().fileExistsAtPath(plistBuddyPath) { // Delete existing AppleLanguages runTask(plistBuddyPath, [fileAtPath, "-c", "Delete :AppleLanguages"], false) // Set new language code runTask(plistBuddyPath, [fileAtPath, "-c", "Add :AppleLanguages array", "-c", "Add :AppleLanguages:0 string '\(languageCode)'"], false) } else { println("Plist buddy does not exist at \(plistBuddyPath), aborting") exit(1) } } func enumerateSimulatorFoldersAndChangeLanguage(languageCode:String) { var devicesPath = "~/Library/Developer/CoreSimulator/Devices".stringByExpandingTildeInPath var isDir: ObjCBool = false // File exists at the right path if NSFileManager.defaultManager().fileExistsAtPath(devicesPath, isDirectory: &isDir) { // We are a directory if isDir { // Enumarate and find all the .GlobalPreferences.plist files var directoryEnumerator = NSFileManager.defaultManager().enumeratorAtPath(devicesPath) while let file: AnyObject = directoryEnumerator?.nextObject() { let filePath: String = file as String if file.lastPathComponent == ".GlobalPreferences.plist" { // Set language code changeLanguageFor(devicesPath.stringByAppendingPathComponent(filePath), languageCode) } } } else { println("Simulator folder does not exist!") exit(1) } } else { println("Simulator folder does not exist!") exit(1) } } //MARK: Script entry point func main() { if Process.arguments.count != 2 { printUsage() exit(1) } let languageCode = Process.arguments[1] enumerateSimulatorFoldersAndChangeLanguage(languageCode) } main()
mit
5aeb1b5178c5f60370eaac388ac54a49
33.504202
143
0.665124
4.613483
false
false
false
false
ken0nek/swift
stdlib/public/SDK/Foundation/NSError.swift
1
32505
import CoreFoundation import Darwin // NSError and CFError conform to the standard ErrorProtocol protocol. Compiler // magic allows this to be done as a "toll-free" conversion when an NSError // or CFError is used as an ErrorProtocol existential. extension NSError : ErrorProtocol { public var _domain: String { return domain } public var _code: Int { return code } } extension CFError : ErrorProtocol { public var _domain: String { return CFErrorGetDomain(self) as String } public var _code: Int { return CFErrorGetCode(self) } } // An error value to use when an Objective-C API indicates error // but produces a nil error object. public enum _GenericObjCError : ErrorProtocol { case nilError } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectiveCBridgeableErrorProtocol : ErrorProtocol { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// A hook for the runtime to use _ObjectiveCBridgeableErrorProtocol in order to /// attempt an "errorTypeValue as? SomeError" cast. /// /// If the bridge succeeds, the bridged value is written to the uninitialized /// memory pointed to by 'out', and true is returned. Otherwise, 'out' is /// left uninitialized, and false is returned. @_silgen_name("swift_stdlib_bridgeNSErrorToErrorProtocol") public func _stdlib_bridgeNSErrorToErrorProtocol< T : _ObjectiveCBridgeableErrorProtocol >(_ error: NSError, out: UnsafeMutablePointer<T>) -> Bool { if let bridged = T(_bridgedNSError: error) { out.initialize(with: bridged) return true } else { return false } } /// Helper protocol for _BridgedNSError, which used to provide /// default implementations. public protocol __BridgedNSError : RawRepresentable, ErrorProtocol { static var _nsErrorDomain: String { get } } // Allow two bridged NSError types to be compared. public func ==<T: __BridgedNSError where T.RawValue: SignedInteger>( lhs: T, rhs: T ) -> Bool { return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax() } public extension __BridgedNSError where RawValue: SignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(rawValue.toIntMax()) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(IntMax(_bridgedNSError.code))) } public final var hashValue: Int { return _code } } // Allow two bridged NSError types to be compared. public func ==<T: __BridgedNSError where T.RawValue: UnsignedInteger>( lhs: T, rhs: T ) -> Bool { return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax() } public extension __BridgedNSError where RawValue: UnsignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(bitPattern: UInt(rawValue.toUIntMax())) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code)))) } public final var hashValue: Int { return _code } } /// Describes a raw representable type that is bridged to a particular /// NSError domain. /// /// This protocol is used primarily to generate the conformance to /// _ObjectiveCBridgeableErrorProtocol for such an enum. public protocol _BridgedNSError : __BridgedNSError, _ObjectiveCBridgeableErrorProtocol, Hashable { /// The NSError domain to which this type is bridged. static var _nsErrorDomain: String { get } } /// Enumeration that describes the error codes within the Cocoa error /// domain. public struct NSCocoaError : RawRepresentable, _BridgedNSError { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static var _nsErrorDomain: String { return NSCocoaErrorDomain } } public func ~=(match: NSCocoaError, error: ErrorProtocol) -> Bool { guard let cocoaError = error as? NSCocoaError else { return false } return match.rawValue == cocoaError.rawValue } public extension NSCocoaError { public static var fileNoSuchFileError: NSCocoaError { return NSCocoaError(rawValue: 4) } public static var fileLockingError: NSCocoaError { return NSCocoaError(rawValue: 255) } public static var fileReadUnknownError: NSCocoaError { return NSCocoaError(rawValue: 256) } public static var fileReadNoPermissionError: NSCocoaError { return NSCocoaError(rawValue: 257) } public static var fileReadInvalidFileNameError: NSCocoaError { return NSCocoaError(rawValue: 258) } public static var fileReadCorruptFileError: NSCocoaError { return NSCocoaError(rawValue: 259) } public static var fileReadNoSuchFileError: NSCocoaError { return NSCocoaError(rawValue: 260) } public static var fileReadInapplicableStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 261) } public static var fileReadUnsupportedSchemeError: NSCocoaError { return NSCocoaError(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadTooLargeError: NSCocoaError { return NSCocoaError(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadUnknownStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 264) } public static var fileWriteUnknownError: NSCocoaError { return NSCocoaError(rawValue: 512) } public static var fileWriteNoPermissionError: NSCocoaError { return NSCocoaError(rawValue: 513) } public static var fileWriteInvalidFileNameError: NSCocoaError { return NSCocoaError(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) public static var fileWriteFileExistsError: NSCocoaError { return NSCocoaError(rawValue: 516) } public static var fileWriteInapplicableStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 517) } public static var fileWriteUnsupportedSchemeError: NSCocoaError { return NSCocoaError(rawValue: 518) } public static var fileWriteOutOfSpaceError: NSCocoaError { return NSCocoaError(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var fileWriteVolumeReadOnlyError: NSCocoaError { return NSCocoaError(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountUnknownError: NSCocoaError { return NSCocoaError(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountBusyError: NSCocoaError { return NSCocoaError(rawValue: 769) } public static var keyValueValidationError: NSCocoaError { return NSCocoaError(rawValue: 1024) } public static var formattingError: NSCocoaError { return NSCocoaError(rawValue: 2048) } public static var userCancelledError: NSCocoaError { return NSCocoaError(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var featureUnsupportedError: NSCocoaError { return NSCocoaError(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableNotLoadableError: NSCocoaError { return NSCocoaError(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableArchitectureMismatchError: NSCocoaError { return NSCocoaError(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableRuntimeMismatchError: NSCocoaError { return NSCocoaError(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLoadError: NSCocoaError { return NSCocoaError(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLinkError: NSCocoaError { return NSCocoaError(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadCorruptError: NSCocoaError { return NSCocoaError(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadUnknownVersionError: NSCocoaError { return NSCocoaError(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadStreamError: NSCocoaError { return NSCocoaError(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListWriteStreamError: NSCocoaError { return NSCocoaError(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var propertyListWriteInvalidError: NSCocoaError { return NSCocoaError(rawValue: 3852) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInterrupted: NSCocoaError { return NSCocoaError(rawValue: 4097) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInvalid: NSCocoaError { return NSCocoaError(rawValue: 4099) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionReplyInvalid: NSCocoaError { return NSCocoaError(rawValue: 4101) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUnavailableError: NSCocoaError { return NSCocoaError(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileNotUploadedDueToQuotaError: NSCocoaError { return NSCocoaError(rawValue: 4354) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUbiquityServerNotAvailable: NSCocoaError { return NSCocoaError(rawValue: 4355) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffFailedError: NSCocoaError { return NSCocoaError(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityConnectionUnavailableError: NSCocoaError { return NSCocoaError(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityRemoteApplicationTimedOutError: NSCocoaError { return NSCocoaError(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffUserInfoTooLargeError: NSCocoaError { return NSCocoaError(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderReadCorruptError: NSCocoaError { return NSCocoaError(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderValueNotFoundError: NSCocoaError { return NSCocoaError(rawValue: 4865) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public var isCoderError: Bool { return rawValue >= 4864 && rawValue <= 4991 } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public var isExecutableError: Bool { return rawValue >= 3584 && rawValue <= 3839 } public var isFileError: Bool { return rawValue >= 0 && rawValue <= 1023 } public var isFormattingError: Bool { return rawValue >= 2048 && rawValue <= 2559 } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public var isPropertyListError: Bool { return rawValue >= 3840 && rawValue <= 4095 } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public var isUbiquitousFileError: Bool { return rawValue >= 4352 && rawValue <= 4607 } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public var isUserActivityError: Bool { return rawValue >= 4608 && rawValue <= 4863 } public var isValidationError: Bool { return rawValue >= 1024 && rawValue <= 2047 } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public var isXPCConnectionError: Bool { return rawValue >= 4096 && rawValue <= 4224 } } extension NSCocoaError { @available(*, unavailable, renamed: "fileNoSuchFileError") public static var FileNoSuchFileError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileLockingError") public static var FileLockingError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknownError") public static var FileReadUnknownError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoPermissionError") public static var FileReadNoPermissionError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInvalidFileNameError") public static var FileReadInvalidFileNameError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadCorruptFileError") public static var FileReadCorruptFileError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoSuchFileError") public static var FileReadNoSuchFileError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInapplicableStringEncodingError") public static var FileReadInapplicableStringEncodingError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnsupportedSchemeError") public static var FileReadUnsupportedSchemeError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadTooLargeError") public static var FileReadTooLargeError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknownStringEncodingError") public static var FileReadUnknownStringEncodingError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnknownError") public static var FileWriteUnknownError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteNoPermissionError") public static var FileWriteNoPermissionError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInvalidFileNameError") public static var FileWriteInvalidFileNameError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteFileExistsError") public static var FileWriteFileExistsError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInapplicableStringEncodingError") public static var FileWriteInapplicableStringEncodingError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnsupportedSchemeError") public static var FileWriteUnsupportedSchemeError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteOutOfSpaceError") public static var FileWriteOutOfSpaceError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteVolumeReadOnlyError") public static var FileWriteVolumeReadOnlyError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountUnknownError") public static var FileManagerUnmountUnknownError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountBusyError") public static var FileManagerUnmountBusyError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "keyValueValidationError") public static var KeyValueValidationError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "formattingError") public static var FormattingError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelledError") public static var UserCancelledError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "featureUnsupportedError") public static var FeatureUnsupportedError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableNotLoadableError") public static var ExecutableNotLoadableError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableArchitectureMismatchError") public static var ExecutableArchitectureMismatchError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableRuntimeMismatchError") public static var ExecutableRuntimeMismatchError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLoadError") public static var ExecutableLoadError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLinkError") public static var ExecutableLinkError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadCorruptError") public static var PropertyListReadCorruptError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadUnknownVersionError") public static var PropertyListReadUnknownVersionError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadStreamError") public static var PropertyListReadStreamError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteStreamError") public static var PropertyListWriteStreamError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteInvalidError") public static var PropertyListWriteInvalidError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInterrupted") public static var XPCConnectionInterrupted: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInvalid") public static var XPCConnectionInvalid: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionReplyInvalid") public static var XPCConnectionReplyInvalid: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUnavailableError") public static var UbiquitousFileUnavailableError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileNotUploadedDueToQuotaError") public static var UbiquitousFileNotUploadedDueToQuotaError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUbiquityServerNotAvailable") public static var UbiquitousFileUbiquityServerNotAvailable: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffFailedError") public static var UserActivityHandoffFailedError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityConnectionUnavailableError") public static var UserActivityConnectionUnavailableError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityRemoteApplicationTimedOutError") public static var UserActivityRemoteApplicationTimedOutError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffUserInfoTooLargeError") public static var UserActivityHandoffUserInfoTooLargeError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderReadCorruptError") public static var CoderReadCorruptError: NSCocoaError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderValueNotFoundError") public static var CoderValueNotFoundError: NSCocoaError { fatalError("unavailable accessor can't be called") } } /// Enumeration that describes the error codes within the NSURL error /// domain. @objc public enum NSURLError : Int, _BridgedNSError { case unknown = -1 case cancelled = -999 case badURL = -1000 case timedOut = -1001 case unsupportedURL = -1002 case cannotFindHost = -1003 case cannotConnectToHost = -1004 case networkConnectionLost = -1005 case dnsLookupFailed = -1006 case httpTooManyRedirects = -1007 case resourceUnavailable = -1008 case notConnectedToInternet = -1009 case redirectToNonExistentLocation = -1010 case badServerResponse = -1011 case userCancelledAuthentication = -1012 case userAuthenticationRequired = -1013 case zeroByteResource = -1014 case cannotDecodeRawData = -1015 case cannotDecodeContentData = -1016 case cannotParseResponse = -1017 case fileDoesNotExist = -1100 case fileIsDirectory = -1101 case noPermissionsToReadFile = -1102 case secureConnectionFailed = -1200 case serverCertificateHasBadDate = -1201 case serverCertificateUntrusted = -1202 case serverCertificateHasUnknownRoot = -1203 case serverCertificateNotYetValid = -1204 case clientCertificateRejected = -1205 case clientCertificateRequired = -1206 case cannotLoadFromNetwork = -2000 case cannotCreateFile = -3000 case cannotOpenFile = -3001 case cannotCloseFile = -3002 case cannotWriteToFile = -3003 case cannotRemoveFile = -3004 case cannotMoveFile = -3005 case downloadDecodingFailedMidStream = -3006 case downloadDecodingFailedToComplete = -3007 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case internationalRoamingOff = -1018 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case callIsActive = -1019 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case dataNotAllowed = -1020 @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) case requestBodyStreamExhausted = -1021 @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) case backgroundSessionRequiresSharedContainer = -995 @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) case backgroundSessionInUseByAnotherProcess = -996 @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) case backgroundSessionWasDisconnected = -997 public static var _nsErrorDomain: String { return NSURLErrorDomain } } extension NSURLError { @available(*, unavailable, renamed: "unknown") static var Unknown: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cancelled") static var Cancelled: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badURL") static var BadURL: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "timedOut") static var TimedOut: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "unsupportedURL") static var UnsupportedURL: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotFindHost") static var CannotFindHost: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotConnectToHost") static var CannotConnectToHost: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "networkConnectionLost") static var NetworkConnectionLost: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dnsLookupFailed") static var DNSLookupFailed: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "httpTooManyRedirects") static var HTTPTooManyRedirects: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "resourceUnavailable") static var ResourceUnavailable: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "notConnectedToInternet") static var NotConnectedToInternet: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "redirectToNonExistentLocation") static var RedirectToNonExistentLocation: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badServerResponse") static var BadServerResponse: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelledAuthentication") static var UserCancelledAuthentication: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userAuthenticationRequired") static var UserAuthenticationRequired: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "zeroByteResource") static var ZeroByteResource: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeRawData") static var CannotDecodeRawData: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeContentData") static var CannotDecodeContentData: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotParseResponse") static var CannotParseResponse: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileDoesNotExist") static var FileDoesNotExist: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileIsDirectory") static var FileIsDirectory: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "noPermissionsToReadFile") static var NoPermissionsToReadFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "secureConnectionFailed") static var SecureConnectionFailed: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasBadDate") static var ServerCertificateHasBadDate: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateUntrusted") static var ServerCertificateUntrusted: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasUnknownRoot") static var ServerCertificateHasUnknownRoot: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateNotYetValid") static var ServerCertificateNotYetValid: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRejected") static var ClientCertificateRejected: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRequired") static var ClientCertificateRequired: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotLoadFromNetwork") static var CannotLoadFromNetwork: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCreateFile") static var CannotCreateFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotOpenFile") static var CannotOpenFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCloseFile") static var CannotCloseFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotWriteToFile") static var CannotWriteToFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotRemoveFile") static var CannotRemoveFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotMoveFile") static var CannotMoveFile: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedMidStream") static var DownloadDecodingFailedMidStream: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedToComplete") static var DownloadDecodingFailedToComplete: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "internationalRoamingOff") static var InternationalRoamingOff: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "callIsActive") static var CallIsActive: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dataNotAllowed") static var DataNotAllowed: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "requestBodyStreamExhausted") static var RequestBodyStreamExhausted: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionRequiresSharedContainer") static var BackgroundSessionRequiresSharedContainer: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionInUseByAnotherProcess") static var BackgroundSessionInUseByAnotherProcess: NSURLError { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionWasDisconnected") static var BackgroundSessionWasDisconnected: NSURLError { fatalError("unavailable accessor can't be called") } } extension POSIXError : _BridgedNSError { public static var _nsErrorDomain: String { return NSPOSIXErrorDomain } } extension MachError : _BridgedNSError { public static var _nsErrorDomain: String { return NSMachErrorDomain } }
apache-2.0
09c408ea9aa29213f90c95079750c512
33.690502
83
0.751084
4.946736
false
false
false
false
loudnate/LoopKit
Extensions/NSDateFormatter.swift
2
768
// // NSDateFormatter.swift // Naterade // // Created by Nathan Racklyeft on 11/25/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation // MARK: - Extensions useful in parsing fixture dates extension ISO8601DateFormatter { static func localTimeDate(timeZone: TimeZone = .currentFixed) -> Self { let formatter = self.init() formatter.formatOptions = .withInternetDateTime formatter.formatOptions.subtract(.withTimeZone) formatter.timeZone = timeZone return formatter } } extension DateFormatter { static var descriptionFormatter: DateFormatter { let formatter = self.init() formatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ" return formatter } }
mit
47ad012d85e4b747627505bf60075f0c
22.242424
75
0.687093
4.620482
false
false
false
false
kelvin13/maxpng
sources/png/string.swift
2
4662
extension String { static var bold:Self = "\u{1B}[1m" static var reset:Self = "\u{1B}[0m" static func pad(_ string:Self, left count:Int, with fill:Character = " ") -> Self { .init(repeating: fill, count: Swift.max(0, count - string.count)) + string } static func pad(_ string:String, right count:Int, with fill:Character = " ") -> Self { string + .init(repeating: fill, count: Swift.max(0, count - string.count)) } init<F>(_ x:F, places:Int) where F:BinaryFloatingPoint { let p:Int = (0 ..< places).reduce(1){ (a, _) in a * 10 } let i:Int = .init((x * .init(p)).rounded()) let (a, b):(quotient:Int, remainder:Int) = i.quotientAndRemainder(dividingBy: p) let tail:String = "\(b)" self = "\(a).\(String.init(repeating: "0", count: places - tail.count) + tail)" } static func swatch<T>(_ color:(r:T, g:T, b:T, a:T)) -> Self where T:FixedWidthInteger & UnsignedInteger { .swatch(" #\(Self.hex(color.r, color.g, color.b, color.a)) ", color: (color.r, color.g, color.b)) } static func swatch<T>(_ color:(r:T, g:T, b:T)) -> Self where T:FixedWidthInteger & UnsignedInteger { .swatch(" #\(Self.hex(color.r, color.g, color.b)) ", color: color) } static func highlight<F>(_ string:Self, bg:(r:F, g:F, b:F), fg:(r:F, g:F, b:F)? = nil) -> Self where F:BinaryFloatingPoint { // if no foreground color specified, print dark colors with white text // and light colors with black text let fg:(r:F, g:F, b:F) = fg ?? ((bg.r + bg.g + bg.b) / 3 < 0.5 ? (1, 1, 1) : (0, 0, 0)) return "\(Self.bg(bg))\(Self.fg(fg))\(string)\(Self.fg(nil))\(Self.bg(nil))" } static func highlight<T>(_ string:Self, bg:(r:T, g:T, b:T), fg:(r:T, g:T, b:T)? = nil) -> Self where T:FixedWidthInteger & UnsignedInteger { .highlight(string, bg: Self.normalize(color: bg), fg: fg.map(Self.normalize(color:))) } static func color<F>(_ string:Self, fg:(r:F, g:F, b:F)) -> Self where F:BinaryFloatingPoint { "\(Self.fg(fg))\(string)\(Self.fg(nil))" } static func color<T>(_ string:Self, fg:(r:T, g:T, b:T)) -> Self where T:FixedWidthInteger & UnsignedInteger { .color(string, fg: Self.normalize(color: fg)) } private static func fg(_ color:(r:UInt8, g:UInt8, b:UInt8)?) -> Self { if let color:(r:UInt8, g:UInt8, b:UInt8) = color { return "\u{1B}[38;2;\(color.r);\(color.g);\(color.b)m" } else { return "\u{1B}[39m" } } private static func bg(_ color:(r:UInt8, g:UInt8, b:UInt8)?) -> Self { if let color:(r:UInt8, g:UInt8, b:UInt8) = color { return "\u{1B}[48;2;\(color.r);\(color.g);\(color.b)m" } else { return "\u{1B}[49m" } } private static func fg<F>(_ color:(r:F, g:F, b:F)?) -> Self where F:BinaryFloatingPoint { .fg(color.map(Self.quantize(color:))) } private static func bg<F>(_ color:(r:F, g:F, b:F)?) -> Self where F:BinaryFloatingPoint { .bg(color.map(Self.quantize(color:))) } private static func quantize<F>(color:(r:F, g:F, b:F)) -> (r:UInt8, g:UInt8, b:UInt8) where F:BinaryFloatingPoint { let r:UInt8 = .init((.init(UInt8.max) * Swift.max(0, Swift.min(color.r, 1))).rounded()), g:UInt8 = .init((.init(UInt8.max) * Swift.max(0, Swift.min(color.g, 1))).rounded()), b:UInt8 = .init((.init(UInt8.max) * Swift.max(0, Swift.min(color.b, 1))).rounded()) return (r, g, b) } private static func normalize<T>(color:(r:T, g:T, b:T)) -> (r:Double, g:Double, b:Double) where T:FixedWidthInteger & UnsignedInteger { let r:Double = .init(color.r) / .init(T.max), g:Double = .init(color.g) / .init(T.max), b:Double = .init(color.b) / .init(T.max) return (r, g, b) } private static func hex<T>(_ components:T...) -> Self where T:FixedWidthInteger & UnsignedInteger { "\(components.map{ Self.pad(.init($0, radix: 16), left: T.bitWidth / 4, with: "0") }.joined())" } private static func swatch<T>(_ description:Self, color:(r:T, g:T, b:T)) -> Self where T:FixedWidthInteger & UnsignedInteger { .highlight(description, bg: color) } }
gpl-3.0
9cf6a2f097dd2041791f0b9f8ce67f97
32.3
103
0.522523
3.190965
false
false
false
false
logansease/ZoomyHeader
ZoomyHeader/Classes/ZoomyHeaderCell.swift
1
2136
// // ImageCell.swift // WhereToGo // // Created by lsease on 4/28/16. // Copyright © 2016 Logan Sease. All rights reserved. // import UIKit open class ZoomyHeaderCell : UITableViewCell, UIScrollViewDelegate { @IBOutlet open var fullImageView: UIImageView! @IBOutlet var scrollView : UIScrollView! open var originalHeight : CGFloat = 150 override open func awakeFromNib() { super.awakeFromNib() // Initialization code fullImageView.autoresizingMask = .flexibleHeight } override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } //this method will be called by our scroll view to tell it to zoom on the images open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return fullImageView } //this should be called by our view controller when the tableview scrolls open func didScroll(_ tableView : UITableView!) { var frame = scrollView.frame; frame.size.height = max((originalHeight - tableView.contentOffset.y),0); frame.origin.y = tableView.contentOffset.y; scrollView.frame = frame; scrollView.zoomScale = 1 + (abs(min(tableView.contentOffset.y,0))/320.0); } open class func registerZoomyCellIdentifier(_ tableView: UITableView!, identifier : String! = "ZoomyHeaderCell") { let podBundle = Bundle(for: self) if let bundleURL = podBundle.url(forResource: "ZoomyHeader", withExtension: "bundle") { if let bundle = Bundle(url: bundleURL) { let cellNib = UINib(nibName: "ZoomyHeaderCell", bundle: bundle) tableView.register(cellNib, forCellReuseIdentifier: identifier) }else { assertionFailure("Could not load the bundle") } }else { assertionFailure("Could not create a path to the bundle") } } }
mit
db263f8868d001cb40decfe5bc81e5a0
31.348485
116
0.616393
5.059242
false
false
false
false
Kruks/FindViewControl
FindViewControl/FindViewControl/ObjectClasses/FindGISReqResponse/Request/GISAddressSearchRequest.swift
1
2449
// // GISAddressSearchRequest.swift // // Create by Krutika Mac Mini on 2/8/2016 // Copyright © 2016. All rights reserved. // Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class GISAddressSearchRequest: NSObject { var address: String! var requestType: String! var latitude: Float! var longitude: Float! override init() { } /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary) { address = dictionary["address"] as? String requestType = dictionary["requestType"] as? String latitude = dictionary["latitude"] as? Float longitude = dictionary["longitude"] as? Float } /** * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() if address != nil { dictionary["address"] = address } if requestType != nil { dictionary["requestType"] = requestType } if latitude != nil { dictionary["latitude"] = latitude } if longitude != nil { dictionary["longitude"] = longitude } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { address = aDecoder.decodeObject(forKey: "address") as? String requestType = aDecoder.decodeObject(forKey: "requestType") as? String latitude = aDecoder.decodeObject(forKey: "latitude") as? Float longitude = aDecoder.decodeObject(forKey: "longitude") as? Float } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encodeWithCoder(aCoder: NSCoder) { if address != nil { aCoder.encode(address, forKey: "address") } if requestType != nil { aCoder.encode(requestType, forKey: "requestType") } if latitude != nil { aCoder.encode(latitude, forKey: "latitude") } if longitude != nil { aCoder.encode(longitude, forKey: "longitude") } } }
mit
54973c1fb8115148db093dcc55ad2eed
26.2
180
0.620507
4.945455
false
false
false
false
Ftkey/LTModalViewController
Sources/Animators/ActionSheetTransitionAnimator.swift
1
2720
// // ActionSheetTransitionAnimator.swift // ModalViewController // // Created by Futao on 16/6/21. // // import Foundation import UIKit @objc(LTActionSheetTransitionAnimator) open class ActionSheetTransitionAnimator: NSObject { @objc open static var presentAnimator:TransitionAnimator { return TransitionAnimator(duration: 0.25, animations: { transitionContext in guard let contextController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } guard let modalVc = contextController as? ModalViewController else { return } let containerView = transitionContext.containerView containerView.addSubview(modalVc.view) modalVc.overlayView.alpha = 0; modalVc.rootController.view.frame = CGRect(x: (modalVc.view.frame.width-modalVc.presentedViewSize.width)/2, y: modalVc.view.frame.height, width: modalVc.presentedViewSize.width, height: modalVc.presentedViewSize.height) UIView.animate(withDuration: 0.25, animations: { modalVc.overlayView.alpha = 0.4 modalVc.rootController.view.frame = CGRect(x: (modalVc.view.frame.width-modalVc.presentedViewSize.width)/2, y: (modalVc.view.frame.height-modalVc.presentedViewSize.height) - modalVc.presentContentInset, width: modalVc.presentedViewSize.width, height: modalVc.presentedViewSize.height) }, completion: { (finished) in transitionContext.completeTransition(finished) }) }) { transitionCompleted in } } @objc open static var dismissAnimator:TransitionAnimator { return TransitionAnimator(duration: 0.25, animations: { transitionContext in guard let contextController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } guard let modalVc = contextController as? ModalViewController else { return } UIView.animate(withDuration: 0.25, animations: { modalVc.overlayView.alpha = 0 modalVc.rootController.view.frame = CGRect(x: (modalVc.view.frame.width-modalVc.presentedViewSize.width)/2, y: modalVc.view.frame.height, width: modalVc.presentedViewSize.width, height: modalVc.presentedViewSize.height) }, completion: { (finished) in transitionContext.completeTransition(finished) }) }) { transitionCompleted in } } }
mit
34876906ee7ee2ddd8387abba46e377c
42.174603
300
0.644853
5.506073
false
false
false
false
OneupNetwork/SQRichTextEditor
Example/SQRichTextEditor/EFColorPicker/EFColorSelectionView.swift
1
4791
// // EFColorSelectionView.swift // EFColorPicker // // Created by EyreFree on 2017/9/29. // // Copyright (c) 2017 EyreFree <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // The enum to define the EFColorView's types. public enum EFSelectedColorView: Int { // The RGB color view type. case RGB = 0 // The HSB color view type. case HSB = 1 } // The EFColorSelectionView aggregates views that should be used to edit color components. public class EFColorSelectionView: UIView, EFColorView, EFColorViewDelegate { // The selected color view private(set) var selectedIndex: EFSelectedColorView = EFSelectedColorView.RGB let rgbColorView: EFRGBView = EFRGBView() let hsbColorView: EFHSBView = EFHSBView() weak public var delegate: EFColorViewDelegate? public var color: UIColor = UIColor.white { didSet { self.selectedView()?.color = color } } override init(frame: CGRect) { super.init(frame: frame) self.ef_init() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.ef_init() } // Makes a color component view (rgb or hsb) visible according to the index. // @param index This index define a view to show. // @param animated If YES, the view is being appeared using an animation. func setSelectedIndex(index: EFSelectedColorView, animated: Bool) { self.selectedIndex = index self.selectedView()?.color = self.color UIView.animate(withDuration: animated ? 0.5 : 0.0) { [weak self] in if let strongSelf = self { strongSelf.rgbColorView.alpha = EFSelectedColorView.RGB == index ? 1.0 : 0.0 strongSelf.hsbColorView.alpha = EFSelectedColorView.HSB == index ? 1.0 : 0.0 } } } func selectedView() -> EFColorView? { return (EFSelectedColorView.RGB == self.selectedIndex ? self.rgbColorView : self.hsbColorView) as? EFColorView } func addColorView(view: EFColorView) { view.delegate = self if let view = view as? UIView { self.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let views = [ "view" : view ] let visualFormats = [ "H:|[view]|", "V:|[view]|" ] for visualFormat in visualFormats { self.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: visualFormat, options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views ) ) } } } override public func updateConstraints() { self.rgbColorView.setNeedsUpdateConstraints() self.hsbColorView.setNeedsUpdateConstraints() super.updateConstraints() } // MARK:- FBColorViewDelegate methods public func colorView(_ colorView: EFColorView, didChangeColor color: UIColor) { self.color = color self.delegate?.colorView(self, didChangeColor: self.color) } // MARK:- Private private func ef_init() { if #available(iOS 11.0, *) { self.accessibilityIgnoresInvertColors = true } self.accessibilityLabel = "color_selection_view" self.backgroundColor = UIColor.white self.addColorView(view: rgbColorView) self.addColorView(view: hsbColorView) self.setSelectedIndex(index: EFSelectedColorView.RGB, animated: false) } }
mit
267065a63949200e6d798afbf0b828ce
34.753731
118
0.643707
4.767164
false
false
false
false
gribozavr/swift
stdlib/public/Darwin/Foundation/Data.swift
1
127483
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc @inlinable // This is @inlinable as trivially computable. fileprivate func malloc_good_size(_ size: Int) -> Int { return size } #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif // Underlying storage representation for medium and large data. // Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial. // NOTE: older overlays called this class _DataStorage. The two must // coexist without a conflicting ObjC class name, so it was renamed. // The old name must not be used in the new runtime. @usableFromInline internal final class __DataStorage { @usableFromInline static let maxSize = Int.max >> 1 @usableFromInline static let vmOpsThreshold = NSPageSize() * 4 @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _offset: Int @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _needToZero: Bool @inlinable // This is @inlinable as trivially computable. var bytes: UnsafeRawPointer? { return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable as trivially computable. var mutableBytes: UnsafeMutableRawPointer? { return _bytes?.advanced(by: -_offset) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return _capacity } @inlinable // This is @inlinable as trivially computable. var length: Int { get { return _length } set { setLength(newValue) } } @inlinable // This is inlinable as trivially computable. var isExternallyOwned: Bool { // all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation // anything with 0 capacity means that we have not allocated this pointer and concequently mutation is not ours to make. return _capacity == 0 } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) { guard isExternallyOwned || newLength > _capacity else { return } if newLength == 0 { if isExternallyOwned { let newCapacity = malloc_good_size(_length) let newBytes = __DataStorage.allocate(newCapacity, false) __DataStorage.move(newBytes!, _bytes!, _length) _freeBytes() _bytes = newBytes _capacity = newCapacity _needToZero = false } } else if isExternallyOwned { let newCapacity = malloc_good_size(newLength) let newBytes = __DataStorage.allocate(newCapacity, clear) if let bytes = _bytes { __DataStorage.move(newBytes!, bytes, _length) } _freeBytes() _bytes = newBytes _capacity = newCapacity _length = newLength _needToZero = true } else { let cap = _capacity var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity)) let origLength = _length var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = __DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength) newBytes = __DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = malloc_good_size(newLength) allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } _deallocator = nil } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv) } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func setLength(_ length: Int) { let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength __DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func get(_ index: Int) -> UInt8 { return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func set(_ index: Int, to value: UInt8) { ensureUniqueBufferReference() _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)) UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer) } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength let shift = resultingLength - currentLength let mutableBytes: UnsafeMutableRawPointer if resultingLength > currentLength { ensureUniqueBufferReference(growingTo: resultingLength) _length = resultingLength } else { ensureUniqueBufferReference() } mutableBytes = _bytes! /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes + start, replacementBytes, replacementLength) } else { memset(mutableBytes + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func resetBytes(in range_: Range<Int>) { let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound) if range.length == 0 { return } if _length < range.location + range.length { let newLength = range.location + range.length if _capacity <= newLength { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength } else { ensureUniqueBufferReference() } memset(_bytes!.advanced(by: range.location), 0, range.length) } @usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer. init(length: Int) { precondition(length < __DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = __DataStorage.shouldAllocateCleared(length) _bytes = __DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline // This is not @inlinable as a non-convience initializer. init(capacity capacity_: Int = 0) { var capacity = capacity_ precondition(capacity < __DataStorage.maxSize) if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline // This is not @inlinable as a non-convience initializer. init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < __DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < __DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _deallocator = { _, _ in _fixLifetime(immutableReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _deallocator = { _, _ in _fixLifetime(mutableReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(customReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: customReference.bytes) _capacity = 0 _needToZero = false _length = customReference.length _deallocator = { _, _ in _fixLifetime(customReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = customMutableReference.mutableBytes _capacity = 0 _needToZero = false _length = customMutableReference.length _deallocator = { _, _ in _fixLifetime(customMutableReference) } } deinit { _freeBytes() } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func mutableCopy(_ range: Range<Int>) -> __DataStorage { return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed. func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false)) } @inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients. @usableFromInline func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } return __NSSwiftData(backing: self, range: range) } } // NOTE: older overlays called this _NSSwiftData. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. internal class __NSSwiftData : NSData { var _backing: __DataStorage! var _range: Range<Data.Index>! convenience init(backing: __DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } @objc override var length: Int { return _range.upperBound - _range.lowerBound } @objc override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } @objc override func copy(with zone: NSZone? = nil) -> Any { return self } @objc override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } @frozen public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> // A small inline buffer of bytes suitable for stack-allocation of small data. // Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible. @usableFromInline @frozen internal struct InlineData { #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #elseif arch(i386) || arch(arm) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #endif @usableFromInline var length: UInt8 @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count <= MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as a convenience initializer. init(_ srcBuffer: UnsafeRawBufferPointer) { self.init(count: srcBuffer.count) if !srcBuffer.isEmpty { Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count) } } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int = 0) { assert(count <= MemoryLayout<Buffer>.size) #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #elseif arch(i386) || arch(arm) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #endif length = UInt8(count) } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: InlineSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: LargeSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(length) } set(newValue) { assert(newValue <= MemoryLayout<Buffer>.size) length = UInt8(newValue) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return 0 } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return count } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as tribially computable. mutating func append(byte: UInt8) { let count = self.count assert(count + 1 <= MemoryLayout<Buffer>.size) Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte } self.length += 1 } @inlinable // This is @inlinable as trivially computable. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { guard !buffer.isEmpty else { return } assert(count + buffer.count <= MemoryLayout<Buffer>.size) let cnt = count _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count) } length += UInt8(buffer.count) } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in return rawBuffer[index] } } set(newValue) { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer[index] = newValue } } } @inlinable // This is @inlinable as trivially computable. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound <= MemoryLayout<Buffer>.size) assert(range.upperBound <= MemoryLayout<Buffer>.size) precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)") if count < range.upperBound { count = range.upperBound } let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in memset(rawBuffer.baseAddress?.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) { assert(subrange.lowerBound <= MemoryLayout<Buffer>.size) assert(subrange.upperBound <= MemoryLayout<Buffer>.size) assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size) precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)") precondition(subrange.upperBound <= length, "index \(subrange.upperBound) is out of bounds of 0..<\(length)") let currentLength = count let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength let shift = resultingLength - currentLength Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in /* shift the trailing bytes */ let start = subrange.lowerBound let length = subrange.upperBound - subrange.lowerBound if shift != 0 { memmove(mutableBytes.baseAddress?.advanced(by: start + replacementLength), mutableBytes.baseAddress?.advanced(by: start + length), currentLength - start - length) } if replacementLength != 0 { memmove(mutableBytes.baseAddress?.advanced(by: start), replacementBytes!, replacementLength) } } count = resultingLength } @inlinable // This is @inlinable as trivially computable. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") Swift.withUnsafeBytes(of: bytes) { let cnt = Swift.min($0.count, range.upperBound - range.lowerBound) guard cnt > 0 else { return } pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt) } } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { // **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8) // Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash. // // This affects slices, which are InlineSlice and not InlineData: // // let d = Data([0xFF, 0xFF]) // InlineData // let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice // assert(s == d) // assert(s.hashValue == d.hashValue) hasher.combine(count) Swift.withUnsafeBytes(of: bytes) { // We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage). let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count) hasher.combine(bytes: bytes) } } } #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline internal typealias HalfInt = Int32 #elseif arch(i386) || arch(arm) @usableFromInline internal typealias HalfInt = Int16 #endif // A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @frozen internal struct InlineSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: Range<HalfInt> @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count < HalfInt.max } @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { assert(buffer.count < HalfInt.max) self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { assert(capacity < HalfInt.max) self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { assert(count < HalfInt.max) self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { assert(inline.count < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice) { assert(large.range.lowerBound < HalfInt.max) assert(large.range.upperBound < HalfInt.max) self.init(large.storage, range: large.range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(large.storage, range: range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { assert(count < HalfInt.max) self.storage = storage slice = 0..<HalfInt(count) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.storage = storage slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(self.range) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return Int(slice.lowerBound) } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return Int(slice.upperBound) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(slice.upperBound - slice.lowerBound) } set(newValue) { assert(newValue < HalfInt.max) ensureUniqueReference() storage.length = newValue slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue)) } } @inlinable // This is @inlinable as trivially computable. var range: Range<Int> { get { return Int(slice.lowerBound)..<Int(slice.upperBound) } set(newValue) { assert(newValue.lowerBound < HalfInt.max) assert(newValue.upperBound < HalfInt.max) slice = HalfInt(newValue.lowerBound)..<HalfInt(newValue.upperBound) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { assert(endIndex + buffer.count < HalfInt.max) ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count) } @inlinable // This is @inlinable as reasonably small. subscript(index: Index) -> UInt8 { get { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.upperBound < range.upperBound { slice = slice.lowerBound..<HalfInt(range.upperBound) } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice = slice.lowerBound..<HalfInt(resultingUpper) } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // At most, hash the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word. // Inlinability strategy: everything should be inlinable as trivial. @usableFromInline @_fixed_layout internal final class RangeReference { @usableFromInline var range: Range<Int> @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var lowerBound: Int { return range.lowerBound } @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var upperBound: Int { return range.upperBound } @inlinable @inline(__always) // This is @inlinable as trivially computable. var count: Int { return range.upperBound - range.lowerBound } @inlinable @inline(__always) // This is @inlinable as a trivial initializer. init(_ range: Range<Int>) { self.range = range } } // A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @frozen internal struct LargeSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: RangeReference @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) } self.init(storage, count: inline.count) } @inlinable // This is @inlinable as a trivial initializer. init(_ slice: InlineSlice) { self.storage = slice.storage self.slice = RangeReference(slice.range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { self.storage = storage self.slice = RangeReference(0..<count) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(range) } if !isKnownUniquelyReferenced(&slice) { slice = RangeReference(range) } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { return slice.range.lowerBound } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { return slice.range.upperBound } @inlinable // This is @inlinable as trivially forwarding. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable. mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return slice.count } set(newValue) { ensureUniqueReference() storage.length = newValue slice.range = slice.range.lowerBound..<(slice.range.lowerBound + newValue) } } @inlinable // This is @inlinable as it is trivially forwarding. var range: Range<Int> { return slice.range } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Int>) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.range.upperBound < range.upperBound { slice.range = slice.range.lowerBound..<range.upperBound } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice.range = slice.range.lowerBound..<resultingUpper } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // Hash at most the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // The actual storage for Data's various representations. // Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.) @usableFromInline @frozen internal enum _Representation { case empty case inline(InlineData) case slice(InlineSlice) case large(LargeSlice) @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer) { if buffer.isEmpty { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else if InlineSlice.canStore(count: buffer.count) { self = .slice(InlineSlice(buffer)) } else { self = .large(LargeSlice(buffer)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) { if buffer.isEmpty { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else { let count = buffer.count let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in _fixLifetime(owner) }, offset: 0) if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } } @inlinable // This is @inlinable as a trivial initializer. init(capacity: Int) { if capacity == 0 { self = .empty } else if InlineData.canStore(count: capacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: capacity) { self = .slice(InlineSlice(capacity: capacity)) } else { self = .large(LargeSlice(capacity: capacity)) } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(InlineData(count: count)) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(count: count)) } else { self = .large(LargeSlice(count: count)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(storage.withUnsafeBytes(in: 0..<count) { InlineData($0) }) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func reserveCapacity(_ minimumCapacity: Int) { guard minimumCapacity > 0 else { return } switch self { case .empty: if InlineData.canStore(count: minimumCapacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: minimumCapacity) { self = .slice(InlineSlice(capacity: minimumCapacity)) } else { self = .large(LargeSlice(capacity: minimumCapacity)) } case .inline(let inline): guard minimumCapacity > inline.capacity else { return } // we know we are going to be heap promoted if InlineSlice.canStore(count: minimumCapacity) { var slice = InlineSlice(inline) slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.reserveCapacity(minimumCapacity) self = .large(slice) } case .slice(var slice): guard minimumCapacity > slice.capacity else { return } if InlineSlice.canStore(count: minimumCapacity) { self = .empty slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var large = LargeSlice(slice) large.reserveCapacity(minimumCapacity) self = .large(large) } case .large(var slice): guard minimumCapacity > slice.capacity else { return } self = .empty slice.reserveCapacity(minimumCapacity) self = .large(slice) } } @inlinable // This is @inlinable as reasonably small. var count: Int { get { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.count case .large(let slice): return slice.count } } set(newValue) { // HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee. // This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame. @inline(__always) func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? { switch representation { case .empty: if newValue == 0 { return nil } else if InlineData.canStore(count: newValue) { return .inline(InlineData(count: newValue)) } else if InlineSlice.canStore(count: newValue) { return .slice(InlineSlice(count: newValue)) } else { return .large(LargeSlice(count: newValue)) } case .inline(var inline): if newValue == 0 { return .empty } else if InlineData.canStore(count: newValue) { guard inline.count != newValue else { return nil } inline.count = newValue return .inline(inline) } else if InlineSlice.canStore(count: newValue) { var slice = InlineSlice(inline) slice.count = newValue return .slice(slice) } else { var slice = LargeSlice(inline) slice.count = newValue return .large(slice) } case .slice(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else if InlineSlice.canStore(count: newValue + slice.startIndex) { guard slice.count != newValue else { return nil } representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .slice(slice) } else { var newSlice = LargeSlice(slice) newSlice.count = newValue return .large(newSlice) } case .large(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else { guard slice.count != newValue else { return nil} representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .large(slice) } } } if let rep = apply(&self, newValue) { self = rep } } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: let empty = InlineData() return try empty.withUnsafeBytes(apply) case .inline(let inline): return try inline.withUnsafeBytes(apply) case .slice(let slice): return try slice.withUnsafeBytes(apply) case .large(let slice): return try slice.withUnsafeBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: var empty = InlineData() return try empty.withUnsafeMutableBytes(apply) case .inline(var inline): defer { self = .inline(inline) } return try inline.withUnsafeMutableBytes(apply) case .slice(var slice): self = .empty defer { self = .slice(slice) } return try slice.withUnsafeMutableBytes(apply) case .large(var slice): self = .empty defer { self = .large(slice) } return try slice.withUnsafeMutableBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T { switch self { case .empty: return try work(NSData()) case .inline(let inline): return try inline.withUnsafeBytes { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress ?? UnsafeRawPointer(bitPattern: 0xBAD0)!), length: $0.count, freeWhenDone: false)) } case .slice(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) case .large(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { switch self { case .empty: var stop = false block(UnsafeBufferPointer<UInt8>(start: nil, count: 0), 0, &stop) case .inline(let inline): inline.withUnsafeBytes { var stop = false block(UnsafeBufferPointer<UInt8>(start: $0.baseAddress?.assumingMemoryBound(to: UInt8.self), count: $0.count), 0, &stop) } case .slice(let slice): slice.storage.enumerateBytes(in: slice.range, block) case .large(let slice): slice.storage.enumerateBytes(in: slice.range, block) } } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { switch self { case .empty: self = _Representation(buffer) case .inline(var inline): if InlineData.canStore(count: inline.count + buffer.count) { inline.append(contentsOf: buffer) self = .inline(inline) } else if InlineSlice.canStore(count: inline.count + buffer.count) { var newSlice = InlineSlice(inline) newSlice.append(contentsOf: buffer) self = .slice(newSlice) } else { var newSlice = LargeSlice(inline) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .slice(var slice): if InlineSlice.canStore(count: slice.range.upperBound + buffer.count) { self = .empty defer { self = .slice(slice) } slice.append(contentsOf: buffer) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .large(var slice): self = .empty defer { self = .large(slice) } slice.append(contentsOf: buffer) } } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { switch self { case .empty: if range.upperBound == 0 { self = .empty } else if InlineData.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .inline(InlineData(count: range.upperBound)) } else if InlineSlice.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .slice(InlineSlice(count: range.upperBound)) } else { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .large(LargeSlice(count: range.upperBound)) } case .inline(var inline): if inline.count < range.upperBound { if InlineSlice.canStore(count: range.upperBound) { var slice = InlineSlice(inline) slice.resetBytes(in: range) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.resetBytes(in: range) self = .large(slice) } } else { inline.resetBytes(in: range) self = .inline(inline) } case .slice(var slice): if InlineSlice.canStore(count: range.upperBound) { self = .empty slice.resetBytes(in: range) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.resetBytes(in: range) self = .large(newSlice) } case .large(var slice): self = .empty slice.resetBytes(in: range) self = .large(slice) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { switch self { case .empty: precondition(subrange.lowerBound == 0 && subrange.upperBound == 0, "range \(subrange) out of bounds of 0..<0") if cnt == 0 { return } else if InlineData.canStore(count: cnt) { self = .inline(InlineData(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else if InlineSlice.canStore(count: cnt) { self = .slice(InlineSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else { self = .large(LargeSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } case .inline(var inline): let resultingCount = inline.count + cnt - (subrange.upperBound - subrange.lowerBound) if resultingCount == 0 { self = .empty } else if InlineData.canStore(count: resultingCount) { inline.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(inline) } else if InlineSlice.canStore(count: resultingCount) { var slice = InlineSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } case .slice(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(InlineData(slice, count: slice.count)) } else if InlineSlice.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(newSlice) } case .large(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { var inline = InlineData(count: resultingUpper) inline.withUnsafeMutableBytes { inlineBuffer in if cnt > 0 { inlineBuffer.baseAddress?.advanced(by: subrange.lowerBound).copyMemory(from: bytes!, byteCount: cnt) } slice.withUnsafeBytes { buffer in if subrange.lowerBound > 0 { inlineBuffer.baseAddress?.copyMemory(from: buffer.baseAddress!, byteCount: subrange.lowerBound) } if subrange.upperBound < resultingUpper { inlineBuffer.baseAddress?.advanced(by: subrange.upperBound).copyMemory(from: buffer.baseAddress!.advanced(by: subrange.upperBound), byteCount: resultingUpper - subrange.upperBound) } } } self = .inline(inline) } else if InlineSlice.canStore(count: slice.startIndex) && InlineSlice.canStore(count: resultingUpper) { self = .empty var newSlice = InlineSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(newSlice) } else { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } } } @inlinable // This is @inlinable as trivially forwarding. subscript(index: Index) -> UInt8 { get { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(let inline): return inline[index] case .slice(let slice): return slice[index] case .large(let slice): return slice[index] } } set(newValue) { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(var inline): inline[index] = newValue self = .inline(inline) case .slice(var slice): self = .empty slice[index] = newValue self = .slice(slice) case .large(var slice): self = .empty slice[index] = newValue self = .large(slice) } } } @inlinable // This is @inlinable as reasonably small. subscript(bounds: Range<Index>) -> Data { get { switch self { case .empty: precondition(bounds.lowerBound == 0 && (bounds.upperBound - bounds.lowerBound) == 0, "Range \(bounds) out of bounds 0..<0") return Data() case .inline(let inline): precondition(bounds.upperBound <= inline.count, "Range \(bounds) out of bounds 0..<\(inline.count)") if bounds.lowerBound == 0 { var newInline = inline newInline.count = bounds.upperBound return Data(representation: .inline(newInline)) } else { return Data(representation: .slice(InlineSlice(inline, range: bounds))) } case .slice(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.count) { return Data(representation: .inline(InlineData(slice, count: bounds.count))) } else { var newSlice = slice newSlice.range = bounds return Data(representation: .slice(newSlice)) } case .large(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.upperBound) { return Data(representation: .inline(InlineData(slice, count: bounds.upperBound))) } else if InlineSlice.canStore(count: bounds.lowerBound) && InlineSlice.canStore(count: bounds.upperBound) { return Data(representation: .slice(InlineSlice(slice, range: bounds))) } else { var newSlice = slice newSlice.slice = RangeReference(bounds) return Data(representation: .large(newSlice)) } } } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { switch self { case .empty: return 0 case .inline: return 0 case .slice(let slice): return slice.startIndex case .large(let slice): return slice.startIndex } } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.endIndex case .large(let slice): return slice.endIndex } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { switch self { case .empty: return NSData() case .inline(let inline): return inline.withUnsafeBytes { return NSData(bytes: $0.baseAddress, length: $0.count) } case .slice(let slice): return slice.bridgedReference() case .large(let slice): return slice.bridgedReference() } } @inlinable // This is @inlinable as trivially forwarding. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { switch self { case .empty: precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) out of bounds 0..<0") return case .inline(let inline): inline.copyBytes(to: pointer, from: range) case .slice(let slice): slice.copyBytes(to: pointer, from: range) case .large(let slice): slice.copyBytes(to: pointer, from: range) } } @inline(__always) // This should always be inlined into Data.hash(into:). func hash(into hasher: inout Hasher) { switch self { case .empty: hasher.combine(0) case .inline(let inline): inline.hash(into: &hasher) case .slice(let slice): slice.hash(into: &hasher) case .large(let large): large.hash(into: &hasher) } } } @usableFromInline internal var _representation: _Representation // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) @usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. @inlinable // This is @inlinable as a trivial initializer. public init(bytes: UnsafeRawPointer, count: Int) { _representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue @inlinable // This is @inlinable as a convenience initializer. public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in memset(buffer.baseAddress, Int32(repeatedValue), buffer.count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. @inlinable // This is @inlinable as a trivial initializer. public init(capacity: Int) { _representation = _Representation(capacity: capacity) } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. @inlinable // This is @inlinable as a trivial initializer. public init(count: Int) { _representation = _Representation(count: count) } /// Initialize an empty `Data`. @inlinable // This is @inlinable as a trivial initializer. public init() { _representation = .empty } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. @inlinable // This is @inlinable as a trivial initializer. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator if count == 0 { deallocator._deallocator(bytes, count) _representation = .empty } else { _representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count) } } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. @inlinable // This is @inlinable as a convenience initializer. public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) self.init(referencing: d) } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { self.init(referencing: d) } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { self.init(referencing: d) } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: __shared NSData) { // This is not marked as inline because _providesConcreteBacking would need to be marked as usable from inline however that is a dynamic lookup in objc contexts. let length = reference.length if length == 0 { _representation = .empty } else { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length) } else { _representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length) } } } // slightly faster paths for common sequences @inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer. public init<S: Sequence>(_ elements: S) where S.Element == UInt8 { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { _representation = contiguous.withUnsafeBytes { return _Representation($0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. let representation = elements.withContiguousStorageIfAvailable { return _Representation(UnsafeRawBufferPointer($0)) } if let representation = representation { _representation = representation } else { // Dummy assignment so we can capture below. _representation = _Representation(capacity: 0) // Copy as much as we can in one shot from the sequence. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in // In order to copy from the sequence, we have to bind the buffer to UInt8. // This is safe since we'll copy out of this buffer as raw memory later. let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of buffer... _representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } } @available(swift, introduced: 4.2) @available(swift, deprecated: 5, message: "use `init(_:)` instead") public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @available(swift, obsoleted: 4.2) public init(bytes: Array<UInt8>) { self.init(bytes) } @available(swift, obsoleted: 4.2) public init(bytes: ArraySlice<UInt8>) { self.init(bytes) } @inlinable // This is @inlinable as a trivial initializer. internal init(representation: _Representation) { _representation = representation } // ----------------------------------- // MARK: - Properties and Functions @inlinable // This is @inlinable as trivially forwarding. public mutating func reserveCapacity(_ minimumCapacity: Int) { _representation.reserveCapacity(minimumCapacity) } /// The number of bytes in the data. @inlinable // This is @inlinable as trivially forwarding. public var count: Int { get { return _representation.count } set(newValue) { precondition(newValue >= 0, "count must not be negative") _representation.count = newValue } } @inlinable // This is @inlinable as trivially computable. public var regions: CollectionOfOne<Data> { return CollectionOfOne(self) } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead") public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes(body) } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeMutableBytes<R>(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead") public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes(body) } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count)) } @inlinable // This is @inlinable as trivially forwarding. internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { if range.isEmpty { return } _representation.copyBytes(to: pointer, from: range) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: range) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. @inlinable // This is @inlinable as generic and reasonably small. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.upperBound - copyRange.lowerBound } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { // this should not be marked as inline since in objc contexts we correct atomicity via _shouldUseNonAtomicWriteReimplementation try _representation.withInteriorPointerReference { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _representation.withInteriorPointerReference { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. @available(swift, deprecated: 5, message: "use `regions` or `for-in` instead") public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _representation.enumerateBytes(block) } @inlinable // This is @inlinable as a generic, trivially forwarding function. internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } _representation.append(contentsOf: UnsafeRawBufferPointer(buffer)) } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { guard !other.isEmpty else { return } other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.append(contentsOf: buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } @inlinable // This is @inlinable as trivially forwarding. public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial. public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { contiguous.withUnsafeBytes { _representation.append(contentsOf: $0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. var appended = false elements.withContiguousStorageIfAvailable { _representation.append(contentsOf: UnsafeRawBufferPointer($0)) appended = true } guard !appended else { return } // The sequence is really not contiguous. // Copy as much as we can in one shot. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in // In order to copy from the sequence, we have to bind the temporary buffer to `UInt8`. // This is safe since we're the only owners of the buffer and we copy out as raw memory below anyway. let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of the buffer... _representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. @inlinable // This is @inlinable as trivially forwarding. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") _representation.resetBytes(in: range) } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. @inlinable // This is @inlinable as generic and reasonably small. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { let totalCount = Int(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _representation.replaceSubrange(subrange, with: bytes, count: cnt) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { if isEmpty || range.upperBound - range.lowerBound == 0 { return Data() } let slice = self[range] return slice.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> Data in return Data(bytes: buffer.baseAddress!, count: buffer.count) } } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. @inlinable // This is @inlinable as trivially forwarding. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _representation.withInteriorPointerReference { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. @inlinable // This is @inlinable as trivially forwarding. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _representation.withInteriorPointerReference { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. @inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together. public func hash(into hasher: inout Hasher) { _representation.hash(into: &hasher) } public func advanced(by amount: Int) -> Data { let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in return Data(bytes: ptr.baseAddress!.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. @inlinable // This is @inlinable as trivially forwarding. public subscript(index: Index) -> UInt8 { get { return _representation[index] } set(newValue) { _representation[index] = newValue } } @inlinable // This is @inlinable as trivially forwarding. public subscript(bounds: Range<Index>) -> Data { get { return _representation[bounds] } set { replaceSubrange(bounds, with: newValue) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger { get { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end return _representation[r] } set { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. @inlinable // This is @inlinable as trivially forwarding. public var startIndex: Index { get { return _representation.startIndex } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. @inlinable // This is @inlinable as trivially forwarding. public var endIndex: Index { get { return _representation.endIndex } } @inlinable // This is @inlinable as trivially computable. public func index(before i: Index) -> Index { return i - 1 } @inlinable // This is @inlinable as trivially computable. public func index(after i: Index) -> Index { return i + 1 } @inlinable // This is @inlinable as trivially computable. public var indices: Range<Int> { get { return startIndex..<endIndex } } @inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages. public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } let cnt = Swift.min(count, buffer.count) withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in _ = memcpy(UnsafeMutableRawPointer(buffer.baseAddress), bytes.baseAddress, cnt) } return (Iterator(self, at: startIndex + cnt), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. @inlinable // This is @inlinable as trivially computable. public func makeIterator() -> Data.Iterator { return Iterator(self, at: startIndex) } public struct Iterator : IteratorProtocol { @usableFromInline internal typealias Buffer = ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) @usableFromInline internal let _data: Data @usableFromInline internal var _buffer: Buffer @usableFromInline internal var _idx: Data.Index @usableFromInline internal let _endIdx: Data.Index @usableFromInline // This is @usableFromInline as a non-trivial initializer. internal init(_ data: Data, at loc: Data.Index) { // The let vars prevent this from being marked as @inlinable _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = loc _endIdx = data.endIndex let bufferSize = MemoryLayout<Buffer>.size Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) let bufferIdx = (loc - data.startIndex) % bufferSize data.copyBytes(to: ptr, from: (loc - bufferIdx)..<(data.endIndex - (loc - bufferIdx) > bufferSize ? (loc - bufferIdx) + bufferSize : data.endIndex)) } } public mutating func next() -> UInt8? { let idx = _idx let bufferSize = MemoryLayout<Buffer>.size guard idx < _endIdx else { return nil } _idx += 1 let bufferIdx = (idx - _data.startIndex) % bufferSize if bufferIdx == 0 { var buffer = _buffer Swift.withUnsafeMutableBytes(of: &buffer) { let ptr = $0.bindMemory(to: UInt8.self) // populate the buffer _data.copyBytes(to: ptr, from: idx..<(_endIdx - idx > bufferSize ? idx + bufferSize : _endIdx)) } _buffer = buffer } return Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. @inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change. public static func ==(d1 : Data, d2 : Data) -> Bool { let length1 = d1.count if length1 != d2.count { return false } if length1 > 0 { return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafeRawBufferPointer) in children.append((label: "pointer", value: bytes.baseAddress!)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _representation.bridgedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } // @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in try container.encode(contentsOf: buffer) } } }
apache-2.0
29564d6585e35e21e90d7b6ee3298b7a
44.383054
352
0.593877
5.126719
false
false
false
false
ahoppen/swift
test/type/opaque_parameters.swift
1
3212
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-redundant-requirements protocol P { } protocol Q { associatedtype A: P & Equatable func f() -> A } extension Int: P { } extension String: P { } // expected-note@+1{{requirement from conditional conformance of '[Double]' to 'Q'}} extension Array: Q where Element: P, Element: Equatable { func f() -> Element { return first! } } extension Set: Q where Element: P, Element: Equatable { // expected-warning {{redundant conformance constraint 'Element' : 'Equatable'}} func f() -> Element { return first! } } // expected-note@+2{{where 'some Q' = 'Int'}} // expected-note@+1{{in call to function 'takesQ'}} func takesQ(_ q: some Q) -> Bool { return q.f() == q.f() } func testTakesQ(arrayOfInts: [Int], setOfStrings: Set<String>, i: Int) { _ = takesQ(arrayOfInts) _ = takesQ(setOfStrings) _ = takesQ(i) // expected-error{{global function 'takesQ' requires that 'Int' conform to 'Q'}} let f = takesQ // expected-error{{generic parameter 'some Q' could not be inferred}} let _: ([String]) -> Bool = takesQ let _: ([Double]) -> Bool = takesQ // expected-error{{global function 'takesQ' requires that 'Double' conform to 'P'}} _ = f } // expected-note@+1{{where 'some P' = '[Int]'}} func takeMultiple<T>(_: T, _: some Q, _: some P) { } func testTakeMultiple( arrayOfInts: [Int], setOfStrings: Set<String>, i: Int, d: Double ) { takeMultiple(d, arrayOfInts, i) takeMultiple(d, arrayOfInts, arrayOfInts) // expected-error{{global function 'takeMultiple' requires that '[Int]' conform to 'P'}} } // inout func anyInOut(_: inout some P) { } func testAnyInOut() { var i = 17 anyInOut(&i) } // In structural positions. func anyDictionary(_ dict: [some Hashable: some Any]) { } func testAnyDictionary(numberNames: [Int: String]) { anyDictionary(numberNames) } // Combine with parameterized protocol types protocol PrimaryCollection<Element>: Collection {} extension Array: PrimaryCollection { } extension Set: PrimaryCollection { } func takePrimaryCollections( _ strings: some PrimaryCollection<String>, _ ints : some PrimaryCollection<Int> ) { for s in strings { let _: String = s } for i in ints { let _: Int = i } } func takeMatchedPrimaryCollections<T: Equatable>( _ first: some PrimaryCollection<T>, _ second: some PrimaryCollection<T> ) -> Bool { first.elementsEqual(second) } func testPrimaries( arrayOfInts: [Int], setOfStrings: Set<String>, setOfInts: Set<Int> ) { takePrimaryCollections(setOfStrings, setOfInts) takePrimaryCollections(setOfStrings, arrayOfInts) _ = takeMatchedPrimaryCollections(arrayOfInts, setOfInts) _ = takeMatchedPrimaryCollections(arrayOfInts, setOfStrings) // expected-error{{type of expression is ambiguous without more context}} } // Prohibit use of opaque parameters in consuming positions. typealias FnType<T> = (T) -> Void func consumingA(fn: (some P) -> Void) { } // expected-error{{'some' cannot appear in parameter position in parameter type '(some P) -> Void'}} func consumingB(fn: FnType<some P>) { } // expected-error{{'some' cannot appear in parameter position in parameter type '(some P) -> Void'}}
apache-2.0
9ec6242bdecac7e6e8eca22ad7018dd4
28.46789
142
0.691158
3.730546
false
false
false
false
caolsen/CircularSlider
CircularSliderExample/CircularSlider.swift
1
14785
// // CircularSlider.swift // // Created by Christopher Olsen on 03/03/16. // Copyright © 2016 Christopher Olsen. All rights reserved. // import UIKit import QuartzCore import Foundation enum CircularSliderHandleType { case semiTransparentWhiteSmallCircle, semiTransparentWhiteCircle, semiTransparentBlackCircle, bigCircle } class CircularSlider: UIControl { // MARK: Values // Value at North/midnight (start) var minimumValue: Float = 0.0 { didSet { setNeedsDisplay() } } // Value at North/midnight (end) var maximumValue: Float = 100.0 { didSet { setNeedsDisplay() } } // value for end of arc. This allows for incomplete circles to be created var maximumAngle: CGFloat = 360.0 { didSet { if maximumAngle > 360.0 { print("Warning: Maximum angle should be 360 or less.") maximumAngle = 360.0 } setNeedsDisplay() } } // Current value between North/midnight (start) and North/midnight (end) - clockwise direction var currentValue: Float { set { assert(newValue <= maximumValue && newValue >= minimumValue, "current value \(newValue) must be between minimumValue \(minimumValue) and maximumValue \(maximumValue)") // Update the angleFromNorth to match this newly set value angleFromNorth = Int((newValue * Float(maximumAngle)) / (maximumValue - minimumValue)) moveHandle(CGFloat(angleFromNorth)) sendActions(for: UIControl.Event.valueChanged) } get { return (Float(angleFromNorth) * (maximumValue - minimumValue)) / Float(maximumAngle) } } // MARK: Handle let circularSliderHandle = CircularSliderHandle() /** * Note: If this property is not set, filledColor will be used. * If handleType is semiTransparent*, specified color will override this property. * * Color of the handle */ var handleColor: UIColor? { didSet { setNeedsDisplay() } } // Type of the handle to display to represent draggable current value var handleType: CircularSliderHandleType = .semiTransparentWhiteSmallCircle { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } // MARK: Labels // BOOL indicating whether values snap to nearest label var snapToLabels: Bool = false /** * Note: The LAST label will appear at North/midnight * The FIRST label will appear at the first interval after North/midnight * * NSArray of strings used to render labels at regular intervals within the circle */ var innerMarkingLabels: [String]? { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } // MARK: Visual Customisation // property Width of the line to draw for slider var lineWidth: Int = 5 { didSet { setNeedsUpdateConstraints() // This could affect intrinsic content size invalidateIntrinsicContentSize() // Need to update intrinsice content size setNeedsDisplay() // Need to redraw with new line width } } // Color of filled portion of line (from North/midnight start to currentValue) var filledColor: UIColor = .red { didSet { setNeedsDisplay() } } // Color of unfilled portion of line (from currentValue to North/midnight end) var unfilledColor: UIColor = .black { didSet { setNeedsDisplay() } } // Font of the inner marking labels within the circle var labelFont: UIFont = .systemFont(ofSize: 10.0) { didSet { setNeedsDisplay() } } // Color of the inner marking labels within the circle var labelColor: UIColor = .red { didSet { setNeedsDisplay() } } /** * Note: A negative value will move the label closer to the center. A positive value will move the label closer to the circumference * Value with which to displace all labels along radial line from center to slider circumference. */ var labelDisplacement: CGFloat = 0 // type of LineCap to use for the unfilled arc // NOTE: user CGLineCap.Butt for full circles var unfilledArcLineCap: CGLineCap = .butt // type of CGLineCap to use for the arc that is filled in as the handle moves var filledArcLineCap: CGLineCap = .butt // MARK: Computed Public Properties var computedRadius: CGFloat { if (radius == -1.0) { // Slider is being used in frames - calculate the max radius based on the frame // (constrained by smallest dimension so it fits within view) let minimumDimension = min(bounds.size.height, bounds.size.width) let halfLineWidth = ceilf(Float(lineWidth) / 2.0) let halfHandleWidth = ceilf(Float(handleWidth) / 2.0) return minimumDimension * 0.5 - CGFloat(max(halfHandleWidth, halfLineWidth)) } return radius } var centerPoint: CGPoint { return CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5) } var angleFromNorth: Int = 0 { didSet { assert(angleFromNorth >= 0, "angleFromNorth \(angleFromNorth) must be greater than 0") } } var handleWidth: CGFloat { switch handleType { case .semiTransparentWhiteSmallCircle: return CGFloat(lineWidth / 2) case .semiTransparentWhiteCircle, .semiTransparentBlackCircle: return CGFloat(lineWidth) case .bigCircle: return CGFloat(lineWidth + 5) // 5 points bigger than standard handles } } // MARK: Private Variables fileprivate var radius: CGFloat = -1.0 { didSet { setNeedsUpdateConstraints() setNeedsDisplay() } } fileprivate var computedHandleColor: UIColor? { var newHandleColor = handleColor switch (handleType) { case .semiTransparentWhiteSmallCircle, .semiTransparentWhiteCircle: newHandleColor = UIColor(white: 1.0, alpha: 0.7) case .semiTransparentBlackCircle: newHandleColor = UIColor(white: 0.0, alpha: 0.7) case .bigCircle: newHandleColor = filledColor } return newHandleColor } fileprivate var innerLabelRadialDistanceFromCircumference: CGFloat { // Labels should be moved far enough to clear the line itself plus a fixed offset (relative to radius). var distanceToMoveInwards = 0.1 * -(radius) - 0.5 * CGFloat(lineWidth) distanceToMoveInwards -= 0.5 * labelFont.pointSize // Also account for variable font size. return distanceToMoveInwards } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = .clear } // TODO: initializer for autolayout /** * Initialise the class with a desired radius * This initialiser should be used for autolayout - use initWithFrame otherwise * Note: Intrinsic content size will be based on this parameter, lineWidth and handleType * * radiusToSet Desired radius of circular slider */ // convenience init(radiusToSet: CGFloat) { // // } // MARK: - Function Overrides override var intrinsicContentSize : CGSize { // Total width is: diameter + (2 * MAX(halfLineWidth, halfHandleWidth)) let diameter = radius * 2 let halfLineWidth = ceilf(Float(lineWidth) / 2.0) let halfHandleWidth = ceilf(Float(handleWidth) / 2.0) let widthWithHandle = diameter + CGFloat(2 * max(halfHandleWidth, halfLineWidth)) return CGSize(width: widthWithHandle, height: widthWithHandle) } override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext() // Draw the circular lines that slider handle moves along drawLine(ctx!) // Draw the draggable 'handle' let handleCenter = pointOnCircleAtAngleFromNorth(angleFromNorth) circularSliderHandle.frame = drawHandle(ctx!, atPoint: handleCenter) // Draw inner labels drawInnerLabels(ctx!, rect: rect) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard event != nil else { return false } if pointInsideHandle(point, withEvent: event!) { return true } else { return pointInsideCircle(point, withEvent: event!) } } fileprivate func pointInsideCircle(_ point: CGPoint, withEvent event: UIEvent) -> Bool { let p1 = centerPoint let p2 = point let xDist = p2.x - p1.x let yDist = p2.y - p1.y let distance = sqrt((xDist * xDist) + (yDist * yDist)) return distance < computedRadius + CGFloat(lineWidth) * 0.5 } fileprivate func pointInsideHandle(_ point: CGPoint, withEvent event: UIEvent) -> Bool { let handleCenter = pointOnCircleAtAngleFromNorth(angleFromNorth) // Adhere to apple's design guidelines - avoid making touch targets smaller than 44 points let handleRadius = max(handleWidth, 44.0) * 0.5 // Treat handle as a box around it's center let pointInsideHorzontalHandleBounds = (point.x >= handleCenter.x - handleRadius && point.x <= handleCenter.x + handleRadius) let pointInsideVerticalHandleBounds = (point.y >= handleCenter.y - handleRadius && point.y <= handleCenter.y + handleRadius) return pointInsideHorzontalHandleBounds && pointInsideVerticalHandleBounds } // MARK: - Drawing methods func drawLine(_ ctx: CGContext) { unfilledColor.set() // Draw an unfilled circle (this shows what can be filled) CircularTrig.drawUnfilledCircleInContext(ctx, center: centerPoint, radius: computedRadius, lineWidth: CGFloat(lineWidth), maximumAngle: maximumAngle, lineCap: unfilledArcLineCap) filledColor.set() // Draw an unfilled arc up to the currently filled point CircularTrig.drawUnfilledArcInContext(ctx, center: centerPoint, radius: computedRadius, lineWidth: CGFloat(lineWidth), fromAngleFromNorth: 0, toAngleFromNorth: CGFloat(angleFromNorth), lineCap: filledArcLineCap) } func drawHandle(_ ctx: CGContext, atPoint handleCenter: CGPoint) -> CGRect { ctx.saveGState() var frame: CGRect! // Ensure that handle is drawn in the correct color handleColor = computedHandleColor handleColor!.set() frame = CircularTrig.drawFilledCircleInContext(ctx, center: handleCenter, radius: 0.5 * handleWidth) ctx.saveGState() return frame } func drawInnerLabels(_ ctx: CGContext, rect: CGRect) { if let labels = innerMarkingLabels, labels.count > 0 { let attributes = [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelColor] // Enumerate through labels clockwise for (index, label) in labels.enumerated() { let labelFrame = contextCoordinatesForLabel(atIndex: index) ctx.saveGState() // invert transformation used on arc ctx.concatenate(CGAffineTransform(translationX: labelFrame.origin.x + (labelFrame.width / 2), y: labelFrame.origin.y + (labelFrame.height / 2))) ctx.concatenate(getRotationalTransform().inverted()) ctx.concatenate(CGAffineTransform(translationX: -(labelFrame.origin.x + (labelFrame.width / 2)), y: -(labelFrame.origin.y + (labelFrame.height / 2)))) // draw label label.draw(in: labelFrame, withAttributes: attributes) ctx.restoreGState() } } } func contextCoordinatesForLabel(atIndex index: Int) -> CGRect { let label = innerMarkingLabels![index] var percentageAlongCircle: CGFloat! // Determine how many degrees around the full circle this label should go if maximumAngle == 360.0 { percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count)) * CGFloat(index + 1)) / 100.0 } else { percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count - 1)) * CGFloat(index)) / 100.0 } let degreesFromNorthForLabel = percentageAlongCircle * maximumAngle let pointOnCircle = pointOnCircleAtAngleFromNorth(Int(degreesFromNorthForLabel)) let labelSize = sizeOfString(label, withFont: labelFont) let offsetFromCircle = offsetFromCircleForLabelAtIndex(index, withSize: labelSize) return CGRect(x: pointOnCircle.x + offsetFromCircle.x, y: pointOnCircle.y + offsetFromCircle.y, width: labelSize.width, height: labelSize.height) } func offsetFromCircleForLabelAtIndex(_ index: Int, withSize labelSize: CGSize) -> CGPoint { // Determine how many degrees around the full circle this label should go let percentageAlongCircle = ((100.0 / CGFloat(innerMarkingLabels!.count - 1)) * CGFloat(index)) / 100.0 let degreesFromNorthForLabel = percentageAlongCircle * maximumAngle let radialDistance = innerLabelRadialDistanceFromCircumference + labelDisplacement let inwardOffset = CircularTrig.pointOnRadius(radialDistance, atAngleFromNorth: CGFloat(degreesFromNorthForLabel)) return CGPoint(x: -labelSize.width * 0.5 + inwardOffset.x, y: -labelSize.height * 0.5 + inwardOffset.y) } // MARK: - UIControl Functions override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let lastPoint = touch.location(in: self) let lastAngle = floor(CircularTrig.angleRelativeToNorthFromPoint(centerPoint, toPoint: lastPoint)) moveHandle(lastAngle) sendActions(for: UIControl.Event.valueChanged) return true } fileprivate func moveHandle(_ newAngleFromNorth: CGFloat) { // prevent slider from moving past maximumAngle if newAngleFromNorth > maximumAngle { if angleFromNorth < Int(maximumAngle / 2) { angleFromNorth = 0 setNeedsDisplay() } else if angleFromNorth > Int(maximumAngle / 2) { angleFromNorth = Int(maximumAngle) setNeedsDisplay() } } else { angleFromNorth = Int(newAngleFromNorth) } setNeedsDisplay() } // MARK: - Helper Functions func pointOnCircleAtAngleFromNorth(_ angleFromNorth: Int) -> CGPoint { let offset = CircularTrig.pointOnRadius(computedRadius, atAngleFromNorth: CGFloat(angleFromNorth)) return CGPoint(x: centerPoint.x + offset.x, y: centerPoint.y + offset.y) } func sizeOfString(_ string: String, withFont font: UIFont) -> CGSize { let attributes = [NSAttributedString.Key.font: font] return NSAttributedString(string: string, attributes: attributes).size() } func getRotationalTransform() -> CGAffineTransform { if maximumAngle == 360 { // do not perform a rotation if using a full circle slider let transform = CGAffineTransform.identity.rotated(by: CGFloat(0)) return transform } else { // rotate slider view so "north" is at the start let radians = Double(-(maximumAngle / 2)) / 180.0 * Double.pi let transform = CGAffineTransform.identity.rotated(by: CGFloat(radians)) return transform } } }
mit
f2a9d1fe3cdf095fb2b68c5ee29bbfa0
33.704225
215
0.692776
4.647595
false
false
false
false
finngaida/spotify2applemusic
Pods/Sweeft/Sources/Sweeft/Networking/API.swift
1
25917
// // API.swift // Pods // // Created by Mathias Quintero on 12/21/16. // // import Foundation /// Response promise from an API public typealias Response<T> = Promise<T, APIError> /// Allowed Methods for HTTP Requests public enum HTTPMethod: String { case get = "GET" case put = "PUT" case post = "POST" case delete = "DELETE" } /// API Body public protocol API { /// Endpoint Reference associatedtype Endpoint: APIEndpoint /// Base URL for the api var baseURL: String { get } /// Headers that should be included into every single request var baseHeaders: [String:String] { get } /// Queries that should be included into every single request var baseQueries: [String:String] { get } /// Will be called before performing a Request for people who like to go deep into the metal func willPerform(request: inout URLRequest) /// Will allow you to prepare more customizable URL Sessions func session(for method: HTTPMethod, at endpoint: Endpoint) -> URLSession } public extension API { /// URL Object for the API var base: URL! { return URL(string: baseURL) } /// Default is empty var baseHeaders: [String:String] { return .empty } /// Default is empty var baseQueries: [String:String] { return .empty } /// Default does nothing func willPerform(request: inout URLRequest) { // Do Nothing } /// Default is the shared session func session(for method: HTTPMethod, at endpoint: Endpoint) -> URLSession { return .shared } } public extension API { /** Will do a simple Request - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: Data that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of Data */ public func doDataRequest(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: Data? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> Data.Result { let promise = Promise<Data, APIError>(completionQueue: completionQueue) let requestString = arguments ==> endpoint.rawValue ** { string, argument in return string.replacingOccurrences(of: "{\(argument.key)}", with: argument.value.description) } let url = (baseQueries + queries >>= { $0.description }) ==> base.appendingPathComponent(requestString) ** { url, query in return url.appendingQuery(key: query.key, value: query.value) } var request = URLRequest(url: url) request.httpMethod = method.rawValue request.httpBody = body (baseHeaders + headers >>= { $0.description }) => { request.addValue($1, forHTTPHeaderField: $0) } auth.apply(to: &request) willPerform(request: &request) let session = self.session(for: method, at: endpoint) let task = session.dataTask(with: request) { (data, response, error) in if let error = error { if let error = error as? URLError, error.code == .timedOut { promise.error(with: .timeout) } else { promise.error(with: .unknown(error: error)) } return } let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 200 guard acceptableStatusCodes.contains(statusCode) else { promise.error(with: .invalidStatus(code: statusCode, data: data)) return } if let data = data { promise.success(with: data) } else { promise.error(with: .noData) } } task.resume() return promise } /** Will do a simple Request of a Data Representable Object - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: Object with the Data that should be sent - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of a Represented Object */ public func doRepresentedRequest<T: DataRepresentable>(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: DataSerializable? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> Response<T> { var headers = headers headers["Content-Type"] <- body?.contentType headers["Accept"] <- T.accept return doDataRequest(with: method, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body?.data, acceptableStatusCodes: acceptableStatusCodes) .nested { data, promise in guard let underlyingData = T(data: data) else { promise.error(with: .invalidData(data: data)) return } promise.success(with: underlyingData) } } /** Will do a simple JSON Request - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of JSON Object */ public func doJSONRequest(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> JSON.Result { return doRepresentedRequest(with: method, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue) } /** Will do a simple Request for a Deserializable Object - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the object inside the json response - Returns: Promise of the Object */ public func doObjectRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: [String] = .empty) -> Response<T> { return doJSONRequest(with: method, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes) .nested { json, promise in guard let item: T = json.get(in: path) else { promise.error(with: .mappingError(json: json)) return } promise.success(with: item) } } /** Will do a simple Request for a Deserializable Object - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the object inside the json response - Returns: Promise of the Object */ public func doObjectRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: String...) -> Response<T> { return doObjectRequest(with: method, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, at: path) } /** Will do a simple Request for an array of Deserializable Objects - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the array inside the json object - Parameter internalPath: path of the object inside the individual objects inside the array - Returns: Promise of Object Array */ public func doObjectsRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: [String] = .empty, with internalPath: [String] = .empty) -> Response<[T]> { return doJSONRequest(with: method, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes) .nested { json, promise in guard let items: [T] = json.getAll(in: path, for: internalPath) else { promise.error(with: .mappingError(json: json)) return } promise.success(with: items) } } /** Will do a series of requests for objects asynchounously and combine the responses into a single array - Parameter method: HTTP Method - Parameter endpoints: array of endpoints of the API it should be sent to - Parameter arguments: Array of arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: Array of JSON Bodies that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the array inside the json object - Parameter internalPath: path of the object inside the individual objects inside the array - Returns: Promise of Array of objects */ public func doFlatBulkObjectRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoints: [Endpoint], arguments: [[String:CustomStringConvertible]] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, bodies: [JSON?] = .empty, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: [String] = .empty, with internalPath: [String] = .empty) -> Response<[T]> { return BulkPromise<[T], APIError>(promises: endpoints => { endpoint, index in let arguments = arguments | index let body = bodies | index ?? nil return self.doObjectsRequest(with: method, to: endpoint, arguments: arguments.?, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue, at: path, with: internalPath) }, completionQueue: completionQueue).flattened } /** Will do a series of requests for objects asynchounously and return an array with all the responses - Parameter method: HTTP Method - Parameter endpoints: array of endpoints of the API it should be sent to - Parameter arguments: Array of arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: Array of JSON Bodies that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the array inside the json object - Returns: Promise of Array of objects */ public func doBulkObjectRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoints: [Endpoint], arguments: [[String:CustomStringConvertible]] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, bodies: [JSON?] = .empty, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: [String] = .empty) -> Response<[T]> { return BulkPromise(promises: endpoints => { endpoint, index in let arguments = arguments | index let body = bodies | index ?? nil return self.doObjectRequest(with: method, to: endpoint, arguments: arguments.?, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue, at: path) }, completionQueue: completionQueue) } /** Will do a series of requests for objects asynchounously and return an array with all the responses - Parameter method: HTTP Method - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: Array of arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: Array of JSON Bodies that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Parameter path: path of the array inside the json object - Returns: Promise of Array of objects */ public func doBulkObjectRequest<T: Deserializable>(with method: HTTPMethod = .get, to endpoint: Endpoint, arguments: [[String:CustomStringConvertible]] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, bodies: [JSON?] = .empty, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main, at path: String...) -> Response<[T]> { let endpoints = arguments.count.range => returning(endpoint) return doBulkObjectRequest(with: method, to: endpoints, arguments: arguments, headers: headers, queries: queries, auth: auth, bodies: bodies, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue, at: path) } /** Do a JSON GET Request - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: Arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of JSON Object */ public func get(_ endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> JSON.Result { return doJSONRequest(with: .get, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue) } /** Do a JSON DELETE Request - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: Arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of JSON Object */ public func delete(_ endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, body: JSON? = nil, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> JSON.Result { return doJSONRequest(with: .delete, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue) } /** Do a JSON POST Request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: Arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of JSON Object */ public func post(_ body: JSON? = nil, to endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> JSON.Result { return doJSONRequest(with: .post, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue) } /** Do a JSON PUT Request - Parameter body: JSON Object that should be sent in the HTTP Body - Parameter endpoint: endpoint of the API it should be sent to - Parameter arguments: Arguments encoded into the endpoint string - Parameter headers: HTTP Headers that should be added to the request - Parameter auth: Authentication Manager for the request - Parameter acceptableStatusCodes: HTTP Status Codes that mean a succesfull request was done - Parameter completionQueue: Queue in which the promise should be run - Returns: Promise of JSON Object */ public func put(_ body: JSON? = nil, at endpoint: Endpoint, arguments: [String:CustomStringConvertible] = .empty, headers: [String:CustomStringConvertible] = .empty, queries: [String:CustomStringConvertible] = .empty, auth: Auth = NoAuth.standard, acceptableStatusCodes: [Int] = [200], completionQueue: DispatchQueue = .main) -> JSON.Result { return doJSONRequest(with: .put, to: endpoint, arguments: arguments, headers: headers, queries: queries, auth: auth, body: body, acceptableStatusCodes: acceptableStatusCodes, completionQueue: completionQueue) } }
mit
c03208c306604ae4a81a59959fd30433
48.554493
239
0.5976
5.661206
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/CustomCamera/WBCameraManager.swift
1
7094
// // WBCameraManager.swift // TestCode // // Created by Zhouheng on 2020/6/30. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit import AVFoundation class WBCameraManager: NSObject { static let exposeObserverKey = "adjustingExposure" var CameraAdjustingExposureContext = 0 /// 转换摄像头 func switchCamera(session: AVCaptureSession, oldinput: AVCaptureDeviceInput, newinput: AVCaptureDeviceInput) -> AVCaptureDeviceInput { session.beginConfiguration() session.removeInput(oldinput) if session.canAddInput(newinput) { session.addInput(newinput) session.commitConfiguration() return newinput } else { session.addInput(oldinput) session.commitConfiguration() return oldinput } } /// 缩放 func zoom(device: AVCaptureDevice, factor: CGFloat) -> NSError? { if device.activeFormat.videoMaxZoomFactor > factor, factor >= 1.0 { do { try device.lockForConfiguration() device.ramp(toVideoZoomFactor: factor, withRate: 4.0) device.unlockForConfiguration() return nil } catch (let error) { return error as NSError } } return error(text: "不支持的缩放倍数", code: 20000) } /// 聚焦 func focus(device: AVCaptureDevice, point: CGPoint) -> NSError? { let supported = device.isFocusPointOfInterestSupported && device.isFocusModeSupported(.autoFocus) if supported { do { try device.lockForConfiguration() device.focusPointOfInterest = point device.focusMode = .autoFocus device.unlockForConfiguration() return nil } catch (let error) { return error as NSError } } return error(text: "设备不支持对焦", code: 20001) } /// 曝光 func expose(device: AVCaptureDevice, point: CGPoint) -> NSError? { let supported = device.isExposurePointOfInterestSupported && device.isExposureModeSupported(.autoExpose) if supported { do { try device.lockForConfiguration() device.exposurePointOfInterest = point device.exposureMode = .autoExpose if device.isExposureModeSupported(.locked) { device.addObserver(self, forKeyPath: WBCameraManager.exposeObserverKey, options: .new, context: &CameraAdjustingExposureContext) } device.unlockForConfiguration() return nil } catch (let error) { return error as NSError } } return error(text: "设备不支持曝光", code: 20002) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &CameraAdjustingExposureContext { if let device = object as? AVCaptureDevice { if device.isAdjustingExposure, device.isExposureModeSupported(.locked) { device.removeObserver(self, forKeyPath: WBCameraManager.exposeObserverKey, context: &CameraAdjustingExposureContext) DispatchQueue.main.async { do { try device.lockForConfiguration() device.exposureMode = .locked device.unlockForConfiguration() } catch (let error) { print(" --- 曝光监听出现错误 --- \(error)") } } } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } /// 自动聚焦、曝光 func resetFocusAndExposure(device: AVCaptureDevice) -> NSError? { let canResetFocus = device.isFocusPointOfInterestSupported && device.isFlashModeSupported(.auto) let canResetExposure = device.isExposurePointOfInterestSupported && device.isExposureModeSupported(.autoExpose) let centerPoint = CGPoint(x: 0.5, y: 0.5) do { try device.lockForConfiguration() if canResetFocus { device.focusMode = .autoFocus device.focusPointOfInterest = centerPoint } if canResetExposure { device.exposureMode = .autoExpose device.exposurePointOfInterest = centerPoint } device.unlockForConfiguration() } catch (let error) { return error as NSError } return nil } /// 闪光灯 func flashMode(device: AVCaptureDevice) -> AVCaptureDevice.FlashMode { return device.flashMode } func changeFlash(device: AVCaptureDevice, mode: AVCaptureDevice.FlashMode) -> NSError? { if !device.hasFlash { return error(text: "不支持闪光灯", code: 20003) } if torchMode(device: device) == .on { let _ = self.setTorch(device: device, mode: .off) } return setFlash(device: device, mode: mode) } func setFlash(device: AVCaptureDevice, mode: AVCaptureDevice.FlashMode) -> NSError? { if device.isFlashModeSupported(mode) { do { try device.lockForConfiguration() device.flashMode = mode device.unlockForConfiguration() return nil } catch (let error) { return error as NSError } } return error(text: "不支持闪光灯", code: 20003) } /// 手电筒 func torchMode(device: AVCaptureDevice) -> AVCaptureDevice.TorchMode { return device.torchMode } func changeTorch(device: AVCaptureDevice, mode: AVCaptureDevice.TorchMode) -> NSError? { if !device.hasTorch { return error(text: "不支持手电筒", code: 20004) } if flashMode(device: device) == .on { let _ = setFlash(device: device, mode: .off) } return setTorch(device: device, mode: mode) } func setTorch(device: AVCaptureDevice, mode: AVCaptureDevice.TorchMode) -> NSError? { if device.isTorchModeSupported(mode) { do { try device.lockForConfiguration() device.torchMode = mode device.unlockForConfiguration() return nil } catch (let error) { return error as NSError } } return error(text: "不支持手电筒", code: 20004) } private func error(text: String, code: Int) -> NSError { let desc = [NSLocalizedDescriptionKey: text] return NSError(domain: "com.wb.camera", code: code, userInfo: desc) } }
apache-2.0
82f66348b9bc3c78e7f855cc4d2537d8
35.510526
151
0.570708
5.390054
false
true
false
false
karamage/CVCalendar
CVCalendar Demo/CVCalendar/CVCalendarMonthContentViewController.swift
1
16990
// // CVCalendarMonthContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthContentViewController: CVCalendarContentViewController { private var monthViews: [Identifier : MonthView] public override init(calendarView: CalendarView, frame: CGRect) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) initialLoad(presentedMonthView.date) } public init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate) presentedMonthView.updateAppearance(scrollView.bounds) initialLoad(presentedDate) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Load & Reload public func initialLoad(date: NSDate) { insertMonthView(getPreviousMonth(date), withIdentifier: Previous) insertMonthView(presentedMonthView, withIdentifier: Presented) insertMonthView(getFollowingMonth(date), withIdentifier: Following) presentedMonthView.mapDayViews { dayView in if self.matchedDays(dayView.date, Date(date: date)) { self.calendarView.coordinator.flush() self.calendarView.touchController.receiveTouchOnDayView(dayView) dayView.circleView?.removeFromSuperview() } } calendarView.presentedDate = CVDate(date: presentedMonthView.date) } public func reloadMonthViews() { for (identifier, monthView) in monthViews { monthView.frame.origin.x = CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width monthView.removeFromSuperview() scrollView.addSubview(monthView) } } // MARK: - Insertion public func insertMonthView(monthView: MonthView, withIdentifier identifier: Identifier) { let index = CGFloat(indexOfIdentifier(identifier)) monthView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0) monthViews[identifier] = monthView scrollView.addSubview(monthView) } public func replaceMonthView(monthView: MonthView, withIdentifier identifier: Identifier, animatable: Bool) { var monthViewFrame = monthView.frame monthViewFrame.origin.x = monthViewFrame.width * CGFloat(indexOfIdentifier(identifier)) monthView.frame = monthViewFrame monthViews[identifier] = monthView if animatable { scrollView.scrollRectToVisible(monthViewFrame, animated: false) } } // MARK: - Load management public func scrolledLeft() { if let presented = monthViews[Presented], let following = monthViews[Following] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[Previous]?.removeFromSuperview() replaceMonthView(presented, withIdentifier: Previous, animatable: false) replaceMonthView(following, withIdentifier: Presented, animatable: true) insertMonthView(getFollowingMonth(following.date), withIdentifier: Following) } } } public func scrolledRight() { if let previous = monthViews[Previous], let presented = monthViews[Presented] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[Following]?.removeFromSuperview() replaceMonthView(previous, withIdentifier: Presented, animatable: true) replaceMonthView(presented, withIdentifier: Following, animatable: false) insertMonthView(getPreviousMonth(previous.date), withIdentifier: Previous) } } } // MARK: - Override methods public override func updateFrames(rect: CGRect) { super.updateFrames(rect) for monthView in monthViews.values { monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds) } reloadMonthViews() if let presented = monthViews[Presented] { if scrollView.frame.height != presented.potentialSize.height { updateHeight(presented.potentialSize.height, animated: false) } scrollView.scrollRectToVisible(presented.frame, animated: false) } } public override func performedDayViewSelection(dayView: DayView) { if dayView.isOut { if dayView.date.day > 20 { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate)) presentPreviousView(dayView) } else { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate)) presentNextView(dayView) } } } public override func presentPreviousView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = monthViews[Following], let presented = monthViews[Presented], let previous = monthViews[Previous] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x += self.scrollView.frame.width presented.frame.origin.x += self.scrollView.frame.width previous.frame.origin.x += self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.Following, animatable: false) self.replaceMonthView(previous, withIdentifier: self.Presented, animatable: false) self.presentedMonthView = previous self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getPreviousMonth(previous.date), withIdentifier: self.Previous) self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } } public override func presentNextView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = monthViews[Previous], let presented = monthViews[Presented], let following = monthViews[Following] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x -= self.scrollView.frame.width presented.frame.origin.x -= self.scrollView.frame.width following.frame.origin.x -= self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.Previous, animatable: false) self.replaceMonthView(following, withIdentifier: self.Presented, animatable: false) self.presentedMonthView = following self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getFollowingMonth(following.date), withIdentifier: self.Following) self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } } public override func updateDayViews(hidden: Bool) { setDayOutViewsVisible(hidden) } private var togglingBlocked = false public override func togglePresentedDate(date: NSDate) { let presentedDate = Date(date: date) if let presented = monthViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date { if !matchedDays(selectedDate, presentedDate) && !togglingBlocked { if !matchedMonths(presentedDate, selectedDate) { togglingBlocked = true monthViews[Previous]?.removeFromSuperview() monthViews[Following]?.removeFromSuperview() insertMonthView(getPreviousMonth(date), withIdentifier: Previous) insertMonthView(getFollowingMonth(date), withIdentifier: Following) let currentMonthView = MonthView(calendarView: calendarView, date: date) currentMonthView.updateAppearance(scrollView.bounds) currentMonthView.alpha = 0 insertMonthView(currentMonthView, withIdentifier: Presented) presentedMonthView = currentMonthView calendarView.presentedDate = Date(date: date) UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { presented.alpha = 0 currentMonthView.alpha = 1 }) { _ in presented.removeFromSuperview() self.selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) self.togglingBlocked = false self.updateLayoutIfNeeded() } } else { if let currentMonthView = monthViews[Presented] { selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) } } } } } } // MARK: - Month management extension CVCalendarMonthContentViewController { public func getFollowingMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month += 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } public func getPreviousMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month -= 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } } // MARK: - Visual preparation extension CVCalendarMonthContentViewController { public func prepareTopMarkersOnMonthView(monthView: MonthView, hidden: Bool) { monthView.mapDayViews { dayView in dayView.topMarker?.hidden = hidden } } public func setDayOutViewsVisible(visible: Bool) { for monthView in monthViews.values { monthView.mapDayViews { dayView in if dayView.isOut { if !visible { dayView.alpha = 0 dayView.hidden = false } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { dayView.alpha = visible ? 0 : 1 }) { _ in if visible { dayView.alpha = 1 dayView.hidden = true dayView.userInteractionEnabled = false } else { dayView.userInteractionEnabled = true } } } } } } public func updateSelection() { let coordinator = calendarView.coordinator if let selected = coordinator.selectedDayView { for (index, monthView) in monthViews { if indexOfIdentifier(index) != 1 { monthView.mapDayViews { dayView in if dayView == selected { dayView.setDeselectedWithClearing(true) coordinator.dequeueDayView(dayView) } } } } } if let presentedMonthView = monthViews[Presented] { self.presentedMonthView = presentedMonthView calendarView.presentedDate = Date(date: presentedMonthView.date) if let selected = coordinator.selectedDayView, let selectedMonthView = selected.monthView where !matchedMonths(Date(date: selectedMonthView.date), Date(date: presentedMonthView.date)) { let current = Date(date: NSDate()) let presented = Date(date: presentedMonthView.date) if matchedMonths(current, presented) { selectDayViewWithDay(current.day, inMonthView: presentedMonthView) } else { selectDayViewWithDay(Date(date: calendarView.manager.monthDateRange(presentedMonthView.date).monthStartDate).day, inMonthView: presentedMonthView) } } } } public func selectDayViewWithDay(day: Int, inMonthView monthView: CVCalendarMonthView) { let coordinator = calendarView.coordinator monthView.mapDayViews { dayView in if dayView.date.day == day && !dayView.isOut { if let selected = coordinator.selectedDayView where selected != dayView { self.calendarView.didSelectDayView(dayView) } coordinator.performDayViewSingleSelection(dayView) } } } } // MARK: - UIScrollViewDelegate extension CVCalendarMonthContentViewController { public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y != 0 { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0) } let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1) if currentPage != page { currentPage = page } lastContentOffset = scrollView.contentOffset.x } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if let presented = monthViews[Presented] { prepareTopMarkersOnMonthView(presented, hidden: true) } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if pageChanged { switch direction { case .Left: scrolledLeft() case .Right: scrolledRight() default: break } } updateSelection() updateLayoutIfNeeded() pageLoadingEnabled = true direction = .None } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { let rightBorder = scrollView.frame.width if scrollView.contentOffset.x <= rightBorder { direction = .Right } else { direction = .Left } } for monthView in monthViews.values { prepareTopMarkersOnMonthView(monthView, hidden: false) } } }
mit
4951966504e72e9296ffa39f45236acc
39.551313
197
0.583755
6.482259
false
false
false
false
DrGo/ResearchKit
samples/ORKCatalog/ORKCatalog/Results/ResultTableViewProviders.swift
10
34991
/* 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 import ResearchKit /** Create a `protocol<UITableViewDataSource, UITableViewDelegate>` that knows how to present the metadata for an `ORKResult` instance. Extra metadata is displayed for specific `ORKResult` types. For example, a table view provider for an `ORKFileResult` instance will display the `fileURL` in addition to the standard `ORKResult` properties. To learn about how to read metadata from the different kinds of `ORKResult` instances, see the `ResultTableViewProvider` subclasses below. Specifically, look at their `resultRowsForSection(_:)` implementations which are meant to enhance the metadata that is displayed for the result table view provider. Note: since these table view providers are meant to display data for developers and are not user visible (see description in `ResultViewController`), none of the properties / content are localized. */ func resultTableViewProviderForResult(result: ORKResult?) -> protocol<UITableViewDataSource, UITableViewDelegate> { guard let result = result else { /* Use a table view provider that shows that there hasn't been a recently provided result. */ return NoRecentResultTableViewProvider() } // The type that will be used to create an instance of a table view provider. let providerType: ResultTableViewProvider.Type /* Map the type of the result to its associated `ResultTableViewProvider`. To reduce the possible effects of someone modifying this code--i.e. cases getting reordered and accidentally getting matches for subtypes of the intended result type, we guard against any subtype matches (e.g. the `ORKCollectionResult` guard against `result` being an `ORKTaskResult` instance). */ switch result { // Survey Questions case is ORKBooleanQuestionResult: providerType = BooleanQuestionResultTableViewProvider.self case is ORKChoiceQuestionResult: providerType = ChoiceQuestionResultTableViewProvider.self case is ORKDateQuestionResult: providerType = DateQuestionResultTableViewProvider.self case is ORKNumericQuestionResult: providerType = NumericQuestionResultTableViewProvider.self case is ORKScaleQuestionResult: providerType = ScaleQuestionResultTableViewProvider.self case is ORKTextQuestionResult: providerType = TextQuestionResultTableViewProvider.self case is ORKTimeIntervalQuestionResult: providerType = TimeIntervalQuestionResultTableViewProvider.self case is ORKTimeOfDayQuestionResult: providerType = TimeOfDayQuestionResultTableViewProvider.self // Consent case is ORKConsentSignatureResult: providerType = ConsentSignatureResultTableViewProvider.self // Active Tasks case is ORKFileResult: providerType = FileResultTableViewProvider.self case is ORKPSATResult: providerType = PSATResultTableViewProvider.self case is ORKReactionTimeResult: providerType = ReactionTimeViewProvider.self case is ORKSpatialSpanMemoryResult: providerType = SpatialSpanMemoryResultTableViewProvider.self case is ORKTappingIntervalResult: providerType = TappingIntervalResultTableViewProvider.self case is ORKToneAudiometryResult: providerType = ToneAudiometryResultTableViewProvider.self case is ORKTimedWalkResult: providerType = TimedWalkResultTableViewProvider.self case is ORKToneAudiometryResult: providerType = ToneAudiometryResultTableViewProvider.self case is ORKTowerOfHanoiResult: providerType = TowerOfHanoiResultTableViewProvider.self // All case is ORKTaskResult: providerType = TaskResultTableViewProvider.self /* Refer to the comment near the switch statement for why the additional guard is here. */ case is ORKCollectionResult where !(result is ORKTaskResult): providerType = CollectionResultTableViewProvider.self default: fatalError("No ResultTableViewProvider defined for \(result.dynamicType).") } // Return a new instance of the specific `ResultTableViewProvider`. return providerType.init(result: result) } /** An enum representing the data that can be presented in a `UITableViewCell` by a `ResultsTableViewProvider` type. */ enum ResultRow { // MARK: Cases case Text(String, detail: String, selectable: Bool) case TextImage(String, image: UIImage?) case Image(UIImage?) // MARK: Types /** Possible `UITableViewCell` identifiers that have been defined in the main storyboard. */ enum TableViewCellIdentifier: String { case Default = "Default" case NoResultSet = "NoResultSet" case NoChildResults = "NoChildResults" case TextImage = "TextImage" case Image = "Image" } // MARK: Initialization /// Helper initializer for `ResultRow.Text`. init(text: String, detail: Any?, selectable: Bool = false) { /* Show the string value if `detail` is not `nil`, otherwise show that it's "nil". Use Optional's map method to map the value to a string if the detail is not `nil`. */ let detailText = detail.map { String($0) } ?? "nil" self = .Text(text, detail: detailText, selectable: selectable) } } /** A special `protocol<UITableViewDataSource, UITableViewDelegate>` that displays a row saying that there's no result. */ class NoRecentResultTableViewProvider: NSObject, UITableViewDataSource, UITableViewDelegate { // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.NoResultSet.rawValue, forIndexPath: indexPath) } } // MARK: ResultTableViewProvider and Subclasses /** Base class for displaying metadata for an `ORKResult` instance. The metadata that's displayed are common properties for all `ORKResult` instances (e.g. `startDate` and `endDate`). */ class ResultTableViewProvider: NSObject, UITableViewDataSource, UITableViewDelegate { // MARK: Properties let result: ORKResult // MARK: Initializers required init(result: ORKResult) { self.result = result } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let resultRows = resultRowsForSection(section) // Show an empty row if there isn't any metadata in the rows for this section. if resultRows.isEmpty { return 1 } return resultRows.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let resultRows = resultRowsForSection(indexPath.section) // Show an empty row if there isn't any metadata in the rows for this section. if resultRows.isEmpty { return tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.NoChildResults.rawValue, forIndexPath: indexPath) } // Fetch the `ResultRow` that corresponds to `indexPath`. let resultRow = resultRows[indexPath.row] switch resultRow { case let .Text(text, detail: detailText, selectable): let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.Default.rawValue, forIndexPath: indexPath) cell.textLabel!.text = text cell.detailTextLabel!.text = detailText /* In this sample, the accessory type should be a disclosure indicator if the table view cell is selectable. */ cell.selectionStyle = selectable ? .Default : .None cell.accessoryType = selectable ? .DisclosureIndicator : .None return cell case let .TextImage(text, image): let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.TextImage.rawValue, forIndexPath: indexPath) as! TextImageTableViewCell cell.leftTextLabel.text = text cell.rightImageView.image = image return cell case let .Image(image): let cell = tableView.dequeueReusableCellWithIdentifier(ResultRow.TableViewCellIdentifier.Image.rawValue, forIndexPath: indexPath) as! ImageTableViewCell cell.fullImageView.image = image return cell } } // MARK: UITableViewDelegate func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Result" : nil } // MARK: Overridable Methods func resultRowsForSection(section: Int) -> [ResultRow] { // Default to an empty array. guard section == 0 else { return [] } return [ // The class name of the result object. ResultRow(text: "type", detail: result.dynamicType), /* The identifier of the result, which corresponds to the task, step or item that generated it. */ ResultRow(text: "identifier", detail: result.identifier), // The start date for the result. ResultRow(text: "start", detail: result.startDate), // The end date for the result. ResultRow(text: "end", detail: result.endDate) ] } } /// Table view provider specific to an `ORKBooleanQuestionResult` instance. class BooleanQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let boolResult = result as! ORKBooleanQuestionResult var boolResultDetailText: String? if let booleanAnswer = boolResult.booleanAnswer { boolResultDetailText = booleanAnswer.boolValue ? "true" : "false" } return super.resultRowsForSection(section) + [ ResultRow(text: "bool", detail: boolResultDetailText) ] } } /// Table view provider specific to an `ORKChoiceQuestionResult` instance. class ChoiceQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let choiceResult = result as! ORKChoiceQuestionResult return super.resultRowsForSection(section) + [ ResultRow(text: "choices", detail: choiceResult.choiceAnswers) ] } } /// Table view provider specific to an `ORKDateQuestionResult` instance. class DateQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKDateQuestionResult return super.resultRowsForSection(section) + [ // The date the user entered. ResultRow(text: "dateAnswer", detail: questionResult.dateAnswer), // The calendar that was used when the date picker was presented. ResultRow(text: "calendar", detail: questionResult.calendar), // The timezone when the user answered. ResultRow(text: "timeZone", detail: questionResult.timeZone) ] } } /// Table view provider specific to an `ORKNumericQuestionResult` instance. class NumericQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKNumericQuestionResult return super.resultRowsForSection(section) + [ // The numeric value the user entered. ResultRow(text: "numericAnswer", detail: questionResult.numericAnswer), // The unit string that was displayed with the numeric value. ResultRow(text: "unit", detail: questionResult.unit) ] } } /// Table view provider specific to an `ORKScaleQuestionResult` instance. class ScaleQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let scaleQuestionResult = result as! ORKScaleQuestionResult return super.resultRowsForSection(section) + [ // The numeric value returned from the discrete or continuous slider. ResultRow(text: "scaleAnswer", detail: scaleQuestionResult.scaleAnswer) ] } } /// Table view provider specific to an `ORKTextQuestionResult` instance. class TextQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKTextQuestionResult return super.resultRowsForSection(section) + [ // The text the user typed into the text view. ResultRow(text: "textAnswer", detail: questionResult.textAnswer) ] } } /// Table view provider specific to an `ORKTimeIntervalQuestionResult` instance. class TimeIntervalQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKTimeIntervalQuestionResult return super.resultRowsForSection(section) + [ // The time interval the user answered. ResultRow(text: "intervalAnswer", detail: questionResult.intervalAnswer) ] } } /// Table view provider specific to an `ORKTimeOfDayQuestionResult` instance. class TimeOfDayQuestionResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKTimeOfDayQuestionResult // Format the date components received in the result. let dateComponentsFormatter = NSDateComponentsFormatter() let dateComponentsAnswerText = dateComponentsFormatter.stringFromDateComponents(questionResult.dateComponentsAnswer!) return super.resultRowsForSection(section) + [ // String summarizing the date components the user entered. ResultRow(text: "dateComponentsAnswer", detail: dateComponentsAnswerText) ] } } /// Table view provider specific to an `ORKConsentSignatureResult` instance. class ConsentSignatureResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let signatureResult = result as! ORKConsentSignatureResult let signature = signatureResult.signature! return super.resultRowsForSection(section) + [ /* The identifier for the signature, identifying which one it is in the document. */ ResultRow(text: "identifier", detail: signature.identifier), /* The title of the signatory, displayed under the line. For example, "Participant". */ ResultRow(text: "title", detail: signature.title), // The given name of the signatory. ResultRow(text: "givenName", detail: signature.givenName), // The family name of the signatory. ResultRow(text: "familyName", detail: signature.familyName), // The date the signature was obtained. ResultRow(text: "date", detail: signature.signatureDate), // The captured image. .TextImage("signature", image: signature.signatureImage) ] } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let lastRow = self.tableView(tableView, numberOfRowsInSection: indexPath.section) - 1 if indexPath.row == lastRow { return 200 } return UITableViewAutomaticDimension } } /// Table view provider specific to an `ORKFileResult` instance. class FileResultTableViewProvider: ResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKFileResult let rows = super.resultRowsForSection(section) + [ // The MIME content type for the file produced. ResultRow(text: "contentType", detail: questionResult.contentType), // The URL of the generated file on disk. ResultRow(text: "fileURL", detail: questionResult.fileURL) ] if let fileURL = questionResult.fileURL, let contentType = questionResult.contentType where contentType.hasPrefix("image/") { if let data = NSData(contentsOfURL: fileURL), let image = UIImage(data: data) { return rows + [ // The image of the generated file on disk. .Image(image) ] } } return rows } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let resultRows = resultRowsForSection(indexPath.section) if !resultRows.isEmpty { switch resultRows[indexPath.row] { case .Image(.Some(let image)): // Keep the aspect ratio the same. let imageAspectRatio = image.size.width / image.size.height return tableView.frame.size.width / imageAspectRatio default: break } } return UITableViewAutomaticDimension } } /// Table view provider specific to an `ORKPSATResult` instance. class PSATResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Answers" } // MARK: UITableViewDelegate func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let PSATResult = result as! ORKPSATResult var rows = super.resultRowsForSection(section) if section == 0 { var presentation = "" let presentationMode = PSATResult.presentationMode if (presentationMode == .Auditory) { presentation = "PASAT" } else if (presentationMode == .Visual) { presentation = "PVSAT" } else if (presentationMode.contains(.Auditory) && presentationMode.contains(.Visual)) { presentation = "PAVSAT" } else { presentation = "Unknown" } // The presentation mode (auditory and/or visual) of the PSAT. rows.append(ResultRow(text: "presentation", detail: presentation)) // The time interval between two digits. rows.append(ResultRow(text: "ISI", detail: PSATResult.interStimulusInterval)) // The time duration the digit is shown on screen. rows.append(ResultRow(text: "stimulus", detail: PSATResult.stimulusDuration)) // The serie length of the PSAT. rows.append(ResultRow(text: "length", detail: PSATResult.length)) // The number of correct answers. rows.append(ResultRow(text: "total correct", detail: PSATResult.totalCorrect)) // The total number of consecutive correct answers. rows.append(ResultRow(text: "total dyad", detail: PSATResult.totalDyad)) // The total time for the answers. rows.append(ResultRow(text: "total time", detail: PSATResult.totalTime)) // The initial digit number. rows.append(ResultRow(text: "initial digit", detail: PSATResult.initialDigit)) return rows } // Add a `ResultRow` for each sample. return rows + PSATResult.samples!.map { sample in let PSATSample = sample as! ORKPSATSample let text = String(format: "%@", PSATSample.correct ? "correct" : "error") let detail = "\(PSATSample.answer) (digit: \(PSATSample.digit), time: \(PSATSample.time))" return ResultRow(text: text, detail: detail) } } } /// Table view provider specific to an `ORKReactionTimeResult` instance. class ReactionTimeViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "File Results" } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let reactionTimeResult = result as! ORKReactionTimeResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ ResultRow(text: "timestamp", detail: reactionTimeResult.timestamp) ] } let fileResultDetail = reactionTimeResult.fileResult.fileURL!.absoluteString return rows + [ ResultRow(text: "File Result", detail: fileResultDetail) ] } } /// Table view provider specific to an `ORKSpatialSpanMemoryResult` instance. class SpatialSpanMemoryResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Game Records" } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKSpatialSpanMemoryResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ // The score the user received for the game as a whole. ResultRow(text: "score", detail: questionResult.score), // The number of games played. ResultRow(text: "numberOfGames", detail: questionResult.numberOfGames), // The number of failures. ResultRow(text: "numberOfFailures", detail: questionResult.numberOfFailures) ] } return rows + questionResult.gameRecords!.map { gameRecord in // Note `gameRecord` is of type `ORKSpatialSpanMemoryGameRecord`. return ResultRow(text: "game", detail: gameRecord.score) } } } /// Table view provider specific to an `ORKTappingIntervalResult` instance. class TappingIntervalResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Samples" } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let questionResult = result as! ORKTappingIntervalResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ // The size of the view where the two target buttons are displayed. ResultRow(text: "stepViewSize", detail: questionResult.stepViewSize), // The rect corresponding to the left button. ResultRow(text: "buttonRect1", detail: questionResult.buttonRect1), // The rect corresponding to the right button. ResultRow(text: "buttonRect2", detail: questionResult.buttonRect2) ] } // Add a `ResultRow` for each sample. return rows + questionResult.samples!.map { tappingSample in // These tap locations are relative to the rectangle defined by `stepViewSize`. let buttonText = tappingSample.buttonIdentifier == .None ? "None" : "button \(tappingSample.buttonIdentifier.rawValue)" let text = String(format: "%.3f", tappingSample.timestamp) let detail = "\(buttonText) \(tappingSample.location)" return ResultRow(text: text, detail: detail) } } } /// Table view provider specific to an `ORKTimedWalkResult` instance. class TimedWalkResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return super.tableView(tableView, titleForHeaderInSection: 0) } // MARK: UITableViewDelegate func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let TimedWalkResult = result as! ORKTimedWalkResult let rows = super.resultRowsForSection(section) return rows + [ // The timed walk distance in meters. ResultRow(text: "distance (m)", detail: TimedWalkResult.distanceInMeters), // The time limit to complete the trials. ResultRow(text: "time limit (s)", detail: TimedWalkResult.timeLimit), // The duration for an addition of the PVSAT. ResultRow(text: "duration (s)", detail: TimedWalkResult.duration) ] } } /// Table view provider specific to an `ORKToneAudiometryResult` instance. class ToneAudiometryResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Samples" } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let toneAudiometryResult = result as! ORKToneAudiometryResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ // The size of the view where the two target buttons are displayed. ResultRow(text: "outputVolume", detail: toneAudiometryResult.outputVolume), ] } // Add a `ResultRow` for each sample. return rows + toneAudiometryResult.samples!.map { toneSample in let text: String let detail: String let channelName = toneSample.channel == .Left ? "Left" : "Right" text = "\(toneSample.frequency) \(channelName)" detail = "\(toneSample.amplitude)" return ResultRow(text: text, detail: detail) } } } /// Table view provider specific to an `ORKTowerOfHanoiResult` instance. class TowerOfHanoiResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { let towerOfHanoiResult = result as! ORKTowerOfHanoiResult return towerOfHanoiResult.moves != nil ? (towerOfHanoiResult.moves!.count + 1) : 1 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Move \(section )" } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let towerOfHanoiResult = result as! ORKTowerOfHanoiResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ ResultRow(text: "solved", detail: towerOfHanoiResult.puzzleWasSolved ? "true" : "false"), ResultRow(text: "moves", detail: "\(towerOfHanoiResult.moves?.count ?? 0 )")] } // Add a `ResultRow` for each sample. let move = towerOfHanoiResult.moves![section - 1] as! ORKTowerOfHanoiMove return rows + [ ResultRow(text: "donor tower", detail: "\(move.donorTowerIndex)"), ResultRow(text: "recipient tower", detail: "\(move.recipientTowerIndex)"), ResultRow(text: "timestamp", detail: "\(move.timestamp)")] } } /// Table view provider specific to an `ORKTaskResult` instance. class TaskResultTableViewProvider: CollectionResultTableViewProvider { // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let taskResult = result as! ORKTaskResult let rows = super.resultRowsForSection(section) if section == 0 { return rows + [ ResultRow(text: "taskRunUUID", detail: taskResult.taskRunUUID.UUIDString), ResultRow(text: "outputDirectory", detail: taskResult.outputDirectory) ] } return rows } } /// Table view provider specific to an `ORKCollectionResult` instance. class CollectionResultTableViewProvider: ResultTableViewProvider { // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return super.tableView(tableView, titleForHeaderInSection: 0) } return "Child Results" } // MARK: UITableViewDelegate func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return indexPath.section == 1 } // MARK: ResultTableViewProvider override func resultRowsForSection(section: Int) -> [ResultRow] { let collectionResult = result as! ORKCollectionResult let rows = super.resultRowsForSection(section) // Show the child results in section 1. if section == 1 { return rows + collectionResult.results!.map { childResult in let childResultClassName = "\(childResult.dynamicType)" return ResultRow(text: childResultClassName, detail: childResult.identifier, selectable: true) } } return rows } }
bsd-3-clause
223db5614329a73e3949e1ecd70845d4
36.910076
176
0.649081
5.702575
false
false
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/00170-swift-parser-skipsingle.swift
1
10209
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func i(f: g) -> <j>(() -> j) -> g { func g k, l { typealias l = m<k<m>, f> } func ^(a: Boolean, Bool) -> Bool { return !(a) } func b(c) -> <d>(() -> d) { } func q(v: h) -> <r>(() -> r) -> h { n { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } protocol p { } protocol m : p { } protocol v : p { } protocol m { v = m } func s<s : m, v : m u v.v == s> (m: v) { } func s<v : m u v.v == v> (m: v) { } s( { ({}) } t func f<e>() -> (e, e -> e) -> e { e b e.c = {} { e) { f } } protocol f { class func c() } class e: f { class func c } } protocol A { func c()l k { func l() -> g { m "" } } class C: k, A { j func l()q c() -> g { m "" } } func e<r where r: A, r: k>(n: r) { n.c() } protocol A { typealias h } c k<r : A> { p f: r p p: r.h } protocol C l.e() } } class o { typealias l = l protocol a { } protocol h : a { } protocol k : a { } protocol g { j n = a } struct n : g { j n = h } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } let k = a k() h protocol k : h { func h k func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c k) func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { class func i() } class k: c{ class func i { } class i { func d((h: (Any, AnyObject)) { d(h) } } d h) func d<i>() -> (i, i -> i) -> i { i j i.f = { } protocol d { class func f() } class i: d{ class func f {} protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e()) class l { func f((k, l() -> f } class d } class i: d, g { l func d() -> f { m "" } } } func m<j n j: g, j: d let l = h l() f protocol l : f { func f protocol g func g<h>() -> (h, h -> h) -> h { f f: ((h, h -> h) -> h)! j f } protocol f { class func j() } struct i { f d: f.i func j() { d.j() } } class g { typealias f = f } func g(f: Int = k) { } let i = g class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j struct c<d : Sequence> { var b: [c<d>] { return [] } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func f<T : Boolean>(b: T) { } f(true as Boolean) func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type func e() { d.e() } } b protocol c : b { func b otocol A { E == F>(f: B<T>) } struct } } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f func g() f e: d { f func g() { } } (e() h d).i() e protocol g : e { func e func a(b: Int = 0) { } let c = a c() var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func m<u>() -> (u, u -> u) -> u { p o p.s = { } { u) { o } } s m { class func s() } class p: m{ class func s {} s p { func m() -> String } class n { func p() -> String { q "" } } class e: n, p { v func> String { q "" } { r m = m } func s<o : m, o : p o o.m == o> (m: o) { } func s<v : p o v.m == m> (u: String) -> <t>(() -> t) - func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n struct c<d: Sequence, b where Optional<b> == d.Iterator.Element> d = i } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { typealias i } protocol e { class func i() } i (d() as e).j.i() d protocol i : d { func d class k<g>: d { var f: g init(f: g) { self.f = f l. d { typealias i = l typealias j = j<i<l>, i> } class j { typealias d = d struct A<T> { let a: [(T, () -> ())] = [] } func b<d-> d { class d:b class b class A<T : A> { } func c<d { enum c { func e var _ = e } } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicl A { { typealias b = b d.i = { } { g) { h } } protocol f { class func i() }} func f<m>() -> (m, m -> m) -> m { e c e.i = { } { m) { n } } protocol f { class func i() } class e: f{ class func i {} func n<j>() -> (j, j -> j) -> j { var m: ((j> j)! f m } protocol k { typealias m } struct e<j : k> {n: j let i: j.m } l func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m - import Foundation class Foo<T>: NSObject { var foo: T init(foo: T) { B>(t: T) { t.c() } x x) { } class a { var _ = i() { } } a=1 as a=1 func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> func k<q { enum k { func j var _ = j } } class x { s m func j(m) } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v let u: v.l } protocol y { o= p>(r: m<v>) } struct D : y { s p = Int func y<v k r { s m } class y<D> { w <r: func j<v x: v) { x.k() } func x(j: Int = a) { } let k = x func b((Any, e))(e: (Any) -> <d>(()-> d) -> f func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) protocol f : f { } func h<d { enum h { func e var _ = e } } protocol e { e func e() } struct h { var d: e.h func e() { d.e() } } protocol f { i [] } func f<g>() -> (g, g -> g) -> g class A<T : A> n = { return $u } l o: n = { (d: n, o: n -> n) -> n q return o(d) } import Foundation class m<j>: NSObject { var h: j g -> k = l $n } b f: _ = j() { } } func k<g { enum k { func l var _ = l func o() as o).m.k() func p(k: b) -> <i>(() -> i) -> b { n { o f "\(k): \(o())" } } struct d<d : n, o:j n { l p } protocol o : o { } func o< class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> struct l<e : Sequence> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k struct c<e> { let d: [( h } func b(g: f) -> <e>(()-> e) -> i h } func e<l { enum e { func e j { class func n() } class l: j{ k() -> ()) } ({}) func j<o : Boolean>(l: o) { } j(j q Boolean) func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) { return { (p: (Any, Any) -> Any) -> Any in func n<n : l,) { } n(e()) e func a<T>() { enum b { case c } } o class w<r>: c { init(g: r) { n.g = g s.init() (t: o struct t : o { p v = t } q t<where n.v == t<v : o u m : v { } struct h<t, j: v where t.h == j f> { c(d ()) } func b(e)-> <d>(() -> d) func f<T : Boolean>(b: T) { } f(true as Boolean) class A: A { } class B : C { } typealias C = B protocol A { typealias E } struct B<T : As a { typealias b = b } func a<T>() {f { class func i() } class d: f{ class func i {} func f() { ({}) } func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } protocol a : a { } class j { func y((Any, j))(v: (Any, AnyObject)) { y(v) } } func w(j: () -> ()) { } class v { l _ = w() { } } ({}) func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { u n } y q<x> { s w(x, () -> ()) } o n { func j() p } class r { func s() -> p { t "" } } class w: r, n { k v: ))] = [] } class n<x : n> w class x<u>: d { l i: u init(i: u) { o.i = j { r { w s "\(f): \(w())" } } protoc protocol f : b { func b () { g g h g } } func e(i: d) -> <f>(() -> f)> import Foundation class k<f>: NSObject { d e: f g(e: f) { j h.g() } } d protocol i : d { func d i b protocol d : b { func b func d(e: = { (g: h, f: h -> h) -> h in return f(g) } } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } struct j<l : o> { k b: l } func a<l>() -> [j<l>] { return [] } f k) func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typealias l typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } a=1 as a=1 enum S<T> { case C(T, () -> ()) } n) func f<o>() -> (o, o -> o) -> o { o m o.j = { } { o) { r } } p q) { } o m = j m() class m { func r((Any, m))(j: (Any, AnyObject)) { r(j) } } func m<o { r m { func n n _ = n } } class k<l : k <c b: func b<c { enum b { func b var _ = b func n<p>() -> (p, p -> p) -> p { b, l] g(o(q)) h e { j class func r() } class k: h{ class func r {} var k = 1 var s: r -> r t -> r) -> r m u h>] { u [] } func r(e: () -> ()) { } class n { var _ = r()
apache-2.0
be93b6e6cd5e5520683db7ea7fd7fd23
12.071703
87
0.404447
2.280322
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/EventBridge/EventBridge_Error.swift
1
4145
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for EventBridge public struct EventBridgeErrorType: AWSErrorType { enum Code: String { case concurrentModificationException = "ConcurrentModificationException" case internalException = "InternalException" case invalidEventPatternException = "InvalidEventPatternException" case invalidStateException = "InvalidStateException" case limitExceededException = "LimitExceededException" case managedRuleException = "ManagedRuleException" case operationDisabledException = "OperationDisabledException" case policyLengthExceededException = "PolicyLengthExceededException" case resourceAlreadyExistsException = "ResourceAlreadyExistsException" case resourceNotFoundException = "ResourceNotFoundException" } private let error: Code public let context: AWSErrorContext? /// initialize EventBridge public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// There is concurrent modification on a rule or target. public static var concurrentModificationException: Self { .init(.concurrentModificationException) } /// This exception occurs due to unexpected causes. public static var internalException: Self { .init(.internalException) } /// The event pattern is not valid. public static var invalidEventPatternException: Self { .init(.invalidEventPatternException) } /// The specified state is not a valid state for an event source. public static var invalidStateException: Self { .init(.invalidStateException) } /// You tried to create more rules or add more targets to a rule than is allowed. public static var limitExceededException: Self { .init(.limitExceededException) } /// This rule was created by an AWS service on behalf of your account. It is managed by that service. If you see this error in response to DeleteRule or RemoveTargets, you can use the Force parameter in those calls to delete the rule or remove targets from the rule. You cannot modify these managed rules by using DisableRule, EnableRule, PutTargets, PutRule, TagResource, or UntagResource. public static var managedRuleException: Self { .init(.managedRuleException) } /// The operation you are attempting is not available in this region. public static var operationDisabledException: Self { .init(.operationDisabledException) } /// The event bus policy is too long. For more information, see the limits. public static var policyLengthExceededException: Self { .init(.policyLengthExceededException) } /// The resource you are trying to create already exists. public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) } /// An entity that you specified does not exist. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } } extension EventBridgeErrorType: Equatable { public static func == (lhs: EventBridgeErrorType, rhs: EventBridgeErrorType) -> Bool { lhs.error == rhs.error } } extension EventBridgeErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
295e7398a6f0e0496f869591745a3295
48.345238
394
0.710977
5.273537
false
false
false
false
rokuz/omim
iphone/Maps/UI/Welcome/FirstLaunchController.swift
1
2512
final class FirstLaunchController: WelcomeViewController { private enum Permission { case location case notifications case nothing } private struct FirstLaunchConfig: WelcomeConfig { let image: UIImage let title: String let text: String let buttonTitle: String let requestPermission: Permission } static var welcomeConfigs: [WelcomeConfig] { return [ FirstLaunchConfig(image: #imageLiteral(resourceName: "img_onboarding_offline_maps"), title: "onboarding_offline_maps_title", text: "onboarding_offline_maps_message", buttonTitle: "whats_new_next_button", requestPermission: .nothing), FirstLaunchConfig(image: #imageLiteral(resourceName: "img_onboarding_geoposition"), title: "onboarding_location_title", text: "onboarding_location_message", buttonTitle: "whats_new_next_button", requestPermission: .nothing), FirstLaunchConfig(image: #imageLiteral(resourceName: "img_onboarding_notification"), title: "onboarding_notifications_title", text: "onboarding_notifications_message", buttonTitle: "whats_new_next_button", requestPermission: .location), FirstLaunchConfig(image: #imageLiteral(resourceName: "img_onboarding_done"), title: "first_launch_congrats_title", text: "first_launch_congrats_text", buttonTitle: "done", requestPermission: .notifications) ] } override class var key: String { return toString(self) } static func controllers() -> [FirstLaunchController] { var result = [FirstLaunchController]() let sb = UIStoryboard.instance(.welcome) FirstLaunchController.welcomeConfigs.forEach { (config) in let vc = sb.instantiateViewController(withIdentifier: toString(self)) as! FirstLaunchController vc.pageConfig = config result.append(vc) } return result } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let config = pageConfig as! FirstLaunchConfig switch config.requestPermission { case .location: MWMLocationManager.start() case .notifications: MWMPushNotifications.setup() case .nothing: break } } }
apache-2.0
402474c750ef69eb7d66494bc645ef44
36.492537
101
0.620621
5.344681
false
true
false
false
WalterCreazyBear/Swifter30
UIElements/UIElements/UITextViewController.swift
1
2188
// // UITextViewController.swift // UIElements // // Created by 熊伟 on 2017/6/20. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class UITextViewController: UIViewController { var text:UITextView = UITextView.init() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.yellow self.title = "Text" self.text.frame = CGRect.init(x: 10, y: 100, width: UIScreen.main.bounds.width-20, height: 300) self.text.backgroundColor = UIColor.white self.text.font = UIFont.systemFont(ofSize: 14) self.text.textColor = UIColor.black self.text.delegate = self self.view.addSubview(self.text) //MARK: 这行代码使得光标从text的左上角开始~ self.automaticallyAdjustsScrollViewInsets = false let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(resign)) self.view.addGestureRecognizer(tapGesture) } @objc func resign() { self.text.resignFirstResponder() } } extension UITextViewController:UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { print("--textViewShouldBeginEditing---\(textView.text)") return true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { print("--textViewShouldEndEditing---\(textView.text)") return true } func textViewDidBeginEditing(_ textView: UITextView) { print("--textViewDidBeginEditing---\(textView.text)") } func textViewDidEndEditing(_ textView: UITextView) { print("--textViewDidEndEditing---\(textView.text)") } func textViewDidChange(_ textView: UITextView) { print("--textViewDidChange---\(textView.text)") } func textViewDidChangeSelection(_ textView: UITextView) { print("--textViewDidChangeSelection---\(textView.text)") } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { print("--replacementText---\(text)") return true } }
mit
6dbbbfcaa9f2e59a06b2b4d92cc3a12f
28.875
116
0.650395
4.979167
false
false
false
false
zeroc-ice/ice-demos
swift/Manual/simpleFilesystem/Sources/Server/main.swift
1
4081
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice /// Servant class for Node. class NodeI: Node { private let name: String private let parent: DirectoryI? init(name: String, parent: DirectoryI?) { self.name = name self.parent = parent } // Slice Node::name() operation func name(current _: Ice.Current) -> String { return name } // Add servant to ASM and parent's contents map. func activate(adapter: Ice.ObjectAdapter) throws { let id = Ice.Identity(name: parent == nil ? "RootDir" : UUID().uuidString, category: "") let prx = try adapter.add(servant: makeDisp(), id: id) // call addChild with proxy to `self` only if parent is not nil parent?.addChild(child: uncheckedCast(prx: prx, type: NodePrx.self)) } // Create a dispatcher for servant `self` func makeDisp() -> Ice.Disp { fatalError("Abstract method") } } /// Servant class for File, reuses Node servant implementation. class FileI: NodeI, File { private var lines: [String] = [] // Slice File::read() operation func read(current _: Ice.Current) -> [String] { return lines } // Slice File::write() operation func write(text: [String], current _: Ice.Current) { lines = text } // Create a dispatcher for servant `self` override func makeDisp() -> Ice.Disp { return FileDisp(self) } } /// Servant class for Directory, reuses Node servant implementation. class DirectoryI: NodeI, Directory { private var contents: [NodePrx?] = [] // Slice Directory::list() operation func list(current _: Ice.Current) -> [NodePrx?] { return contents } // addChild is called by the child in order to add // itself to the contents member of the parent func addChild(child: NodePrx) { contents.append(child) } // Create a dispatcher for servant `self` override func makeDisp() -> Ice.Disp { return DirectoryDisp(self) } } func run() -> Int32 { do { let communicator = try Ice.initialize(CommandLine.arguments) defer { communicator.destroy() } // // Create an object adapter. // let adapter = try communicator.createObjectAdapterWithEndpoints(name: "SimpleFilesystem", endpoints: "default -h localhost -p 10000") // // Create the root directory (with name "/" and no parent) // let root = DirectoryI(name: "/", parent: nil) try root.activate(adapter: adapter) // // Create a file called "README" in the root directory // var file = FileI(name: "README", parent: root) file.write(text: ["This file system contains a collection of poetry."], current: Ice.Current()) try file.activate(adapter: adapter) // // Create a directory called "Coleridge" in the root directory // let coleridge = DirectoryI(name: "Coleridge", parent: root) try coleridge.activate(adapter: adapter) // // Create a file called "Kubla_Khan" in the Coleridge directory // file = FileI(name: "Kubla_Khan", parent: coleridge) file.write(text: ["In Xanadu did Kubla Khan", "A stately pleasure-dome decree:", "Where Alph, the sacred river, ran", "Through caverns measureless to man", "Down to a sunless sea."], current: Ice.Current()) try file.activate(adapter: adapter) // // All objects are created, allow client requests now // try adapter.activate() // // Wait until we are done // communicator.waitForShutdown() return 0 } catch { print("Error: \(error)\n") return 1 } } exit(run())
gpl-2.0
2e4b6bde2a076f520d6f1e46f0529d55
27.943262
115
0.567508
4.378755
false
false
false
false
lb2281075105/LBXiongMaoTV
LBXiongMaoTV/LBXiongMaoTV/NetWork(网络)/LBXMNetWork.swift
1
830
// // LBXMNetWork.swift // LBXiongMaoTV // // Created by 云媒 on 2017/4/13. // Copyright © 2017年 YunMei. All rights reserved. // import UIKit import Alamofire ///枚举 enum HttpRequestType { case GET case POST } ///请求类型、url、pragrams class LBXMNetWork: NSObject { class func netWorkRequest(requestType:HttpRequestType,urlString:String,pragrams:[String:Any]? = nil,completion:@escaping (_ json:AnyObject)->()){ ///请求数据 let type = requestType == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(urlString, method: type, parameters: pragrams).responseJSON { (response) in if let result = response.result.value{ completion(result as AnyObject) } } } }
apache-2.0
22a5f8eed5ba5a41fb40afdc11e89ab7
24.774194
148
0.607009
4.035354
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/Home/ZXCHomeRetWeetView.swift
1
3184
// // ZXCHomeRetWeetView.swift // WeiBo // // Created by Aioria on 2017/3/30. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit class ZXCHomeRetWeetView: UIView { var statusViewModel: ZXCStatusViewModel? { didSet { if let picUrls = statusViewModel?.status?.retweeted_status?.pic_urls, picUrls.count > 0 { homePicView.picUrls = picUrls homePicView.snp.updateConstraints({ (make) in make.top.equalTo(labContent.snp.bottom).offset(MarginHome) make.bottom.equalTo(self).offset(-MarginHome) }) } else if statusViewModel?.status?.retweeted_status?.text != nil { homePicView.snp.updateConstraints({ (make) in make.top.equalTo(labContent.snp.bottom) make.bottom.equalTo(self).offset(-MarginHome) }) homePicView.picUrls = [] } else { homePicView.snp.updateConstraints({ (make) in make.top.equalTo(labContent.snp.bottom) make.bottom.equalTo(self) }) homePicView.picUrls = [] } if statusViewModel?.status?.retweeted_status?.text != nil { labContent.snp.updateConstraints({ (make) in make.top.equalTo(self).offset(MarginHome) }) labContent.attributedText = statusViewModel?.reweetAttributedString } else { labContent.snp.updateConstraints({ (make) in make.top.equalTo(self) }) labContent.attributedText = NSAttributedString() } } } lazy var homePicView: ZXCHomePictureView = ZXCHomePictureView() fileprivate lazy var labContent: UILabel = { let lab = UILabel(fontSize: 13, textColor: UIColor.lightGray, text: "") lab.numberOfLines = 0 return lab }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { backgroundColor = UIColor.init(white: 0.95, alpha: 1) addSubview(labContent) addSubview(homePicView) labContent.snp.makeConstraints { (make) in make.top.equalTo(self).offset(MarginHome) make.left.equalTo(self).offset(MarginHome) make.right.equalTo(self).offset(-MarginHome) } homePicView.snp.makeConstraints { (make) in make.top.equalTo(labContent.snp.bottom).offset(MarginHome) make.left.equalTo(self).offset(MarginHome) make.size.equalTo(CGSize(width: 100, height: 100)) make.bottom.equalTo(self).offset(-MarginHome) } } }
mit
70e226a2b4bc5ac81fcb2c5c744724b8
29.295238
101
0.524992
5.223317
false
false
false
false
solszl/Shrimp500px
Shrimp500px/Service/NetWork/NetStatus.swift
1
2699
// // NetStatus.swift // Shrimp500px // // Created by 振亮 孙 on 16/3/2. // Copyright © 2016年 papa.studio. All rights reserved. // import Foundation import ReachabilitySwift protocol NetStatusDelegate { func startListen() func stopListen() func reachabilityChanged(status: Reachability.NetworkStatus) func currentReachabilityStatus(status: Reachability.NetworkStatus) } class NetStatus { var delegate: NetStatusDelegate? var reachability: Reachability? init() { // 构建检查器 setupReachability(hostName: "baidu.com", useClosures: true) } private func setupReachability(hostName hostName: String?, useClosures: Bool) { do { let reachability = try hostName == nil ? Reachability.reachabilityForInternetConnection() : Reachability(hostname: hostName!) self.reachability = reachability } catch ReachabilityError.FailedToCreateWithAddress(let address) { log.error("Unable to create\nReachability with address:\n\(address)") return } catch {} if (useClosures) { reachability?.whenReachable = { reachability in dispatch_async(dispatch_get_main_queue()) { self.delegate?.currentReachabilityStatus(reachability.currentReachabilityStatus) } } reachability?.whenUnreachable = { reachability in dispatch_async(dispatch_get_main_queue()) { self.delegate?.reachabilityChanged(Reachability.NetworkStatus.NotReachable) } } } else { NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability) } } func startListen() { do{ try reachability!.startNotifier() }catch{ log.warning("could not start reachability notifier") } } func stopListen() { NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil) reachability!.stopNotifier() reachability = nil } func reachabilityChanged(note: NSNotification) { let reachability = note.object as! Reachability if reachability.isReachable() { delegate?.reachabilityChanged(reachability.currentReachabilityStatus) } } deinit { stopListen() NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: reachability) } }
mit
fef7c67e7781b2dbd75f80140e65ab5a
30.904762
161
0.633955
5.642105
false
false
false
false
DevaLee/LYCSwiftDemo
LYCSwiftDemo/Classes/live/View/EmotionView/LYCEmotionView.swift
1
3287
// // LYCEmotionView.swift // LYCSwiftDemo // // Created by yuchen.li on 2017/6/12. // Copyright © 2017年 zsc. All rights reserved. // import UIKit private let kCellId = "kCellId" private let kCellName = "LYCEmotionCollectionViewCell" protocol LYCEmotionViewDelgate : class { func didSelectEmotion(emotion : LYCEmotionModel) } class LYCEmotionView: UIView { weak var delegate : LYCEmotionViewDelgate? var emotionClickCallBack : ((LYCEmotionModel) -> ())? fileprivate var emotionView : HYPageCollectionView! fileprivate lazy var emotionVM : LYCEmotionViewModel = LYCEmotionViewModel() override init(frame : CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LYCEmotionView { fileprivate func setupUI(){ let titles = ["热门","专属"] let style = HYTitleStyle() let layout = HYPageCollectionFlowLayout() layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.cols = 7 layout.rows = 3 let emoFrame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height) emotionView = HYPageCollectionView(frame: emoFrame, titles: titles, style: style, isTitleInTop: false, layout: layout) emotionView.datasoure = self emotionView.delegate = self emotionView.backgroundColor = UIColor.black //MARK:???出错 // NSStringFromClass(LYCEmotionCollectionViewCell.self) let nib = UINib.init(nibName: kCellName, bundle: nil) emotionView.register(nib: nib, identifier: kCellId) addSubview(emotionView) } } //MARK:- 数据源 extension LYCEmotionView : HYPageCollectionViewDataSource { func numberOfSections(pageCollectionView: HYPageCollectionView) -> Int { return emotionVM.package.count } func collection(_ pageCollectionView: HYPageCollectionView, numberOfItemsInSection section: Int) -> Int { let package = emotionVM.package[section] return package.emotionPack.count } func collection(_ pageCollectionView: HYPageCollectionView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! LYCEmotionCollectionViewCell let emotionPack = emotionVM.package[indexPath.section] as LYCEmotionPackage let emotionModel = emotionPack.emotionPack[indexPath.item] cell.emotionModel = emotionModel return cell } } //MARK:- 代理方法 extension LYCEmotionView : HYPageCollectionViewDelegate { func collection(_ pageCollectionView: HYPageCollectionView, collection: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { let emotionModel = emotionVM.package[indexPath.section].emotionPack[indexPath.item] // delegate?.didSelectEmotion(emotion: emotionModel) if let callBack = emotionClickCallBack { callBack(emotionModel) } } }
mit
7844d746358fc48f61c5aa5628a6ae69
33.659574
159
0.692142
4.951368
false
false
false
false
milseman/swift
test/SourceKit/InterfaceGen/gen_swift_module.swift
9
1575
import swift_mod_syn func f(s : inout [Int]) { s.sort() } // RUN: %empty-directory(%t.mod) // RUN: %swift -emit-module -o %t.mod/swift_mod.swiftmodule %S/Inputs/swift_mod.swift -parse-as-library // RUN: %sourcekitd-test -req=interface-gen -module swift_mod -- -I %t.mod > %t.response // RUN: diff -u %s.response %t.response // RUN: %sourcekitd-test -req=module-groups -module swift_mod -- -I %t.mod | %FileCheck -check-prefix=GROUP-EMPTY %s // GROUP-EMPTY: <GROUPS> // GROUP-EMPTY-NEXT: <\GROUPS> // RUN: %swift -emit-module -o %t.mod/swift_mod_syn.swiftmodule %S/Inputs/swift_mod_syn.swift -parse-as-library // RUN: %sourcekitd-test -req=interface-gen-open -module swift_mod_syn -- -I %t.mod == -req=cursor -pos=4:7 %s -- %s -I %t.mod | %FileCheck -check-prefix=SYNTHESIZED-USR1 %s // SYNTHESIZED-USR1: s:s17MutableCollectionPssAARzs012RandomAccessB0Rzs10Comparable7Elements8SequencePRpzlE4sortyyF::SYNTHESIZED::s:Sa // RUN: %sourcekitd-test -req=interface-gen-open -module Swift -synthesized-extension \ // RUN: == -req=find-usr -usr "s:s17MutableCollectionPssAARzs012RandomAccessB0Rzs10Comparable7Elements8SequencePRpzlE4sortyyF::SYNTHESIZED::s:Sa" | %FileCheck -check-prefix=SYNTHESIZED-USR2 %s // SYNTHESIZED-USR2-NOT: USR NOT FOUND // RUN: %sourcekitd-test -req=interface-gen-open -module Swift \ // RUN: == -req=find-usr -usr "s:s17MutableCollectionPssAARzs012RandomAccessB0Rzs10Comparable7Elements8SequencePRpzlE4sortyyF::SYNTHESIZED::s:Sa::SYNTHESIZED::USRDOESNOTEXIST" | %FileCheck -check-prefix=SYNTHESIZED-USR3 %s // SYNTHESIZED-USR3-NOT: USR NOT FOUND
apache-2.0
db5914e9e8805db57a2cb9e652b268af
59.576923
223
0.744127
2.922078
false
true
false
false
nesnes/MacMeters
MacMeters/SettingsWindow.swift
1
2884
// // SettingsWindow.swift // // // Created by Alexandre Brehmer on 09/08/2015. // // import Cocoa /// The setting window class control an handle the events from the SettingsWindow class SettingsWindow: NSWindowController, NSTableViewDataSource, NSTableViewDelegate { /// Reference to the colorWell object in the window @IBOutlet weak var colorWell: NSColorWell! /// Reference to the tableView object in the window @IBOutlet weak var keyTable: NSTableView! /// Array containing the list of values to display in the TableView var objects: NSMutableArray! = NSMutableArray() /// Equivalent to the init() method, called just before the window is shown override func windowDidLoad() { super.windowDidLoad() var keyList = SettingsManager.getKeyList() //get the list of the keys stored in the Settings for key in keyList{ self.objects.addObject(key) //add the key to the tableView } self.keyTable.reloadData() //update the tableView } /// Called when the user choosed a color in the color picked given by the colorWell /// The function convert the choosen color and save it as the value of the selected key @IBAction func colorPicked(sender: NSColorWell) { if (self.keyTable.numberOfSelectedRows > 0) { let selectedItem = self.objects.objectAtIndex(self.keyTable.selectedRow) as! String let color = colorWell.color var colorInt: Int = getIntColorFromFloat(color.redComponent, color.greenComponent, color.blueComponent) SettingsManager.setValue(selectedItem, value: colorInt) } } /// Need to be declared to satisfy the inheritance of NSTableViewDataSource func numberOfRowsInTableView(tableView: NSTableView) -> Int { return self.objects.count } /// Need to be declared to satisfy the inheritance of NSTableViewDelegate /// Select and initialize the view used as cell in the tableView func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var cellView = tableView.makeViewWithIdentifier("cell", owner: self) as! NSTableCellView cellView.textField!.stringValue = self.objects.objectAtIndex(row) as! String return cellView } /// Handle the selections in the tableView /// Update the colorWell to the stored color of the selected Key func tableViewSelectionDidChange(notification: NSNotification) { if (self.keyTable.numberOfSelectedRows > 0) { let selectedItem = self.objects.objectAtIndex(self.keyTable.selectedRow) as! String var color = SettingsManager.getColorValue(selectedItem) colorWell.color = color } } }
mit
4d3329351f32ae1f4198ccda9126a047
37.972973
115
0.676144
5.262774
false
false
false
false
pkx0128/UIKit
MScrollAndPageControll/MScrollAndPageControll/ViewController.swift
1
2337
// // ViewController.swift // MScrollAndPageControll // // Created by pankx on 2017/10/3. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class ViewController: UIViewController { var myScroll: UIScrollView! var mylabel: UILabel! var myPage: UIPageControl! override func viewDidLoad() { super.viewDidLoad() setupUI() setupPage() } } extension ViewController: UIScrollViewDelegate { func setupUI() { view.backgroundColor = UIColor.white myScroll = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) myScroll.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.5) myScroll.contentSize = CGSize(width: view.bounds.width * 5, height: view.bounds.height) myScroll.isPagingEnabled = true myScroll.showsHorizontalScrollIndicator = true myScroll.showsVerticalScrollIndicator = false myScroll.delegate = self view.addSubview(myScroll) for i in 0...4 { mylabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 40)) mylabel.center = CGPoint(x: view.bounds.width * (0.5 + CGFloat(i)), y: view.bounds.height * 0.2) mylabel.textAlignment = .center mylabel.text = "\(i + 1)" myScroll.addSubview(mylabel) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let p = Int(myScroll.contentOffset.x / myScroll.frame.width) myPage.currentPage = p } func setupPage() { myPage = UIPageControl(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 50)) myPage.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.9) myPage.numberOfPages = 5 myPage.currentPage = 0 myPage.pageIndicatorTintColor = UIColor.darkGray myPage.currentPageIndicatorTintColor = UIColor.black myPage.addTarget(self, action:#selector(pagechange) , for: .valueChanged) view.addSubview(myPage) } @objc func pagechange(sender: UIPageControl) { var fr = myScroll.frame fr.origin.x = fr.size.width * CGFloat(sender.currentPage) fr.origin.y = 0 myScroll.scrollRectToVisible(fr, animated: true) } }
mit
691866f3413671765b6320bbf4b4a10f
36.645161
112
0.643959
4.190305
false
false
false
false
hayksaakian/OverRustleiOS
OverRustleiOS/MLG.swift
1
2394
// // MLG.swift // OverRustleiOS // // Created by Hayk Saakian on 8/20/15. // Copyright (c) 2015 Maxwell Burggraf. All rights reserved. // import Foundation public class MLG: RustleStream { let PLAYER_EMBED_URL = "http://www.majorleaguegaming.com/player/embed/" let STREAM_API_URL = "http://streamapi.majorleaguegaming.com/service/streams/playback/%@?format=all" let stream_config_regex = "var playerConfig = (.+);" override func getStreamURL() -> NSURL { // warning: this is all assuming the stream exists and is live // step 1: figure out the mlgXYZ id // 1a: get the html containing the data var error: NSError? var url = NSURL(string: "\(PLAYER_EMBED_URL)\(channel)")! var res = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)! as String // 1b: pull the id from the json on the page let stream_id = findStreamId(res) if stream_id == nil { return NSURL() } // step 2: get the streams list url = NSURL(string:String(format: STREAM_API_URL, stream_id!))! let stream_api_data = NSData(contentsOfURL: url, options: nil, error: &error)! let streams = JSON(data: stream_api_data)["data"]["items"] for (index: String, subJson: JSON) in streams { if let source_url = subJson["url"].string { // find the first HLS playlist if source_url.hasSuffix("m3u8") { return NSURL(string: source_url)! } } } return NSURL() } func findStreamId(html: String) -> String? { let matches = matchesForRegexInText(stream_config_regex, text: html) if matches.count == 0 { return nil } var json_string = matches[0].substringWithRange(Range<String.Index>(start: advance(matches[0].startIndex, 19), end: advance(matches[0].endIndex, -1))) println("json string \(json_string)") if let dataFromString = json_string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { let json = JSON(data: dataFromString) let id = json["media"]["stream_name"].string return id } return nil } }
mit
76e7ec3d0dba12dce792c3860758b86d
33.2
158
0.576441
4.207381
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/model/TKColoredRoute.swift
1
1464
// // TKColoredRoute.swift // TripKit // // Created by Adrian Schoenig on 4/7/17. // Copyright © 2017 SkedGo. All rights reserved. // import Foundation import MapKit public class TKColoredRoute: NSObject { @objc public private(set) var path: [MKAnnotation] public let routeColor: TKColor? public let routeDashPattern: [NSNumber]? public let routeIsTravelled: Bool public let selectionIdentifier: String? @objc public init(path: [MKAnnotation], color: TKColor? = nil, dashPattern: [NSNumber]? = nil, isTravelled: Bool = true, identifier: String? = nil) { self.path = path routeColor = color routeDashPattern = dashPattern routeIsTravelled = isTravelled self.selectionIdentifier = identifier } @objc(initWithWaypoints:from:to:withColor:dashPattern:isTravelled:) public init(path: [MKAnnotation], from: Int, to: Int, color: TKColor?, dashPattern: [NSNumber]?, isTravelled: Bool) { let validTo = to > from ? to : path.count let first = max(0, min(from, validTo)) let last = min(path.count, max(from, validTo)) self.path = Array(path[first..<last]) routeColor = color routeDashPattern = dashPattern routeIsTravelled = isTravelled self.selectionIdentifier = nil } public func append(_ annotations: [MKAnnotation]) { path.append(contentsOf: annotations) } } extension TKColoredRoute: TKDisplayableRoute { public var routePath: [Any] { return path } }
apache-2.0
330687350c855ad1926bc45a5eb4189f
26.092593
151
0.699248
4.030303
false
false
false
false
acevest/acecode
learn/AcePlay/AcePlay.playground/Pages/TypeCasting.xcplaygroundpage/Contents.swift
1
3697
//: [Previous](@previous) import Foundation var str = "Hello, TypeCasting" //: [Next](@next) class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } // 这个数组将会被推断为MediaItem类型 let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] var movieCount = 0 var songCount = 0 for i in library { if i is Movie { movieCount += 1 } else if i is Song { songCount += 1 } } print("Media Library contains \(movieCount) Movies and \(songCount) Songs") print("------------------------------------------------------------------") // 向下转型 // 某类型的一个常量或变量可能在幕后实际上属于一个子类。当确定是这种情况时,可以尝试向下转到它的子类型,用类型转换操作符(as? 或 as!) // 因为向下转型可能会失败,类型转型操作符带有两种不同形式。条件形式as? 返回一个试图向下转成的类型的可选值。强制形式 as! 把试图向下转型和强制解包转换结果结合为一个操作 for m in library { if let movie = m as? Movie { print("Movie: \(movie.name) directed by \(movie.director)") } else if let song = m as? Song { print("Song: \(song.name) by \(song.artist)") } } // Any和AnyObject的类型转换 // Swift为不确定类型提供了两种特殊的类型别名 // 1. Any可以表示任何类型,包括函数类型 // 2. AnyObject可以表示任何类类型的实例 var things = [Any]() things.append(99) things.append(0) things.append(2.718281828459) things.append(0.0) things.append("Hello Swift") things.append((3, 4)) things.append(Movie(name: "Citizen Kane", director: "Orson Welles")) things.append( { (name: String) -> String in "Hello \(name)!" } ) print("------------------------------------------------------------------") for t in things { switch t { case 0 as Int: print("zero as Int") case 0 as Double: print("zero as Double") case let someInt as Int : print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0 : print("a positive double value of \(someDouble)") case is Double: print("some other double value that i do not want to print") case let someStr as String: print("a string value of \"\(someStr)\"") case let (x, y) as (Int, Int) : print("an (x, y) point at (\(x), \(y)") case let movie as Movie: print("a movie named \(movie.name) directed by \(movie.director)") case let strConverter as (String) -> String : print(strConverter("Ace")) default: print("Something else") } } // 注意:Any类型可以表示所有类型的值,包括可选类型 // Swift会在用Any类型来表示一个可选值的时候,给一个警告。如果确实想使用Any类型来承载可选值,可以使用as操作符显式转换为Any let optionalNumber: Int? = 3 // things.append(optionalNumber) // 会有warning things.append(optionalNumber as Any) // 不会有warning
gpl-2.0
36cb2e1686e83265aecf4bcc313b38a3
23.286822
89
0.609639
3.40914
false
false
false
false
rharri/swift-ios
JustDataTaskDemo/JustDataTaskDemo/ViewController.swift
1
2067
// // ViewController.swift // HTTPSessionDemo // // Created by Ryan Harri on 2016-11-04. // Copyright © 2016 Ryan Harri. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! private var posts = [Post]() override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.hidesWhenStopped = true DispatchQueue.main.async { self.activityIndicator.startAnimating() } // Get all posts and update the UI on completion Post.posts() { (posts) in guard let posts = posts else { return } self.posts = posts DispatchQueue.main.async { self.activityIndicator.stopAnimating() self.tableView.reloadData() } } // Get a single post, but don't update the UI Post.post(byPostID: 10) { (post) in guard let _ = post else { return } } // Get posts by user ID, but don't update the UI Post.posts(byUserID: 1) { (posts) in guard let _ = posts else { return } } } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) let post = posts[indexPath.row] cell.textLabel?.text = post.title cell.detailTextLabel?.text = post.body return cell } }
mit
07da3900eb7cc88d8ea90d7b7e767d9d
26.184211
100
0.563892
5.324742
false
false
false
false
panadaW/MyNews
MyWb/MyWb/Class/Controllers/Home/HomeTableViewController.swift
1
1743
// // HomeTableViewController.swift // MyWb // // Created by 王明申 on 15/10/8. // Copyright © 2015年 晨曦的Mac. All rights reserved. // import UIKit class HomeTableViewController: BaseTableViewController { var statues: [Status]? { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() if TokenModel.loadToken == nil { visitorview?.changViewInfo(true, imagename: "visitordiscover_feed_image_smallicon", message: "关注一些人,回这里看看有什么惊喜") return } prepareFortableView() loadstatus() } // MARK:注册cell private func prepareFortableView() { tableView.registerClass(homeCell.self, forCellReuseIdentifier: "Wcell") // 预估行高 tableView.estimatedRowHeight = 300 tableView.rowHeight = UITableViewAutomaticDimension // 取消分割线 tableView.separatorStyle = UITableViewCellSeparatorStyle.None } func loadstatus() { //加载用户数据 Status.loadstatus { [weak self](dataList, error) -> () in if error != nil { print(error) return } self?.statues = dataList } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statues?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Wcell", forIndexPath: indexPath) as! homeCell cell.status = statues![indexPath.row] return cell } }
mit
bdc823cdfcc6dd92b4b5215742c2819d
27.655172
120
0.627557
4.8739
false
false
false
false
superk589/DereGuide
DereGuide/Unit/View/UnitTableViewCell.swift
2
3240
// // UnitTableViewCell.swift // DereGuide // // Created by zzk on 16/7/28. // Copyright © 2016 zzk. All rights reserved. // import UIKit import SnapKit class UnitTableViewCell: UITableViewCell { var iconStackView: UIStackView! var cardIcons: [CGSSCardIconView] { return iconStackView.arrangedSubviews.compactMap { ($0 as? UnitSimulationCardView)?.icon } } // var appealStackView: UIStackView! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) prepareUI() } private func prepareUI() { var views = [UIView]() for _ in 0...5 { let view = UnitSimulationCardView() views.append(view) } iconStackView = UIStackView(arrangedSubviews: views) iconStackView.spacing = 5 iconStackView.distribution = .fillEqually iconStackView.isUserInteractionEnabled = false contentView.addSubview(iconStackView) // var labels = [UILabel]() // let colors = [Color.life, Color.vocal, Color.dance, Color.visual, UIColor.darkGray] // for i in 0...4 { // let label = UILabel() // label.font = UIFont.init(name: "menlo", size: 12) // label.textColor = colors[i] // labels.append(label) // } // // appealStackView = UIStackView(arrangedSubviews: labels) // appealStackView.spacing = 5 // appealStackView.distribution = .equalCentering // contentView.addSubview(appealStackView) iconStackView.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.greaterThanOrEqualTo(10) make.right.lessThanOrEqualTo(-10) // make the view as wide as possible make.right.equalTo(-10).priority(900) make.left.equalTo(10).priority(900) // make.bottom.equalTo(-10) make.width.lessThanOrEqualTo(96 * 6 + 25) make.centerX.equalToSuperview() } // appealStackView.snp.makeConstraints { (make) in // make.left.equalTo(10) // make.right.equalTo(-10) // make.top.equalTo(iconStackView.snp.bottom) // make.bottom.equalTo(-5) // } accessoryType = .disclosureIndicator } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareUI() } func setup(with unit: Unit) { for i in 0...5 { let member = unit[i] if let card = member.card, let view = iconStackView.arrangedSubviews[i] as? UnitSimulationCardView { view.icon.cardID = card.id if i != 5 { if card.skill != nil { view.skillLabel.text = "SLv.\((member.skillLevel))" } else { view.skillLabel.text = "n/a" } } else { view.skillLabel.text = "n/a" } view.potentialLabel.setup(with: member.potential) } } } }
mit
a839c115d171b24534ff3c4e988587bc
31.39
112
0.552948
4.58133
false
false
false
false
boqian2000/swift-algorithm-club
Fixed Size Array/FixedSizeArray.playground/Contents.swift
3
1161
//: Playground - noun: a place where people can play /* An unordered array with a maximum size. Performance is always O(1). */ struct FixedSizeArray<T> { private var maxSize: Int private var defaultValue: T private var array: [T] private (set) var count = 0 init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](repeating: defaultValue, count: maxSize) } subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } mutating func append(_ newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } mutating func removeAt(index: Int) -> T { assert(index >= 0) assert(index < count) count -= 1 let result = array[index] array[index] = array[count] array[count] = defaultValue return result } mutating func removeAll() { for i in 0..<count { array[i] = defaultValue } count = 0 } } var array = FixedSizeArray(maxSize: 5, defaultValue: 0) array.append(4) array.append(2) array[1] array.removeAt(index: 0) array.removeAll()
mit
215787b8617ba8ae0a0de6e22e5d506b
19.732143
61
0.637382
3.674051
false
false
false
false
ashfurrow/RxSwift
RxSwift/Observables/Observable+Time.swift
3
11503
// // Observable+Time.swift // Rx // // Created by Krunoslav Zaher on 3/22/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // MARK: throttle extension ObservableType { /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers and send events on. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func throttle<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Observable<E> { return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) } /** Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. `throttle` and `debounce` are synonyms. - parameter dueTime: Throttling duration for each element. - parameter scheduler: Scheduler to run the throttle timers and send events on. - returns: The throttled sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func debounce<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Observable<E> { return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) } } // MARK: sample extension ObservableType { /** Samples the source observable sequence using a samper observable sequence producing sampling ticks. Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** - parameter sampler: Sampling tick sequence. - returns: Sampled observable sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func sample<O: ObservableType>(sampler: O) -> Observable<E> { return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true) } /** Samples the source observable sequence using a samper observable sequence producing sampling ticks. Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. **In case there were no new elements between sampler ticks, last produced element is always sent to the resulting sequence.** - parameter sampler: Sampling tick sequence. - returns: Sampled observable sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func sampleLatest<O: ObservableType>(sampler: O) -> Observable<E> { return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: false) } } // MARK: interval /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - parameter period: Period for producing the values in the resulting sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence that produces a value after each period. */ @warn_unused_result(message="http://git.io/rxs.uo") public func interval<S: SchedulerType>(period: S.TimeInterval, _ scheduler: S) -> Observable<Int64> { return Timer(dueTime: period, period: period, scheduler: scheduler ) } // MARK: timer /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - parameter scheduler: Scheduler to run timers on. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ @warn_unused_result(message="http://git.io/rxs.uo") public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ period: S.TimeInterval, _ scheduler: S) -> Observable<Int64> { return Timer( dueTime: dueTime, period: period, scheduler: scheduler ) } /** Returns an observable sequence that produces a single value at the specified absolute due time, using the specified scheduler to run the timer. - parameter dueTime: Time interval after which to produce the value. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence that produces a value at due time. */ @warn_unused_result(message="http://git.io/rxs.uo") public func timer<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Observable<Int64> { return Timer( dueTime: dueTime, period: nil, scheduler: scheduler ) } // MARK: take extension ObservableType { /** Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func take<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S) -> Observable<E> { return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) } } // MARK: skip extension ObservableType { /** Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - parameter duration: Duration for skipping elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func skip<S: SchedulerType>(duration: S.TimeInterval, _ scheduler: S) -> Observable<E> { return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) } } // MARK: ignoreElements extension ObservableType { /** Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false. - returns: An observable sequence that skips all elements of the source sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func ignoreElements() -> Observable<E> { return filter { _ -> Bool in return false } } } // MARK: delaySubscription extension ObservableType { /** Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. - parameter dueTime: Relative time shift of the subscription. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: Time-shifted sequence. */ @warn_unused_result(message="http://git.io/rxs.uo") public func delaySubscription<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Observable<E> { return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) } } // MARK: buffer extension ObservableType { /** Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. - parameter timeSpan: Maximum time length of a buffer. - parameter count: Maximum element count of a buffer. - parameter scheduler: Scheduler to run buffering timers on. - returns: An observable sequence of buffers. */ @warn_unused_result(message="http://git.io/rxs.uo") public func buffer<S: SchedulerType>(timeSpan timeSpan: S.TimeInterval, count: Int, scheduler: S) -> Observable<[E]> { return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) } } // MARK: window extension ObservableType { /** Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. - parameter timeSpan: Maximum time length of a window. - parameter count: Maximum element count of a window. - parameter scheduler: Scheduler to run windowing timers on. - returns: An observable sequence of windows (instances of `Observable`). */ @warn_unused_result(message="http://git.io/rxs.uo") public func window<S: SchedulerType>(timeSpan timeSpan: S.TimeInterval, count: Int, scheduler: S) -> Observable<Observable<E>> { return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) } } // MARK: timeout extension ObservableType { /** Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter scheduler: Scheduler to run the timeout timer on. - returns: An observable sequence with a TimeoutError in case of a timeout. */ @warn_unused_result(message="http://git.io/rxs.uo") public func timeout<S: SchedulerType>(dueTime: S.TimeInterval, _ scheduler: S) -> Observable<E> { return Timeout(source: self.asObservable(), dueTime: dueTime, other: nil, scheduler: scheduler) } /** Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter other: Sequence to return in case of a timeout. - parameter scheduler: Scheduler to run the timeout timer on. - returns: The source sequence switching to the other sequence in case of a timeout. */ @warn_unused_result(message="http://git.io/rxs.uo") public func timeout<S: SchedulerType, O: ObservableConvertibleType where E == O.E>(dueTime: S.TimeInterval, other: O, _ scheduler: S) -> Observable<E> { return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) } }
mit
776347b0e377dcaa7f34d09fcba238fd
40.222222
316
0.709243
4.641243
false
false
false
false
OverSwift/ShadowEdge
ShadowEdgeExample/LIbrary/ShadowEdge/Classes/UIShadowSide.swift
1
750
// // UIShadowSide.swift // ShadowEdge // // Created by Sergiy Loza on 26.02.17. // Copyright © 2017 Sergiy Loza. All rights reserved. // import Foundation public struct UIShadowEdge : OptionSet { public typealias RawValue = UInt private var value: UInt public init(rawValue: UInt){ value = rawValue } public var rawValue: UInt { return value } public static let top: UIShadowEdge = UIShadowEdge(rawValue: 1 << 0) public static let right: UIShadowEdge = UIShadowEdge(rawValue: 1 << 1) public static let bottom: UIShadowEdge = UIShadowEdge(rawValue: 1 << 2) public static let left: UIShadowEdge = UIShadowEdge(rawValue: 1 << 3) public static let all: UIShadowEdge = [.top, .bottom, .right, .left] }
gpl-3.0
40f688925ee193cc4492fede984b8241
23.966667
73
0.691589
4.138122
false
false
false
false
seem-sky/ios-charts
Charts/Classes/Renderers/CombinedChartRenderer.swift
1
10838
// // CombinedChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class CombinedChartRenderer: ChartDataRendererBase, LineChartRendererDelegate, BarChartRendererDelegate, ScatterChartRendererDelegate, CandleStickChartRendererDelegate { private weak var _chart: CombinedChartView!; /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled = false; /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled = true; /// if set to true, all values of a stack are drawn individually, and not just their sum public var drawValuesForWholeStackEnabled = true; /// if set to true, a grey area is darawn behind each bar that indicates the maximum value public var drawBarShadowEnabled = true; internal var _renderers = [ChartDataRendererBase](); internal var _drawOrder: [CombinedChartView.DrawOrder] = [.Bar, .Line, .Candle, .Scatter]; public init(chart: CombinedChartView, animator: ChartAnimator, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); _chart = chart; createRenderers(); } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [ChartDataRendererBase](); for order in drawOrder { switch (order) { case .Bar: if (_chart.barData !== nil) { _renderers.append(BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Line: if (_chart.lineData !== nil) { _renderers.append(LineChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Candle: if (_chart.candleData !== nil) { _renderers.append(CandleStickChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; case .Scatter: if (_chart.scatterData !== nil) { _renderers.append(ScatterChartRenderer(delegate: self, animator: _animator, viewPortHandler: viewPortHandler)); } break; } } } public override func drawData(#context: CGContext) { for renderer in _renderers { renderer.drawData(context: context); } } public override func drawValues(#context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context); } } public override func drawExtras(#context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context); } } public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { for renderer in _renderers { renderer.drawHighlighted(context: context, indices: indices); } } /// Returns the sub-renderer object at the specified index. public func getSubRenderer(#index: Int) -> ChartDataRendererBase! { if (index >= _renderers.count || index < 0) { return nil; } else { return _renderers[index]; } } // MARK: - LineChartRendererDelegate public func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData! { return _chart.lineData; } public func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter { return _chart.fillFormatter; } public func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Float { return _chart.chartYMax; } public func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Float { return _chart.chartYMin; } public func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Float { return _chart.chartXMax; } public func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Float { return _chart.chartXMin; } public func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: - BarChartRendererDelegate public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! { return _chart.barData; } public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int { return _chart.maxVisibleValueCount; } public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Float { return _chart.chartXMax; } public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool { return drawHighlightArrowEnabled; } public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool { return drawValueAboveBarEnabled; } public func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool { return drawValuesForWholeStackEnabled; } public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool { return drawBarShadowEnabled; } public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool { return _chart.getAxis(axis).isInverted; } // MARK: - ScatterChartRendererDelegate public func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData! { return _chart.scatterData; } public func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Float { return _chart.chartYMax; } public func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Float { return _chart.chartYMin; } public func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Float { return _chart.chartXMax; } public func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Float { return _chart.chartXMin; } public func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: - CandleStickChartRendererDelegate public func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData! { return _chart.candleData; } public func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return _chart.getTransformer(which); } public func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter! { return _chart._defaultValueFormatter; } public func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Float { return _chart.chartYMax; } public func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Float { return _chart.chartYMin; } public func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Float { return _chart.chartXMax; } public func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Float { return _chart.chartXMin; } public func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int { return _chart.maxVisibleValueCount; } // MARK: Accessors /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// returns true if all values of a stack are drawn, and not just their sum public var isDrawValuesForWholeStackEnabled: Bool { return drawValuesForWholeStackEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [CombinedChartView.DrawOrder] { get { return _drawOrder; } set { if (newValue.count > 0) { _drawOrder = newValue; } } } }
apache-2.0
958bb5ed0ac845c3754b803d879f1fd0
30.32659
150
0.652611
5.817499
false
false
false
false
disklessGames/cartel
Cartel/Cartel/CardCell.swift
1
1613
import UIKit class CardCell: UICollectionViewCell { @IBOutlet var imageView: DraggableCard! @IBOutlet var countLabel: UILabel! @IBOutlet var player2: UILabel! override func prepareForReuse() { imageView.subviews.forEach { $0.removeFromSuperview() } } func configure(_ block: [Card], agents: Int, rotation: CGAffineTransform, isPlayable: Bool) { if let last = block.last, last.type == .road || last.type == .none { imageView.image = last.image } else { imageView.image = block.first?.image showStackedImages(block) } if agents > 0 { countLabel.text = "\(agents)" player2.text = "\(agents)" } else { countLabel.text = "" player2.text = "" } if isPlayable { layer.borderWidth = 1 layer.borderColor = UIColor.green.cgColor } else { layer.borderWidth = 0 } clipsToBounds = false imageView.transform = rotation } func showStackedImages(_ cards: [Card]) { for (index, card) in cards.enumerated() { let newLevel = UIImageView(image: card.image) if index > 0 { newLevel.frame = CGRect(x: CGFloat(-12 * (index - 1)), y: CGFloat(-20 * (index - 1)), width: frame.width, height: frame.height) imageView.addSubview(newLevel) } } } }
mit
39cc27da451b8e94eb53622d0b30aed1
30.019231
97
0.50093
4.858434
false
false
false
false
HC1058503505/HCCardView
HCCardView/CardView/HCCardViewStyle.swift
1
2223
// // HCCardViewStyle.swift // HCCardView // // Created by UltraPower on 2017/5/23. // Copyright © 2017年 UltraPower. All rights reserved. // import Foundation import UIKit /** 设置HCCardView的风格样式 * headerViewBGColor: 头部标题view背景颜色 * headerViewHeight: 头部标题view的高度 * headerViewItemsWidth: 标题的宽度 * headerViewItemsMargin: 标题间的间距 * itemNormalFontSize: 正常标题文字大小 * itemSelectedFontSize: 选中标题文字大小 * isGradient: 标题切换时文字大小,颜色,背景大小是否进行渐变 * itemSelectedColor: 选中标题的文字颜色 * itemNormalColor: 正常标题的文字颜色 * isShowLineView: 是否显示选择指示器 * lineViewColor: 选择指示器颜色 * isShowCoverView: 是否显示标题背景指示器 * coverViewColor: 标题背景指示器颜色 * emojiMinimumRows: 表情键盘最小行数 * emojiMinimumColumns: 表情键盘对消列数 */ struct HCCardViewStyle { /// 头部标题view背景颜色 var headerViewBGColor:UIColor = UIColor.white /// 头部标题view的高度 var headerViewHeight:CGFloat = 64.0 /// 标题的宽度 var headerViewItemsWidth:CGFloat = 45.0 /// 标题间的间距 var headerViewItemsMargin:CGFloat = 15.0 /// 正常标题文字大小 var itemNormalFontSize:CGFloat = 13.0 /// 选中标题文字大小 var itemSelectedFontSize:CGFloat = 16.0 /// 标题切换时文字大小,颜色,背景大小是否进行渐变 var isGradient:Bool = false /// 选中标题的文字颜色 var itemSelectedColor:UIColor = UIColor.red /// 正常标题的文字颜色 var itemNormalColor:UIColor = UIColor.white /// 是否显示选择指示器 var isShowLineView:Bool = true /// 选择指示器颜色 var lineViewColor:UIColor = UIColor.white /// 是否显示标题背景指示器 var isShowCoverView:Bool = true /// 标题背景指示器颜色 var coverViewColor:UIColor = UIColor(white: 0.5, alpha: 0.3) /// 表情键盘最小行数 var emojiMinimumRows: Int = 3 /// 表情键盘对消列数 var emojiMinimumColumns: Int = 3 }
mit
bc30b203ed0391add075133a9c718bb0
22.138889
64
0.69988
3.669604
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
MemorizeItForeverCore/MemorizeItForeverCore/Services/SetManagement/SetService.swift
1
2973
// // SetManager.swift // MemorizeItForever // // Created by Hadi Zamani on 4/12/16. // Copyright © 2016 SomeSimpleSolution. All rights reserved. // import Foundation final public class SetService: SetServiceProtocol { private var setDataAccess: SetDataAccessProtocol init(dataAccess: SetDataAccessProtocol){ setDataAccess = dataAccess } public func createDefaultSet(name: String) { do{ if try setDataAccess.fetchSetNumber() == 0{ var set = SetModel() set.name = name try setDataAccess.save(set) } } catch{ } } public func setUserDefaultSet() { setUserDefaultSet(force: false) } public func setUserDefaultSet(force: Bool) { do{ let sets = try setDataAccess.fetchAll() if sets.count > 0{ let defaults = UserDefaults.standard if defaults.object(forKey: Settings.defaultSet.rawValue) == nil || force{ changeSet(sets[0]) } } } catch{ } } public func save(_ setName: String){ do{ var set = SetModel() set.name = setName try setDataAccess.save(set) } catch{ } } public func edit(_ setModel: SetModel, setName: String){ do{ var set = SetModel() set.name = setName set.setId = setModel.setId try setDataAccess.edit(set) } catch{ } } public func delete(_ setModel: SetModel) -> Bool{ do{ if try ifSetIsdeletable(){ try setDataAccess.delete(setModel) changeDefaultSetIfNeeded(setModel) return true } else{ // TODO notify set is not deletable } } catch{ } return false } public func get() -> [SetModel]{ do{ return try setDataAccess.fetchAll() } catch{ } return [] } public func ifSetIsdeletable() throws -> Bool{ do{ return try setDataAccess.fetchSetNumber() > 1 } catch{ throw error } } public func changeSet(_ setModel: SetModel){ UserDefaults.standard.set(setModel.toDic(), forKey: Settings.defaultSet.rawValue) NotificationCenter.default.post(.setChanged, object: nil) } private func changeDefaultSetIfNeeded(_ set: SetModel){ let defaults = UserDefaults.standard if let setModel = defaults.getDefaultSetModel(){ if setModel.setId == set.setId{ setUserDefaultSet(force: true) } } } }
mit
8e9ffb5236d0026de8cc665546073a42
22.967742
89
0.500673
5.297683
false
false
false
false
aranasaurus/flingInvaders
flingInvaders/Background.swift
1
1576
// // Background.swift // flingInvaders // // Created by Ryan Arana on 7/12/14. // Copyright (c) 2014 aranasaurus.com. All rights reserved. // import SpriteKit class Background: SKNode { var bg: SKSpriteNode var bg2: SKSpriteNode let scrollSpeed = 10.0 init() { bg = SKSpriteNode(imageNamed: "bg_1_1.png") bg.zPosition = 0 bg.position = CGPoint(x:0, y:0) bg2 = bg.copy() as SKSpriteNode bg2.position = CGPoint(x:0, y:bg.size.height) super.init() self.position = CGPoint(x:bg.size.width/2, y:bg.size.height/2) /* Used to debug/see exactly how the scrolling is working. let label1 = SKLabelNode(fontNamed:"Chalkduster") label1.text = "1" label1.fontSize = 120 label1.position = CGPoint(x: 0.5, y: 0.5) label1.zPosition = 1 bg.addChild(label1) let label2 = SKLabelNode(fontNamed:"Chalkduster") label2.text = "2" label2.fontSize = 120 label2.position = CGPoint(x:0.5, y:0.5) label2.zPosition = 1 bg2.addChild(label2) */ self.addChild(bg) self.addChild(bg2) } func update(currentTime: NSTimeInterval) { bg.position = CGPoint(x: 0, y: bg.position.y - self.scrollSpeed) bg2.position = CGPoint(x: 0, y: bg2.position.y - self.scrollSpeed) if (bg.position.y <= -bg.size.height) { bg.position = CGPoint(x:0, y:bg.position.y+bg.size.height) bg2.position = CGPoint(x:0, y:bg.position.y+bg.size.height) } } }
apache-2.0
c214d4b6d34c097520d7772e13daee3b
27.654545
74
0.593274
3.317895
false
false
false
false
gpancio/iOS-Prototypes
GPUIKit/GPUIKit/Classes/RoundedTextFieldWithIcon.swift
1
2500
// // RoundedTextFieldWithIcon.swift // GPUIKit // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import UIKit /** A UITextField that has rounded ends and an optional image that will be shown to the left of the input text. By default, the background color is white with 80% transparency. */ @IBDesignable public class RoundedTextFieldWithIcon: UITextField { var imageView = UIImageView() @IBInspectable var image: UIImage? { set(image) { imageView.image = image setNeedsDisplay() } get { return imageView.image } } @IBInspectable var placeholderText: String? { get { return placeholder } set { placeholder = newValue let placeholderString = NSAttributedString(string: placeholder ?? "", attributes: [NSForegroundColorAttributeName: UIColor(white: 1.0, alpha: 1.0)]) attributedPlaceholder = placeholderString } } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public func layoutSubviews() { layer.cornerRadius = self.bounds.height / 2 super.layoutSubviews() } func setup() { layer.cornerRadius = bounds.height / 2 imageView.frame = CGRectMake(20, 0, 25, 25) leftView = imageView leftViewMode = UITextFieldViewMode.Always placeholderText = placeholder backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.2) } override public func leftViewRectForBounds(bounds: CGRect) -> CGRect { var boundsRect = super.leftViewRectForBounds(bounds) boundsRect.origin.x += self.bounds.height / 2 return boundsRect } override public func editingRectForBounds(bounds: CGRect) -> CGRect { var boundsRect = super.editingRectForBounds(bounds) boundsRect.origin.x += self.bounds.height / 2 return boundsRect } override public func textRectForBounds(bounds: CGRect) -> CGRect { var boundsRect = super.textRectForBounds(bounds) boundsRect.origin.x += self.bounds.height / 2 return boundsRect } }
mit
cea74d59552f685386d95fe64acee18a
25.03125
160
0.606242
5.20625
false
false
false
false
aleffert/dials
Desktop/Source/NetworkRequestStatusView.swift
1
6202
// // NetworkRequestStatusView.swift // Dials-Desktop // // Created by Akiva Leffert on 5/6/15. // // import Cocoa class NetworkRequestStatusGroupViewOwner : NSObject { @IBOutlet var view : NetworkRequestStatusGroupView! } class NetworkRequestStatusGroupView : NSView { @IBOutlet var contentLabel : NSTextField! } private func sortHeaderMap(_ map : [AnyHashable: Any]) -> [(String, String)] { let elements = (map as? [String:String] ?? [:]) let pairs = elements.sorted { $0.0 < $1.0 } return pairs } extension URLRequest { var sortedHeaders : [(String, String)] { return sortHeaderMap(allHTTPHeaderFields ?? [:]) } } extension URLResponse { var sortedHeaders : [(String, String)] { return sortHeaderMap( (self as? HTTPURLResponse)?.allHeaderFields ?? [:]) } } class NetworkRequestStatusView: NSView { typealias DataExtractor = (NetworkRequestInfo) -> [(String, NSAttributedString)] @IBOutlet var contentView : NSView! @IBOutlet var stackView : NSStackView! override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } func setup() { Bundle.main.loadNibNamed("NetworkRequestStatusView", owner: self, topLevelObjects: nil) addSubview(contentView) contentView.addConstraintsMatchingSuperviewBounds() } static func formatPairs(_ pairs : [(String, String)]) -> NSAttributedString { let result = NSMutableAttributedString() for (key, value) in pairs { if result.length > 0 { result.append(NSAttributedString(string: "\n")) } result.append(NSAttributedString(string : key, attributes : [ NSFontAttributeName : NSFont.boldSystemFont(ofSize: 10) ])) result.append(NSAttributedString(string : "\t")) result.append(NSAttributedString(string : value, attributes : [ NSFontAttributeName : NSFont.systemFont(ofSize: 10) ])) } return result } fileprivate static func requestMessageFields(_ info : NetworkRequestInfo) -> [(String, String)] { var fields : [(String, String)] = [] if let URL = info.request.url { let field = ("URL", URL.absoluteString) fields.append(field) } fields.append(contentsOf: [ ("Start Date", info.startTime.preciseDateString), ("End Date", info.endTime?.preciseDateString ?? "In Progress") ]) if let method = info.request.httpMethod { let field = ("Method", method) fields.append(field) } if let end = info.endTime { let field = ("Duration", "\(Int(end.timeIntervalSinceReferenceDate * 1000 - info.startTime.timeIntervalSinceReferenceDate * 1000))ms") fields.append(field) } if let size = info.request.httpBody?.count { let field = ("Size", "\(size) bytes") fields.append(field) } return fields } static func requestDataExtractor(_ info : NetworkRequestInfo) -> [(String, NSAttributedString)] { return [ ("Message", formatPairs(requestMessageFields(info))), ("Headers", formatPairs(info.request.sortedHeaders)) ] } fileprivate static func responseMessageFields(_ info : NetworkRequestInfo) -> [(String, String)]? { var fields : [(String, String)] = [] if let response = info.response as? HTTPURLResponse { let field = ("Status", "\(response.statusCode) (\(response.statusCodeDescription))") fields.append(field) } if let size = info.data?.length { let field = ("Size", "\(size) bytes") fields.append(field) } return fields.count > 0 ? fields : nil } static func responseDataExtractor(_ info : NetworkRequestInfo) -> [(String, NSAttributedString)] { var elements : [(String, NSAttributedString)] = [] if let response = info.response { let headers = response.sortedHeaders let pair = ("Headers", formatPairs(headers)) elements.append(pair) } if let error = info.error { let pair = ("Error", formatPairs([ ("Code", "\(error.code)"), ("Domain", error.domain), ("Description", error.localizedDescription) ])) elements.append(pair) } if let messageFields = responseMessageFields(info) { let pair = ("Message", formatPairs(messageFields)) elements.append(pair) } return elements } var dataExtractor : DataExtractor = {_ in [] } var requestInfo : NetworkRequestInfo? { didSet { let data = requestInfo.map { self.dataExtractor($0) } ?? [] while stackView.views.count > data.count { guard let view = stackView.views.last else { break } stackView.removeView(view) } while stackView.views.count < data.count { let owner = NetworkRequestStatusGroupViewOwner() Bundle.main.loadNibNamed("NetworkRequestStatusGroupView", owner: owner, topLevelObjects: nil) let body = owner.view let groupView = GroupContainerView(frame: CGRect.zero) groupView.translatesAutoresizingMaskIntoConstraints = false groupView.contentView = body stackView.addView(groupView, in: .top) } for ((title, content), view) in zip(data, stackView.views as! [GroupContainerView]) { view.title = title let groupView = view.contentView as! NetworkRequestStatusGroupView groupView.contentLabel.attributedStringValue = content } } } }
mit
d2a6bbb88e6d689cb82300fbc244c63e
33.455556
146
0.574976
5.151163
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/KYC/Client/KYCLimitsOverviewResponse.swift
1
1908
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit public struct KYCLimitsOverviewResponse: Equatable, Decodable { public struct Feature: Equatable, Decodable { public enum TimePeriod: String, Equatable, Decodable { case day = "DAY" case month = "MONTH" case year = "YEAR" } public struct PeriodicLimit: Equatable, Decodable { let value: MoneyValue? let period: TimePeriod } public let name: String public let enabled: Bool public let limit: PeriodicLimit? } public let limits: [Feature] } extension KYCLimitsOverview { init(tiers: KYC.UserTiers, features: [KYCLimitsOverviewResponse.Feature]) { let mappedFeatures = features .compactMap { rawFeature -> LimitedTradeFeature? in guard let identifier = LimitedTradeFeature.Identifier(rawValue: rawFeature.name) else { return nil } return LimitedTradeFeature( id: identifier, enabled: rawFeature.enabled, limit: rawFeature.limit?.mapToPeriodicLimit() ) } self.init( tiers: tiers, features: mappedFeatures ) } } extension KYCLimitsOverviewResponse.Feature.TimePeriod { func mapToTimePeriod() -> LimitedTradeFeature.TimePeriod { switch self { case .day: return .day case .month: return .month case .year: return .year } } } extension KYCLimitsOverviewResponse.Feature.PeriodicLimit { func mapToPeriodicLimit() -> LimitedTradeFeature.PeriodicLimit { LimitedTradeFeature.PeriodicLimit( value: value, period: period.mapToTimePeriod() ) } }
lgpl-3.0
bc0c07e5a4fd6d52e9c45c9fe9e3c767
25.859155
103
0.585212
5.267956
false
false
false
false
marwen86/NHtest
NHTest/NHTest/Manager/NHMovieCreator.swift
1
6602
// // NHMovieCreator.swift // NHTest // // Created by Mohamed Marouane YOUSSEF on 07/10/2017. // Copyright © 2017 Mohamed Marouane YOUSSEF. All rights reserved. // import Foundation import AVFoundation import UIKit public typealias CXEMovieMakerCompletion = (URL) -> Void typealias CXEMovieMakerUIImageExtractor = (AnyObject) -> UIImage? public class CXEImagesToVideo: NSObject{ var assetWriter:AVAssetWriter! var writeInput:AVAssetWriterInput! var bufferAdapter:AVAssetWriterInputPixelBufferAdaptor! var videoSettings:[String : Any]! var frameTime:CMTime! var fileURL:URL! var completionBlock: CXEMovieMakerCompletion? var movieMakerUIImageExtractor:CXEMovieMakerUIImageExtractor? public class func videoSettings(codec:String, width:Int, height:Int) -> [String: Any]{ if(Int(width) % 16 != 0){ print("warning: video settings width must be divisible by 16") } let videoSettings:[String: Any] = [AVVideoCodecKey: AVVideoCodecH264, AVVideoWidthKey: width, AVVideoHeightKey: height] return videoSettings } public init(videoSettings: [String: Any]) { super.init() let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let tempPath = paths[0] + "/exprotvideo.mp4" if(FileManager.default.fileExists(atPath: tempPath)){ guard (try? FileManager.default.removeItem(atPath: tempPath)) != nil else { print("remove path failed") return } } self.fileURL = URL(fileURLWithPath: tempPath) self.assetWriter = try! AVAssetWriter(url: self.fileURL, fileType: AVFileTypeQuickTimeMovie) self.videoSettings = videoSettings self.writeInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: videoSettings) assert(self.assetWriter.canAdd(self.writeInput), "add failed") self.assetWriter.add(self.writeInput) let bufferAttributes:[String: Any] = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32ARGB)] self.bufferAdapter = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: self.writeInput, sourcePixelBufferAttributes: bufferAttributes) self.frameTime = CMTimeMake(1, 1) } public func createMovieFrom(urls: [URL], withCompletion: @escaping CXEMovieMakerCompletion){ self.createMovieFromSource(images: urls as [AnyObject], extractor:{(inputObject:AnyObject) ->UIImage? in return UIImage(data: try! Data(contentsOf: inputObject as! URL))}, withCompletion: withCompletion) } public func createMovieFrom(images: [UIImage], withCompletion: @escaping CXEMovieMakerCompletion){ self.createMovieFromSource(images: images, extractor: {(inputObject:AnyObject) -> UIImage? in return inputObject as? UIImage}, withCompletion: withCompletion) } func createMovieFromSource(images: [AnyObject], extractor: @escaping CXEMovieMakerUIImageExtractor, withCompletion: @escaping CXEMovieMakerCompletion){ self.completionBlock = withCompletion self.assetWriter.startWriting() self.assetWriter.startSession(atSourceTime: kCMTimeZero) let mediaInputQueue = DispatchQueue(label: "mediaInputQueue") var i = 0 let frameNumber = images.count self.writeInput.requestMediaDataWhenReady(on: mediaInputQueue){ while(true){ if(i >= frameNumber){ break } if (self.writeInput.isReadyForMoreMediaData){ var sampleBuffer:CVPixelBuffer? autoreleasepool{ let img = extractor(images[i]) if img == nil{ i += 1 print("Warning: counld not extract one of the frames") //continue } sampleBuffer = self.newPixelBufferFrom(cgImage: img!.cgImage!) } if (sampleBuffer != nil){ if(i == 0){ self.bufferAdapter.append(sampleBuffer!, withPresentationTime: kCMTimeZero) }else{ let value = i - 1 let lastTime = CMTimeMake(Int64(value), self.frameTime.timescale) let presentTime = CMTimeAdd(lastTime, self.frameTime) self.bufferAdapter.append(sampleBuffer!, withPresentationTime: presentTime) } i = i + 1 } } } self.writeInput.markAsFinished() self.assetWriter.finishWriting { DispatchQueue.main.sync { self.completionBlock!(self.fileURL) } } } } func newPixelBufferFrom(cgImage:CGImage) -> CVPixelBuffer?{ let options:[String: Any] = [kCVPixelBufferCGImageCompatibilityKey as String: true, kCVPixelBufferCGBitmapContextCompatibilityKey as String: true] var pxbuffer:CVPixelBuffer? let frameWidth = self.videoSettings[AVVideoWidthKey] as! Int let frameHeight = self.videoSettings[AVVideoHeightKey] as! Int let status = CVPixelBufferCreate(kCFAllocatorDefault, frameWidth, frameHeight, kCVPixelFormatType_32ARGB, options as CFDictionary?, &pxbuffer) assert(status == kCVReturnSuccess && pxbuffer != nil, "newPixelBuffer failed") CVPixelBufferLockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pxdata = CVPixelBufferGetBaseAddress(pxbuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: pxdata, width: frameWidth, height: frameHeight, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pxbuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) assert(context != nil, "context is nil") context!.concatenate(CGAffineTransform.identity) context!.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)) CVPixelBufferUnlockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pxbuffer } }
mit
75eb60a130256ba0459ec7228b685666
44.524138
234
0.625511
5.487116
false
false
false
false
Bersaelor/KDTree
Sources/KDTree+Sequence.swift
1
2464
// // KDTree+Sequence.swift // // Copyright (c) 2020 mathHeartCode UG(haftungsbeschränkt) <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension KDTree: Sequence { public func makeIterator() -> AnyIterator<Element> { switch self { case .leaf: return AnyIterator { return nil } case let .node(left, value, _, right): var index = 0 var iteratorStruct = KDTreeIteratorStruct(left: left, right: right) return AnyIterator { if index == 0 { index = 1 return value } else if index == 1, let nextValue = iteratorStruct.leftIterator?.next() { return nextValue } else { index = 2 return iteratorStruct.rightIterator?.next() } } } } } fileprivate struct KDTreeIteratorStruct<Element: KDTreePoint> { let left: KDTree<Element> let right: KDTree<Element> init(left: KDTree<Element>, right: KDTree<Element>) { self.left = left self.right = right } lazy var leftIterator: AnyIterator<Element>? = { return self.left.makeIterator() }() lazy var rightIterator: AnyIterator<Element>? = { return self.right.makeIterator() }() }
mit
34ecf24aa26fffc8ec077faf473ff293
36.892308
90
0.638652
4.64717
false
false
false
false
xivol/Swift-CS333
playgrounds/extras/location/track-my-steps/track-my-steps/TrackingViewController.swift
3
2823
// // ViewController.swift // track-my-steps // // Created by Илья Лошкарёв on 13.04.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timeLabel: TimeLabel! @IBOutlet weak var pause: UIButton! @IBOutlet weak var stop: UIButton! unowned var trackManager = (UIApplication.shared.delegate as! AppDelegate).trackManager let stopwatch = Stopwatch() override func viewDidLoad() { super.viewDidLoad() stopwatch.delegate = timeLabel stopwatch.start() pause.layer.borderColor = pause.tintColor.cgColor pause.layer.borderWidth = 5 } @IBAction func playPause(_ sender: UIButton) { if trackManager.isRunning { trackManager.pause() stopwatch.pause() pause.setTitle("Resume", for: .normal) pause.tintColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1) print("pause") } else { trackManager.resume() stopwatch.resume() pause.setTitle("Pause", for: .normal) pause.tintColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) print("play") } } @IBAction func stopTracking(_ sender: UIButton) { trackManager.stop() stopwatch.stop() dismiss(animated: true) } } class RoundButton: UIButton { override var tintColor: UIColor! { didSet { layer.borderColor = tintColor.cgColor } } override var bounds: CGRect { didSet { layer.cornerRadius = bounds.width / 2 } } } class TimeLabel: UILabel, StopwatchDelegate { func stopwatchDidStart(stopwatch: Stopwatch) { updateTime(0, 0, 0) } func stopwatchDidStop(stopwatch: Stopwatch) {} func stopwatchDidPause(stopwatch: Stopwatch, at time: TimeInterval) {} func stopwatchDidResume(stopwatch: Stopwatch, at time: TimeInterval) {} func stopwatchTimeChanged(stopwatch: Stopwatch, elapsedTime: TimeInterval) { let minutes = UInt(elapsedTime / 60) let seconds = UInt(elapsedTime - TimeInterval(minutes * 60)) let milliseconds = UInt((elapsedTime - TimeInterval(minutes * 60 + seconds)) * 100) updateTime(minutes, seconds, milliseconds) } func updateTime(_ minutes: UInt, _ seconds: UInt, _ milliseconds: UInt) { let formatted = String(format:"%02d:%02d:%02d", minutes, seconds, milliseconds) let attributed = NSAttributedString(string: formatted, attributes: [ NSKernAttributeName : CGFloat(4) ]) self.attributedText = attributed } }
mit
b0ebebd41f3a817ae523c0688e53c067
30.088889
113
0.629378
4.594417
false
false
false
false
HarukaMa/iina
iina/KeyMapping.swift
1
3925
// // KeyMap.swift // iina // // Created by lhc on 12/12/2016. // Copyright © 2016 lhc. All rights reserved. // import Foundation class KeyMapping { static let prettyKeySymbol = [ "META": "⌘", "ENTER": "↩︎", "SHIFT": "⇧", "ALT": "⌥", "CTRL":"⌃", "SPACE": "␣", "BS": "⌫", "DEL": "⌦", "TAB": "⇥", "ESC": "⎋", "UP": "↑", "DOWN": "↓", "LEFT": "←", "RIGHT" : "→", "PGUP": "⇞", "PGDWN": "⇟", "HOME": "↖︎", "END": "↘︎", "PLAY": "▶︎\u{2006}❙\u{200A}❙", "PREV": "◀︎◀︎", "NEXT": "▶︎▶︎" ] var isIINACommand: Bool var key: String var action: [String] private var privateRawAction: String var rawAction: String { set { if newValue.hasPrefix("@iina") { privateRawAction = newValue.substring(from: newValue.index(newValue.startIndex, offsetBy: "@iina".characters.count)).trimmingCharacters(in: .whitespaces) action = rawAction.components(separatedBy: " ") isIINACommand = true } else { privateRawAction = newValue action = rawAction.components(separatedBy: " ") isIINACommand = false } } get { return privateRawAction } } var comment: String? var readableAction: String { get { let joined = action.joined(separator: " ") return isIINACommand ? ("@iina " + joined) : joined } } var prettyKey: String { get { return key .components(separatedBy: "+") .map { token -> String in let uppercasedToken = token.uppercased() if let symbol = KeyMapping.prettyKeySymbol[uppercasedToken] { return symbol } else if let origToken = KeyCodeHelper.reversedKeyMapForShift[token] { return KeyMapping.prettyKeySymbol["SHIFT"]! + origToken.uppercased() } else { return uppercasedToken } }.joined(separator: "") } } var prettyCommand: String { return KeyBindingTranslator.readableCommand(fromAction: action, isIINACommand: isIINACommand) } init(key: String, rawAction: String, isIINACommand: Bool = false, comment: String? = nil) { self.key = key self.privateRawAction = rawAction self.action = rawAction.components(separatedBy: " ") self.isIINACommand = isIINACommand self.comment = comment } static func parseInputConf(at path: String) -> [KeyMapping]? { let reader = StreamReader(path: path) var mapping: [KeyMapping] = [] var isIINACommand = false while var line: String = reader?.nextLine() { // ignore empty lines if line.isEmpty { continue } if line.hasPrefix("#@iina") { // extended syntax isIINACommand = true line = line.substring(from: line.index(line.startIndex, offsetBy: "#@iina".characters.count)) } else if line.hasPrefix("#") { // igore comment continue } // remove inline comment if let sharpIndex = line.characters.index(of: "#") { line = line.substring(to: sharpIndex) } // split let splitted = line.characters.split(separator: " ", maxSplits: 1) if splitted.count < 2 { return nil } let key = String(splitted[0]).trimmingCharacters(in: .whitespaces) let action = String(splitted[1]).trimmingCharacters(in: .whitespaces) mapping.append(KeyMapping(key: key, rawAction: action, isIINACommand: isIINACommand, comment: nil)) } return mapping } static func generateConfData(from mappings: [KeyMapping]) -> String { var result = "# Generated by IINA\n\n" mappings.forEach { km in if km.isIINACommand { result += "#@iina \(km.key) \(km.action.joined(separator: " "))\n" } else { result += "\(km.key) \(km.action.joined(separator: " "))\n" } } return result } }
gpl-3.0
3606384d9a84f10d62a651740aefacac
26.169014
161
0.585537
3.932722
false
false
false
false
charmaex/favorite-movies
FavoriteMovies/AppDelegate.swift
1
6119
// // AppDelegate.swift // FavoriteMovies // // Created by Jan Dammshäuser on 17.02.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.jandamm.FavoriteMovies" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("FavoriteMovies", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
gpl-3.0
c983c81ac086f206df12a14a85493656
54.099099
291
0.720569
5.92062
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/Type Casting.xcplaygroundpage/Contents.swift
1
3188
//: ## Type Casting //: ---- //: [Previous](@previous) import Foundation var result = "" //: Defining a Class Hierarchy for Type Casting class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] print(library) //: Checking Type var movieCount = 0 var songCount = 0 for item in library { if item is Movie { ++movieCount } else if item is Song { ++songCount } } print("Media library contains \(movieCount) movies and \(songCount) songs") //: Downcasting for item in library { if let movie = item as? Movie { result = "Movie: '\(movie.name)', dir. \(movie.director)" } else if let song = item as? Song { result = "Song: '\(song.name)', by \(song.artist)" } else { result = "Another class" } print(result) } //: Type Casting for AnyObject let someObjects: [AnyObject] = [ Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"), Movie(name: "Moon", director: "Duncan Jones"), Movie(name: "Alien", director: "Ridley Scott") ] print(someObjects) for object in someObjects { let movie = object as! Movie print("Movie: '\(movie.name)', dir. \(movie.director)") } for movie in someObjects as! [Movie] { print("Movie: '\(movie.name)', dir. \(movie.director)") } //: Type Casting for Any var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({ (name: String) -> String in "Hello, \(name)" }) print(things) for thing in things { switch thing { case 0 as Int: result = "zero as an Int" case 0 as Double: result = "zero as a Double" case let someInt as Int: result = "an integer value of \(someInt)" case let someDouble as Double where someDouble > 0: result = "a positive double value of \(someDouble)" case is Double: result = "some other double value that I don't want to print" case let someString as String: result = "a string value of \"\(someString)\"" case let (x, y) as (Double, Double): result = "an (x, y) point at \(x), \(y)" case let movie as Movie: result = "a movie called '\(movie.name)', dir. \(movie.director)" case let stringConverter as String -> String: result = stringConverter("Michael") default: result = "something else" } print(result) } //: [Next](@next)
mit
b306b08486a8925e58aae2502985e9d0
23.713178
75
0.617315
3.582022
false
false
false
false
duliodenis/v
V/V/Controllers/NewGroupViewController.swift
1
7048
// // NewGroupViewController.swift // V // // Created by Dulio Denis on 6/18/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit import CoreData class NewGroupViewController: UIViewController { var context: NSManagedObjectContext? // set this when we create our new instance of our VC var chatCreationDelegate: ChatCreationDelegate? private let subjectField = UITextField() private let characterNumberLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() // set the title title = "New Group" // set the background color view.backgroundColor = UIColor.whiteColor() // set the left and right Navigation Bar Button Items to Cancel & Next navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancel") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: "next") // update Next button updateNextButton(forCharacterCount: 0) // set the placeholder and delegate for our Subject Field variable subjectField.placeholder = "Group Subject" subjectField.delegate = self // falsify the automatic constraints so we can use Auto Layout subjectField.translatesAutoresizingMaskIntoConstraints = false // add the subjectField to the view view.addSubview(subjectField) // update the character label updateCharacterLabel(forCharacterCount: 0) // setup the characterNumberLabel view characterNumberLabel.textColor = UIColor.grayColor() characterNumberLabel.translatesAutoresizingMaskIntoConstraints = false // add the characterNumberLabel as a sub view to our subject field subjectField.addSubview(characterNumberLabel) // add an Auto Layout constrainable light gray bottom border let bottomBorder = UIView() bottomBorder.backgroundColor = UIColor.lightGrayColor() bottomBorder.translatesAutoresizingMaskIntoConstraints = false // make bottom border a sub view of the subject field subjectField.addSubview(bottomBorder) // Setup Auto Layout Constraints let constraints: [NSLayoutConstraint] = [ // specify that subject field be top constrained to the top layout but not flush - border of 20 subjectField.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 20), // leading achor should be constrained to the margin's leading anchor subjectField.leadingAnchor.constraintEqualToAnchor(view.layoutMarginsGuide.leadingAnchor), // and trailing anchor is constrained to the view's trailing anchor subjectField.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor), // constrain the width of the bottom border to be equal to the subject field's width bottomBorder.widthAnchor.constraintEqualToAnchor(subjectField.widthAnchor), // the bottom anchor of the bottom border be constrained to the subject field's bottom anchor bottomBorder.bottomAnchor.constraintEqualToAnchor(subjectField.bottomAnchor), // the leading anchor to the subject field's leading anchor bottomBorder.leadingAnchor.constraintEqualToAnchor(subjectField.leadingAnchor), // and the bottom border can have a constant height of 1 point bottomBorder.heightAnchor.constraintEqualToConstant(1), // finally, the character number label center is equal to the subject field's center characterNumberLabel.centerYAnchor.constraintEqualToAnchor(subjectField.centerYAnchor), // and its trailing anchor is constrained to the subject field's margin trailing anchor characterNumberLabel.trailingAnchor.constraintEqualToAnchor(subjectField.layoutMarginsGuide.trailingAnchor) ] // Activate our constraints NSLayoutConstraint.activateConstraints(constraints) } // MARK: Navigation Bar Item Methods func cancel() { // dismiss VC when cancel is tapped in the Nav bar dismissViewControllerAnimated(true, completion: nil) } func next() { // when next is tapped in the Nav bar ensure we have a context and a Chat instance guard let context = context, chat = NSEntityDescription.insertNewObjectForEntityForName("Chat", inManagedObjectContext: context) as? Chat else { return } // update the chat name with the subject field chat.name = subjectField.text // instantiate the New Group Participants VC and set the context and chat let newGroupParticipantsVC = NewGroupParticipantsViewController() newGroupParticipantsVC.context = context newGroupParticipantsVC.chat = chat // the chat creation delegate is the All Chats VC newGroupParticipantsVC.chatCreationDelegate = chatCreationDelegate // Push our New Group Participants VC onto the Navigation Stack navigationController?.pushViewController(newGroupParticipantsVC, animated: true) } // MARK: Update UI Elements Method func updateCharacterLabel(forCharacterCount length: Int) { // Maximum number (25) minus the character count characterNumberLabel.text = String(25 - length) } func updateNextButton(forCharacterCount length: Int) { // if the length is zero then grey out and disable if length == 0 { navigationItem.rightBarButtonItem?.tintColor = UIColor.lightGrayColor() navigationItem.rightBarButtonItem?.enabled = false } else { // otherwise enable navigationItem.rightBarButtonItem?.tintColor = view.tintColor navigationItem.rightBarButtonItem?.enabled = true } } } extension NewGroupViewController: UITextFieldDelegate { // user has changed the text and we need to determine if we should allow func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // get current character count let currentCharacterCount = textField.text?.characters.count ?? 0 // and the new length let newLength = currentCharacterCount + string.characters.count - range.length // if the new length is greater than the maximum length (25) if newLength <= 25 { // update the character label updateCharacterLabel(forCharacterCount: newLength) // update the next button updateNextButton(forCharacterCount: newLength) // and replace the specified range return true } // otherwise keep the old text return false } }
mit
e85a78e1383f6a90ccee2ea8cec5d07d
42.770186
161
0.682702
6.143854
false
false
false
false
cityos/CoreCityOS
Sources/DeviceData.swift
2
1972
/* This source file is part of the CoreCityOS open source project Copyright (c) 2016 CityOS LLC Licensed under Apache License v2.0 See https://cityos.io/ios/LICENCE.txt for license information */ /** Describes info data for one hardware device. Most common data is: * `id` - id of the device, most commonly ipv6 address * `model` - model type of the device * `schema` - schema version * `version` - device version In addition to these properties, `DeviceData` can also store additional data with `deviceInfo` dictionary. */ public struct DeviceData { /// Device ID public var deviceID: String /// Device model public var model: String? /// Device schema public var schema: String? /// Device version public var version: String? /// Provides additional object for storing any device specific info public var deviceInfo: [String: AnyObject] /// Creates `DeviceData` public init(deviceID: String, model: String? = nil, schema: String? = nil, version: String? = nil, deviceInfo info: [String: AnyObject] = [:]) { self.deviceID = deviceID self.model = model self.schema = schema self.version = version self.deviceInfo = info } } extension DeviceData : Equatable { } public func == (lhs: DeviceData, rhs: DeviceData) -> Bool { return lhs.deviceID == rhs.deviceID } extension DeviceData { public var description: String { return "Device:\n--- \nID: \(deviceID) \nModel: \(model ?? "Not specified")\nVersion: \(version ?? "Not specified")\nAdditional info: \(deviceInfo ?? [:])" } } //MARK: Subscript extensions for DeviceData structure extension DeviceData { public subscript(key: String) -> AnyObject? { get { return deviceInfo[key] } set { deviceInfo[key] = newValue } } }
apache-2.0
f4ebc00c2fbd116e5b2ba41431e85398
24.947368
163
0.619168
4.461538
false
false
false
false
eduarenas/GithubClient
Sources/GitHubClient/HTTPService/HTTPService+Rx.swift
1
2784
// // HTTPService+Rx.swift // GithubClient // // Created by Eduardo Arenas on 7/18/17. // Copyright © 2017 GameChanger. All rights reserved. // import Foundation import RxSwift extension HTTPService { func get(url: String, query: [String: CustomStringConvertible]? = nil, headers: [String: CustomStringConvertible]? = nil) -> Observable<(Data, HTTPURLResponse)> { return Observable.create({ (observer) -> Disposable in self.get(url: url, query: query, headers: headers, completion: self.notifyObserver(observer)) return Disposables.create() }) } func post(url: String, query: [String: CustomStringConvertible]? = nil, data: Data? = nil, headers: [String: CustomStringConvertible]? = nil) -> Observable<(Data, HTTPURLResponse)> { return Observable.create({ (observer) -> Disposable in self.post(url: url, query: query, data: data, headers: headers, completion: self.notifyObserver(observer)) return Disposables.create() }) } func patch(url: String, query: [String: CustomStringConvertible]? = nil, data: Data? = nil, headers: [String: CustomStringConvertible]? = nil) -> Observable<(Data, HTTPURLResponse)> { return Observable.create({ (observer) -> Disposable in self.patch(url: url, query: query, data: data, headers: headers, completion: self.notifyObserver(observer)) return Disposables.create() }) } func put(url: String, query: [String: CustomStringConvertible]? = nil, data: Data? = nil, headers: [String: CustomStringConvertible]? = nil) -> Observable<(Data, HTTPURLResponse)> { return Observable.create({ (observer) -> Disposable in self.put(url: url, query: query, data: data, headers: headers, completion: self.notifyObserver(observer)) return Disposables.create() }) } func delete(url: String, query: [String: CustomStringConvertible]? = nil, headers: [String: CustomStringConvertible]? = nil) -> Observable<(Data, HTTPURLResponse)> { return Observable.create({ (observer) -> Disposable in self.delete(url: url, query: query, headers: headers, completion: self.notifyObserver(observer)) return Disposables.create() }) } private func notifyObserver(_ observer: AnyObserver<(Data, HTTPURLResponse)>) -> CompletionHandler { return { (data, response, error) in if let error = error { observer.onError(error) } else if let data = data, let response = response as? HTTPURLResponse { observer.onNext((data, response)) observer.onCompleted() } else { observer.onError(HTTPServiceError.invalidResponse) } } } }
mit
882b56037697f2e54f588b2888bff61d
35.618421
113
0.647143
4.510535
false
false
false
false
HenvyLuk/BabyGuard
BabyGuard/CVCalendar/CVCalendarContentViewController.swift
1
8282
// // CVCalendarContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public typealias Identifier = String public class CVCalendarContentViewController: UIViewController { // MARK: - Constants public let previous = "Previous" public let presented = "Presented" public let following = "Following" // MARK: - Public Properties public unowned let calendarView: CalendarView public let scrollView: UIScrollView public var presentedMonthView: MonthView public var bounds: CGRect { return scrollView.bounds } public var currentPage = 1 public var pageChanged: Bool { get { return currentPage == 1 ? false : true } } public var pageLoadingEnabled = true public var presentationEnabled = true public var lastContentOffset: CGFloat = 0 public var direction: CVScrollDirection = .None public init(calendarView: CalendarView, frame: CGRect) { self.calendarView = calendarView scrollView = UIScrollView(frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: NSDate()) presentedMonthView.updateAppearance(frame) super.init(nibName: nil, bundle: nil) scrollView.contentSize = CGSize(width: frame.width * 3, height: frame.height) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.layer.masksToBounds = true scrollView.pagingEnabled = true scrollView.delegate = self } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI Refresh extension CVCalendarContentViewController { public func updateFrames(frame: CGRect) { if frame != CGRect.zero { scrollView.frame = frame scrollView.removeAllSubviews() scrollView.contentSize = CGSize(width: frame.size.width * 3, height: frame.size.height) } calendarView.hidden = false } } //MARK: - Month Refresh extension CVCalendarContentViewController { public func refreshPresentedMonth() { for weekV in presentedMonthView.weekViews { for dayView in weekV.dayViews { removeCircleLabel(dayView) dayView.setupDotMarker() dayView.preliminarySetup() dayView.supplementarySetup() dayView.topMarkerSetup() } } } } // MARK: Delete circle views (in effect refreshing the dayView circle) extension CVCalendarContentViewController { func removeCircleLabel(dayView: CVCalendarDayView) { for each in dayView.subviews { if each is UILabel { continue } else if each is CVAuxiliaryView { continue } else { each.removeFromSuperview() } } } } //MARK: Delete dot views (in effect refreshing the dayView dots) extension CVCalendarContentViewController { func removeDotViews(dayView: CVCalendarDayView) { for each in dayView.subviews { if each is CVAuxiliaryView && each.frame.height == 13 { each.removeFromSuperview() } } } } // MARK: - Abstract methods /// UIScrollViewDelegate extension CVCalendarContentViewController: UIScrollViewDelegate { } // Convenience API. extension CVCalendarContentViewController { public func performedDayViewSelection(dayView: DayView) { } public func togglePresentedDate(date: NSDate) { } public func presentNextView(view: UIView?) { } public func presentPreviousView(view: UIView?) { } public func updateDayViews(hidden: Bool) { } } // MARK: - Contsant conversion extension CVCalendarContentViewController { public func indexOfIdentifier(identifier: Identifier) -> Int { let index: Int switch identifier { case previous: index = 0 case presented: index = 1 case following: index = 2 default: index = -1 } return index } } // MARK: - Date management extension CVCalendarContentViewController { public func dateBeforeDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month -= 1 let dateBefore = calendar.dateFromComponents(components)! return dateBefore } public func dateAfterDate(date: NSDate) -> NSDate { let components = Manager.componentsForDate(date) let calendar = NSCalendar.currentCalendar() components.month += 1 let dateAfter = calendar.dateFromComponents(components)! return dateAfter } public func matchedMonths(lhs: Date, _ rhs: Date) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month } public func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week) } public func matchedDays(lhs: Date, _ rhs: Date) -> Bool { return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day) } } // MARK: - AutoLayout Management extension CVCalendarContentViewController { private func layoutViews(views: [UIView], toHeight height: CGFloat) { scrollView.frame.size.height = height var superStack = [UIView]() var currentView: UIView = calendarView while let currentSuperview = currentView.superview where !(currentSuperview is UIWindow) { superStack += [currentSuperview] currentView = currentSuperview } for view in views + superStack { view.layoutIfNeeded() } } public func updateHeight(height: CGFloat, animated: Bool) { if calendarView.shouldAnimateResizing { var viewsToLayout = [UIView]() if let calendarSuperview = calendarView.superview { for constraintIn in calendarSuperview.constraints { if let firstItem = constraintIn.firstItem as? UIView, let _ = constraintIn.secondItem as? CalendarView { viewsToLayout.append(firstItem) } } } for constraintIn in calendarView.constraints where constraintIn.firstAttribute == NSLayoutAttribute.Height { constraintIn.constant = height if animated { UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { self.layoutViews(viewsToLayout, toHeight: height) }) { _ in self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize self.presentedMonthView.updateInteractiveView() } } else { layoutViews(viewsToLayout, toHeight: height) presentedMonthView.updateInteractiveView() presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } break } } } public func updateLayoutIfNeeded() { if presentedMonthView.potentialSize.height != scrollView.bounds.height { updateHeight(presentedMonthView.potentialSize.height, animated: true) } else if presentedMonthView.frame.size != scrollView.frame.size { presentedMonthView.frame.size = presentedMonthView.potentialSize presentedMonthView.updateInteractiveView() } } } extension UIView { public func removeAllSubviews() { for subview in subviews { subview.removeFromSuperview() } } }
apache-2.0
772070012f00c0be47dde999b32e6593
30.018727
99
0.614586
5.607312
false
false
false
false
fxm90/GradientProgressBar
Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Diff.swift
1
4207
import Foundation struct Difference<A> { enum Which { case first case second case both } let elements: [A] let which: Which } func diff<A: Hashable>(_ fst: [A], _ snd: [A]) -> [Difference<A>] { var idxsOf = [A: [Int]]() fst.enumerated().forEach { idxsOf[$1, default: []].append($0) } let sub = snd.enumerated().reduce((overlap: [Int: Int](), fst: 0, snd: 0, len: 0)) { sub, sndPair in (idxsOf[sndPair.element] ?? []) .reduce((overlap: [Int: Int](), fst: sub.fst, snd: sub.snd, len: sub.len)) { innerSub, fstIdx in var newOverlap = innerSub.overlap newOverlap[fstIdx] = (sub.overlap[fstIdx - 1] ?? 0) + 1 if let newLen = newOverlap[fstIdx], newLen > sub.len { return (newOverlap, fstIdx - newLen + 1, sndPair.offset - newLen + 1, newLen) } return (newOverlap, innerSub.fst, innerSub.snd, innerSub.len) } } let (_, fstIdx, sndIdx, len) = sub if len == 0 { let fstDiff = fst.isEmpty ? [] : [Difference(elements: fst, which: .first)] let sndDiff = snd.isEmpty ? [] : [Difference(elements: snd, which: .second)] return fstDiff + sndDiff } else { let fstDiff = diff(Array(fst.prefix(upTo: fstIdx)), Array(snd.prefix(upTo: sndIdx))) let midDiff = [Difference(elements: Array(fst.suffix(from: fstIdx).prefix(len)), which: .both)] let lstDiff = diff(Array(fst.suffix(from: fstIdx + len)), Array(snd.suffix(from: sndIdx + len))) return fstDiff + midDiff + lstDiff } } let minus = "−" let plus = "+" private let figureSpace = "\u{2007}" struct Hunk { let fstIdx: Int let fstLen: Int let sndIdx: Int let sndLen: Int let lines: [String] var patchMark: String { let fstMark = "\(minus)\(fstIdx + 1),\(fstLen)" let sndMark = "\(plus)\(sndIdx + 1),\(sndLen)" return "@@ \(fstMark) \(sndMark) @@" } // Semigroup static func +(lhs: Hunk, rhs: Hunk) -> Hunk { return Hunk( fstIdx: lhs.fstIdx + rhs.fstIdx, fstLen: lhs.fstLen + rhs.fstLen, sndIdx: lhs.sndIdx + rhs.sndIdx, sndLen: lhs.sndLen + rhs.sndLen, lines: lhs.lines + rhs.lines ) } // Monoid init(fstIdx: Int = 0, fstLen: Int = 0, sndIdx: Int = 0, sndLen: Int = 0, lines: [String] = []) { self.fstIdx = fstIdx self.fstLen = fstLen self.sndIdx = sndIdx self.sndLen = sndLen self.lines = lines } init(idx: Int = 0, len: Int = 0, lines: [String] = []) { self.init(fstIdx: idx, fstLen: len, sndIdx: idx, sndLen: len, lines: lines) } } func chunk(diff diffs: [Difference<String>], context ctx: Int = 4) -> [Hunk] { func prepending(_ prefix: String) -> (String) -> String { return { prefix + $0 + ($0.hasSuffix(" ") ? "¬" : "") } } let changed: (Hunk) -> Bool = { $0.lines.contains(where: { $0.hasPrefix(minus) || $0.hasPrefix(plus) }) } let (hunk, hunks) = diffs .reduce((current: Hunk(), hunks: [Hunk]())) { cursor, diff in let (current, hunks) = cursor let len = diff.elements.count switch diff.which { case .both where len > ctx * 2: let hunk = current + Hunk(len: ctx, lines: diff.elements.prefix(ctx).map(prepending(figureSpace))) let next = Hunk( fstIdx: current.fstIdx + current.fstLen + len - ctx, fstLen: ctx, sndIdx: current.sndIdx + current.sndLen + len - ctx, sndLen: ctx, lines: (diff.elements.suffix(ctx) as ArraySlice<String>).map(prepending(figureSpace)) ) return (next, changed(hunk) ? hunks + [hunk] : hunks) case .both where current.lines.isEmpty: let lines = (diff.elements.suffix(ctx) as ArraySlice<String>).map(prepending(figureSpace)) let count = lines.count return (current + Hunk(idx: len - count, len: count, lines: lines), hunks) case .both: return (current + Hunk(len: len, lines: diff.elements.map(prepending(figureSpace))), hunks) case .first: return (current + Hunk(fstLen: len, lines: diff.elements.map(prepending(minus))), hunks) case .second: return (current + Hunk(sndLen: len, lines: diff.elements.map(prepending(plus))), hunks) } } return changed(hunk) ? hunks + [hunk] : hunks }
mit
584b5b997cd9870d220c576cb1b4c21c
32.632
107
0.602284
3.445902
false
false
false
false
nextforce/PhoneNumberKit
PhoneNumberKit/PartialFormatter.swift
1
16440
// // PartialFormatter.swift // PhoneNumberKit // // Created by Roy Marmelstein on 29/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation /// Partial formatter public final class PartialFormatter { private let phoneNumberKit: PhoneNumberKit weak var metadataManager: MetadataManager? weak var parser: PhoneNumberParser? weak var regexManager: RegexManager? public convenience init(phoneNumberKit: PhoneNumberKit = PhoneNumberKit(), defaultRegion: String = PhoneNumberKit.defaultRegionCode(), withPrefix: Bool = true, maxDigits: Int? = nil) { self.init(phoneNumberKit: phoneNumberKit, regexManager: phoneNumberKit.regexManager, metadataManager: phoneNumberKit.metadataManager, parser: phoneNumberKit.parseManager.parser, defaultRegion: defaultRegion, withPrefix: withPrefix, maxDigits: maxDigits) } init(phoneNumberKit: PhoneNumberKit, regexManager: RegexManager, metadataManager: MetadataManager, parser: PhoneNumberParser, defaultRegion: String, withPrefix: Bool = true, maxDigits: Int? = nil) { self.phoneNumberKit = phoneNumberKit self.regexManager = regexManager self.metadataManager = metadataManager self.parser = parser self.defaultRegion = defaultRegion updateMetadataForDefaultRegion() self.withPrefix = withPrefix self.maxDigits = maxDigits } public var defaultRegion: String { didSet { updateMetadataForDefaultRegion() } } public var maxDigits: Int? func updateMetadataForDefaultRegion() { guard let metadataManager = metadataManager else { return } if let regionMetadata = metadataManager.territoriesByCountry[defaultRegion] { defaultMetadata = metadataManager.mainTerritory(forCode: regionMetadata.countryCode) } else { defaultMetadata = nil } currentMetadata = defaultMetadata } var defaultMetadata: MetadataTerritory? var currentMetadata: MetadataTerritory? var prefixBeforeNationalNumber = String() var shouldAddSpaceAfterNationalPrefix = false var withPrefix = true // MARK: Status public var currentRegion: String { get { return currentMetadata?.codeID ?? defaultRegion } } public func nationalNumber(from rawNumber: String) -> String { guard let parser = parser else { return rawNumber } let iddFreeNumber = extractIDD(rawNumber) var nationalNumber = parser.normalizePhoneNumber(iddFreeNumber) if prefixBeforeNationalNumber.count > 0 { nationalNumber = extractCountryCallingCode(nationalNumber) } nationalNumber = extractNationalPrefix(nationalNumber) if let maxDigits = maxDigits { let extra = nationalNumber.count - maxDigits if extra > 0 { nationalNumber = String(nationalNumber.dropLast(extra)) } } return nationalNumber } // MARK: Lifecycle /** Formats a partial string (for use in TextField) - parameter rawNumber: Unformatted phone number string - returns: Formatted phone number string. */ public func formatPartial(_ rawNumber: String) -> String { // Always reset variables with each new raw number resetVariables() guard isValidRawNumber(rawNumber) else { return rawNumber } var nationalNumber = self.nationalNumber(from: rawNumber) if let formats = availableFormats(nationalNumber) { if let formattedNumber = applyFormat(nationalNumber, formats: formats) { nationalNumber = formattedNumber } else { for format in formats { if let template = createFormattingTemplate(format, rawNumber: nationalNumber) { nationalNumber = applyFormattingTemplate(template, rawNumber: nationalNumber) break } } } } var finalNumber = String() if prefixBeforeNationalNumber.count > 0 { finalNumber.append(prefixBeforeNationalNumber) } if shouldAddSpaceAfterNationalPrefix && prefixBeforeNationalNumber.count > 0 && prefixBeforeNationalNumber.last != PhoneNumberConstants.separatorBeforeNationalNumber.first { finalNumber.append(PhoneNumberConstants.separatorBeforeNationalNumber) } if nationalNumber.count > 0 { finalNumber.append(nationalNumber) } if finalNumber.last == PhoneNumberConstants.separatorBeforeNationalNumber.first { finalNumber = String(finalNumber[..<finalNumber.index(before: finalNumber.endIndex)]) } return finalNumber } // MARK: Formatting Functions internal func resetVariables() { currentMetadata = defaultMetadata prefixBeforeNationalNumber = String() shouldAddSpaceAfterNationalPrefix = false } // MARK: Formatting Tests internal func isValidRawNumber(_ rawNumber: String) -> Bool { do { // In addition to validPhoneNumberPattern, // accept any sequence of digits and whitespace, prefixed or not by a plus sign let validPartialPattern = "[++]?(\\s*\\d)+\\s*$|\(PhoneNumberPatterns.validPhoneNumberPattern)" let validNumberMatches = try regexManager?.regexMatches(validPartialPattern, string: rawNumber) let validStart = regexManager?.stringPositionByRegex(PhoneNumberPatterns.validStartPattern, string: rawNumber) if validNumberMatches?.count == 0 || validStart != 0 { return false } } catch { return false } return true } internal func isNanpaNumberWithNationalPrefix(_ rawNumber: String) -> Bool { guard currentMetadata?.countryCode == 1 && rawNumber.count > 1 else { return false } let firstCharacter: String = String(describing: rawNumber.first) let secondCharacter: String = String(describing: rawNumber[rawNumber.index(rawNumber.startIndex, offsetBy: 1)]) return (firstCharacter == "1" && secondCharacter != "0" && secondCharacter != "1") } func isFormatEligible(_ format: MetadataPhoneNumberFormat) -> Bool { guard let phoneFormat = format.format else { return false } do { let validRegex = try regexManager?.regexWithPattern(PhoneNumberPatterns.eligibleAsYouTypePattern) if validRegex?.firstMatch(in: phoneFormat, options: [], range: NSMakeRange(0, phoneFormat.count)) != nil { return true } } catch {} return false } // MARK: Formatting Extractions func extractIDD(_ rawNumber: String) -> String { var processedNumber = rawNumber do { if let internationalPrefix = currentMetadata?.internationalPrefix { let prefixPattern = String(format: PhoneNumberPatterns.iddPattern, arguments: [internationalPrefix]) let matches = try regexManager?.matchedStringByRegex(prefixPattern, string: rawNumber) if let m = matches?.first { let startCallingCode = m.count let index = rawNumber.index(rawNumber.startIndex, offsetBy: startCallingCode) processedNumber = String(rawNumber[index...]) prefixBeforeNationalNumber = String(rawNumber[..<index]) } } } catch { return processedNumber } return processedNumber } func extractNationalPrefix(_ rawNumber: String) -> String { var processedNumber = rawNumber var startOfNationalNumber: Int = 0 if isNanpaNumberWithNationalPrefix(rawNumber) { prefixBeforeNationalNumber.append("1 ") } else { do { if let nationalPrefix = currentMetadata?.nationalPrefixForParsing { let nationalPrefixPattern = String(format: PhoneNumberPatterns.nationalPrefixParsingPattern, arguments: [nationalPrefix]) let matches = try regexManager?.matchedStringByRegex(nationalPrefixPattern, string: rawNumber) if let m = matches?.first { startOfNationalNumber = m.count } } } catch { return processedNumber } } let index = rawNumber.index(rawNumber.startIndex, offsetBy: startOfNationalNumber) processedNumber = String(rawNumber[index...]) prefixBeforeNationalNumber.append(String(rawNumber[..<index])) return processedNumber } func extractCountryCallingCode(_ rawNumber: String) -> String { var processedNumber = rawNumber if rawNumber.isEmpty { return rawNumber } var numberWithoutCountryCallingCode = String() if prefixBeforeNationalNumber.isEmpty == false && prefixBeforeNationalNumber.first != "+" { prefixBeforeNationalNumber.append(PhoneNumberConstants.separatorBeforeNationalNumber) } if let potentialCountryCode = parser?.extractPotentialCountryCode(rawNumber, nationalNumber: &numberWithoutCountryCallingCode), potentialCountryCode != 0 { processedNumber = numberWithoutCountryCallingCode currentMetadata = metadataManager?.mainTerritory(forCode: potentialCountryCode) let potentialCountryCodeString = String(potentialCountryCode) prefixBeforeNationalNumber.append(potentialCountryCodeString) prefixBeforeNationalNumber.append(" ") } else if withPrefix == false && prefixBeforeNationalNumber.isEmpty { let potentialCountryCodeString = String(describing: currentMetadata?.countryCode) prefixBeforeNationalNumber.append(potentialCountryCodeString) prefixBeforeNationalNumber.append(" ") } return processedNumber } func availableFormats(_ rawNumber: String) -> [MetadataPhoneNumberFormat]? { guard let regexManager = regexManager else { return nil } var tempPossibleFormats = [MetadataPhoneNumberFormat]() var possibleFormats = [MetadataPhoneNumberFormat]() if let metadata = currentMetadata { let formatList = metadata.numberFormats for format in formatList { if isFormatEligible(format) { tempPossibleFormats.append(format) if let leadingDigitPattern = format.leadingDigitsPatterns?.last { if (regexManager.stringPositionByRegex(leadingDigitPattern, string: String(rawNumber)) == 0) { possibleFormats.append(format) } } else { if (regexManager.matchesEntirely(format.pattern, string: String(rawNumber))) { possibleFormats.append(format) } } } } if possibleFormats.count == 0 { possibleFormats.append(contentsOf: tempPossibleFormats) } return possibleFormats } return nil } func applyFormat(_ rawNumber: String, formats: [MetadataPhoneNumberFormat]) -> String? { guard let regexManager = regexManager else { return nil } for format in formats { if let pattern = format.pattern, let formatTemplate = format.format { let patternRegExp = String(format: PhoneNumberPatterns.formatPattern, arguments: [pattern]) do { let matches = try regexManager.regexMatches(patternRegExp, string: rawNumber) if matches.count > 0 { if let nationalPrefixFormattingRule = format.nationalPrefixFormattingRule { let separatorRegex = try regexManager.regexWithPattern(PhoneNumberPatterns.prefixSeparatorPattern) let nationalPrefixMatches = separatorRegex.matches(in: nationalPrefixFormattingRule, options: [], range: NSMakeRange(0, nationalPrefixFormattingRule.count)) if nationalPrefixMatches.count > 0 { shouldAddSpaceAfterNationalPrefix = true } } let formattedNumber = regexManager.replaceStringByRegex(pattern, string: rawNumber, template: formatTemplate) return formattedNumber } } catch { } } } return nil } func createFormattingTemplate(_ format: MetadataPhoneNumberFormat, rawNumber: String) -> String? { guard var numberPattern = format.pattern, let numberFormat = format.format, let regexManager = regexManager else { return nil } guard numberPattern.range(of: "|") == nil else { return nil } do { let characterClassRegex = try regexManager.regexWithPattern(PhoneNumberPatterns.characterClassPattern) numberPattern = characterClassRegex.stringByReplacingMatches(in: numberPattern, withTemplate: "\\\\d") let standaloneDigitRegex = try regexManager.regexWithPattern(PhoneNumberPatterns.standaloneDigitPattern) numberPattern = standaloneDigitRegex.stringByReplacingMatches(in: numberPattern, withTemplate: "\\\\d") if let tempTemplate = getFormattingTemplate(numberPattern, numberFormat: numberFormat, rawNumber: rawNumber) { if let nationalPrefixFormattingRule = format.nationalPrefixFormattingRule { let separatorRegex = try regexManager.regexWithPattern(PhoneNumberPatterns.prefixSeparatorPattern) let nationalPrefixMatch = separatorRegex.firstMatch(in: nationalPrefixFormattingRule, options: [], range: NSMakeRange(0, nationalPrefixFormattingRule.count)) if nationalPrefixMatch != nil { shouldAddSpaceAfterNationalPrefix = true } } return tempTemplate } } catch { } return nil } func getFormattingTemplate(_ numberPattern: String, numberFormat: String, rawNumber: String) -> String? { guard let regexManager = regexManager else { return nil } do { let matches = try regexManager.matchedStringByRegex(numberPattern, string: PhoneNumberConstants.longPhoneNumber) if let match = matches.first { if match.count < rawNumber.count { return nil } var template = regexManager.replaceStringByRegex(numberPattern, string: match, template: numberFormat) template = regexManager.replaceStringByRegex("9", string: template, template: PhoneNumberConstants.digitPlaceholder) return template } } catch { } return nil } func applyFormattingTemplate(_ template: String, rawNumber: String) -> String { var rebuiltString = String() var rebuiltIndex = 0 for character in template { if character == PhoneNumberConstants.digitPlaceholder.first { if rebuiltIndex < rawNumber.count { let nationalCharacterIndex = rawNumber.index(rawNumber.startIndex, offsetBy: rebuiltIndex) rebuiltString.append(rawNumber[nationalCharacterIndex]) rebuiltIndex += 1 } } else { if rebuiltIndex < rawNumber.count { rebuiltString.append(character) } } } if rebuiltIndex < rawNumber.count { let nationalCharacterIndex = rawNumber.index(rawNumber.startIndex, offsetBy: rebuiltIndex) let remainingNationalNumber: String = String(rawNumber[nationalCharacterIndex...]) rebuiltString.append(remainingNationalNumber) } rebuiltString = rebuiltString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return rebuiltString } }
mit
f2797afb76eefffc7357b4a6bc7f4967
42.484127
261
0.634909
6.142377
false
false
false
false
newtonstudio/cordova-plugin-device
imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYStickersDataSource.swift
1
3213
// // IMGLYStickersDataSource.swift // imglyKit // // Created by Sascha Schwabbauer on 23/03/15. // Copyright (c) 2015 9elements GmbH. All rights reserved. // import UIKit public protocol IMGLYStickersDataSourceDelegate: class, UICollectionViewDataSource { var stickers: [IMGLYSticker] { get } } public class IMGLYStickersDataSource: NSObject, IMGLYStickersDataSourceDelegate { public let stickers: [IMGLYSticker] override init() { let stickerFiles = [ "sticker01", "sticker02", "sticker03", "sticker04", "sticker05", "sticker06", "sticker07", "sticker08", "sticker09", "sticker10", "sticker11", "sticker12", "sticker13", "sticker14", "sticker15", "sticker16", "sticker17", "sticker18", "sticker19", "sticker20", "sticker21", "sticker22", "sticker23", "sticker24", "sticker25", "sticker26", "sticker27", "sticker28", "sticker29", "sticker30", "sticker31", "sticker32", "sticker33", //"glasses_nerd", //"glasses_normal", //"glasses_shutter_green", //"glasses_shutter_yellow", //"glasses_sun", //"hat_cap", //"hat_party", //"hat_sherrif", //"hat_zylinder", //"heart", //"mustache_long", //"mustache1", //"mustache2", //"mustache3", //"pipe", //"snowflake", //"star" ] stickers = stickerFiles.map { file in if let image = UIImage(named: file, inBundle: NSBundle(forClass: IMGLYStickersDataSource.self), compatibleWithTraitCollection: nil) { let thumbnail = UIImage(named: file + "_thumbnail", inBundle: NSBundle(forClass: IMGLYStickersDataSource.self), compatibleWithTraitCollection: nil) return IMGLYSticker(image: image, thumbnail: thumbnail) } return nil }.filter { $0 != nil }.map { $0! } super.init() } init(stickers: [IMGLYSticker]) { self.stickers = stickers super.init() } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return stickers.count } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StickersCollectionViewCellReuseIdentifier, forIndexPath: indexPath) as! IMGLYStickerCollectionViewCell cell.imageView.image = stickers[indexPath.row].thumbnail ?? stickers[indexPath.row].image return cell } }
apache-2.0
d42a0d8617184a2a4858dac71939edf4
29.894231
175
0.545285
5.258592
false
false
false
false
kreeger/pinwheel
Classes/ViewControllers/PinsViewController.swift
1
3159
// // Pinwheel // PinsViewController.swift // Copyright (c) 2014 Ben Kreeger. All rights reserved. // import UIKit class PinsViewController: UIViewController { var refreshControl: UIRefreshControl! var collectionView: UICollectionView! var layout: UICollectionViewFlowLayout! var logoutItem: UIBarButtonItem! var dataSource: PinsDataSource! init(dataSource: PinsDataSource) { self.dataSource = dataSource super.init(nibName: nil, bundle: nil) dataSource.delegate = self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func loadView() { view = UIView(frame: UIScreen.mainScreen().bounds) layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 1 collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout) collectionView.delegate = self collectionView.alwaysBounceVertical = true collectionView.backgroundColor = UIColor(white: 0.95, alpha: 1.0) view.addSubview(collectionView) refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshControlPulled:", forControlEvents: .ValueChanged) collectionView.addSubview(refreshControl) } override func viewDidLoad() { super.viewDidLoad() title = "Pins" logoutItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: "logoutItemTapped:") self.navigationItem.leftBarButtonItem = logoutItem collectionView.dataSource = dataSource dataSource.registerCells(collectionView) refreshControl.beginRefreshing() refreshControl.sendActionsForControlEvents(.ValueChanged) } } // MARK: Actions extension PinsViewController { func logoutItemTapped(sender: UIControl) { let flowHandler = LogoutFlowHandler() flowHandler.logout() } func refreshControlPulled(sender: UIRefreshControl) { DDLogSwift.logWarn("\(reflect(self).summary).\(__FUNCTION__)") dataSource.fetchPins { sender.endRefreshing() } } } // MARK: PinsDataSourceDelegate extension PinsViewController: PinsDataSourceDelegate { func dataSource(dataSource: PinsDataSource, didRefreshWithPins pins: [PinboardPost]) { dispatch_async(dispatch_get_main_queue()) { self.collectionView.reloadData() } } } // MARK: UICollectionViewDelegate extension PinsViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { println("Hello, there.") } } // MARK: UICollectionViewDelegateFlowLayout extension PinsViewController: UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize { let size = dataSource.sizeForItemAtIndexPath(indexPath, constrainedToWidth: self.view.frame.size.width) return size } }
mit
d102bf897f8fe9a420706de935cc694f
31.56701
172
0.703071
5.532399
false
false
false
false
ohadh123/MuscleUp-
MuscleUp!/UIApplication+isFirstLaunch.swift
1
670
// // File.swift // MuscleUp! // // Created by Etai Koronyo on 6/8/17. // Copyright © 2017 Ohad Koronyo. All rights reserved. // import Foundation import UIKit private var firstLaunch : Bool = false extension UIApplication { static func isFirstLaunch() -> Bool { let firstLaunchFlag = "isFirstLaunchFlag" let isFirstLaunch = UserDefaults.standard.string(forKey: firstLaunchFlag) == nil if (isFirstLaunch) { firstLaunch = isFirstLaunch UserDefaults.standard.set("false", forKey: firstLaunchFlag) UserDefaults.standard.synchronize() } return firstLaunch || isFirstLaunch } }
apache-2.0
9236e7add135ff985713eaf685b42aeb
24.730769
88
0.657698
4.46
false
false
false
false
gvzq/iOS-Twitter
Twitter/TweetDetailViewController.swift
1
4451
// // TweetDetailViewController.swift // Twitter // // Created by Gerardo Vazquez on 2/23/16. // Copyright © 2016 Gerardo Vazquez. All rights reserved. // import UIKit class TweetDetailViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! @IBOutlet weak var favoriteCountLabel: UILabel! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var replyButton: UIButton! var tweet: Tweet! override func viewDidLoad() { super.viewDidLoad() profileImageView.setImageWithURL(NSURL(string: (tweet.user?.profileImageUrl)!)!) let tapGesture = UITapGestureRecognizer(target: self, action: "profileImageTapped:") profileImageView.addGestureRecognizer(tapGesture) profileImageView.userInteractionEnabled = true nameLabel.text = tweet.user?.name tweetTextLabel.text = tweet.text timeStampLabel.text = tweet.createdAtString favoriteCountLabel.text = "\(tweet.favouritesCount!)" retweetCountLabel.text = "\(tweet.retweetCount!)" if (tweet.favorited!) { favoriteButton.setImage(UIImage(named: "favorite_on"), forState: .Normal) favoriteCountLabel.textColor = UIColor.redColor() } else { favoriteButton.setImage(UIImage(named: "favorite"), forState: .Normal) favoriteCountLabel.textColor = UIColor.grayColor() } if (tweet.retweeted!) { retweetButton.setImage(UIImage(named: "retweet_on"), forState: .Normal) retweetCountLabel.textColor = UIColor(red:0.1, green:0.72, blue:0.6, alpha:1.0) } else { retweetButton.setImage(UIImage(named: "retweet"), forState: .Normal) retweetCountLabel.textColor = UIColor.grayColor() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onFavorite(sender: AnyObject) { if (tweet.favorited!) { TwitterClient.sharedInstance.destroyFavorite(tweet.id!) tweet.favouritesCount!-- tweet.favorited = false favoriteButton.setImage(UIImage(named: "favorite"), forState: .Normal) favoriteCountLabel.textColor = UIColor.grayColor() } else { TwitterClient.sharedInstance.createFavorite(tweet.id!) tweet.favouritesCount!++ tweet.favorited = true favoriteButton.setImage(UIImage(named: "favorite_on"), forState: .Normal) favoriteCountLabel.textColor = UIColor.redColor() } favoriteCountLabel.text = "\(tweet.favouritesCount!)" } @IBAction func onRetweet(sender: AnyObject) { if (tweet.retweeted!) { TwitterClient.sharedInstance.unretweet(tweet.id!) tweet.retweetCount!-- tweet.retweeted = false retweetButton.setImage(UIImage(named: "retweet"), forState: .Normal) retweetCountLabel.textColor = UIColor.grayColor() } else { TwitterClient.sharedInstance.retweet(tweet.id!) tweet.retweetCount!++ tweet.retweeted = true retweetButton.setImage(UIImage(named: "retweet_on"), forState: .Normal) retweetCountLabel.textColor = UIColor(red:0.1, green:0.72, blue:0.6, alpha:1.0) } retweetCountLabel.text = "\(tweet.retweetCount!)" } @IBAction func onReply(sender: AnyObject) { } func profileImageTapped(gesture: UIGestureRecognizer) { self.performSegueWithIdentifier("segueForProfile", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueForReply" { let replyViewController = segue.destinationViewController as! ReplyViewController replyViewController.screenName = tweet.user?.screenName } if segue.identifier == "segueForProfile" { let profileViewController = segue.destinationViewController as! ProfileViewController profileViewController.user = tweet.user } } }
apache-2.0
38dc6548ec0307829fb14019467b6aa9
39.09009
97
0.656854
5.192532
false
false
false
false
marceloreina/github-app-viper
GitHubApp/GitHubApp/TopSwiftReposPresenter.swift
1
1692
// // TopSwiftReposPresenter.swift // GitHubApp // // Created by Marcelo Reina on 02/03/17. // Copyright © 2017 Marcelo Reina. All rights reserved. // import Foundation class TopSwiftReposPresenter { weak var view: TopSwiftReposView! var interactor: TopSwiftReposUseCase! var router: TopSwiftReposWireframe! fileprivate static let initialPageNumber = 1 fileprivate var currentPage = TopSwiftReposPresenter.initialPageNumber fileprivate var topSwiftRepos = [Repo]() } extension TopSwiftReposPresenter: TopSwiftReposInteractorOutput { internal func topSwiftReposFetched(repos: [Repo]) { if repos.isEmpty && topSwiftRepos.isEmpty { view!.showNoContent() } else { topSwiftRepos.append(contentsOf: repos) view?.showRepos(repos: topSwiftRepos.flatMap({ (repo) -> RepoDisplayData? in return RepoDisplayData(from: repo) })) } } internal func failedToLoadRepos() { view.showNoContent() } } extension TopSwiftReposPresenter: TopSwiftReposPresentation { internal func loadRepoList() { currentPage = TopSwiftReposPresenter.initialPageNumber topSwiftRepos.removeAll() interactor.fetchTopSwiftRepos(pageNumber: currentPage) } internal func loadMoreRepos() { currentPage += 1 interactor.fetchTopSwiftRepos(pageNumber: currentPage) } internal func repoSelected(at index: Int) { guard index >= 0 && !topSwiftRepos.isEmpty && index < topSwiftRepos.count else { return } router.presentRepoPullRequests(for: topSwiftRepos[index]) } }
mit
283a2e9c4d2586bb3f65dab03235a702
28.666667
88
0.670609
5.203077
false
false
false
false
shedowHuang/MyLiveBySwift
MyLiveBySwift/MyLiveBySwift/Classes/Home/View/RecommendGameView.swift
1
2263
// // RecommendGameView.swift // MyLiveBySwift // // Created by Shedows on 2017/1/4. // Copyright © 2017年 Shedows. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { // MARK:-定义属性 var groups : [AnchorGroup]?{ didSet { groups?.remove(at: 0) groups?.remove(at: 0) //添加 更多 选项 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups?.append(moreGroup) // 刷新 collectView.reloadData() } } // MARK: 控件属性 @IBOutlet weak var collectView: UICollectionView! // MARK: 系统回调函数 override func awakeFromNib() { super.awakeFromNib() // 设置该控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // 注册cell collectView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } // MARK:- 快速创建的类方法 extension RecommendGameView{ static func recommendGameView() -> RecommendGameView{ return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendGameView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.group = groups![indexPath.item] //cell.backgroundColor = (indexPath.item) % 2 == 0 ? UIColor.purple : UIColor.red return cell } }
mit
60d8876d105ce271f780b2b665aaf73f
26.662338
126
0.640376
5.107914
false
false
false
false
qianqian2/ocStudy1
faqtheEnd/faqtheEnd/NetworkTools.swift
2
2261
// // NetworkTools.swift // AFNetworkingWraping // // Created by arang on 16/12/4. // Copyright © 2016年 arang. All rights reserved. // import AFNetworking enum RequestType : String { case Get case Post } class NetworkTools: AFHTTPSessionManager { static let shareInstance : NetworkTools = { let tools = NetworkTools() tools.responseSerializer.acceptableContentTypes?.insert("text/html") return tools }() } extension NetworkTools { func request(requestType : RequestType, url : String, parameters : [String : Any], resultBlock : @escaping([String : Any]?, Error?) -> ()) { // 成功闭包 let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in resultBlock(responseObj as? [String : Any], nil) } // 失败的闭包 let failureBlock = { (task: URLSessionDataTask?, error: Error) in resultBlock(nil, error) } // Get 请求 if requestType == .Get { get(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } // Post 请求 if requestType == .Post { post(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } } } extension NetworkTools { func request(requestType : RequestType, url : String, parameters : [String : Any], succeed : @escaping([String : Any]?) -> (), failure : @escaping(Error?) -> ()) { // 成功闭包 let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in succeed(responseObj as? [String : Any]) } // 失败的闭包 let failureBlock = { (task: URLSessionDataTask?, error: Error) in failure(error) } // Get 请求 if requestType == .Get { get(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } // Post 请求 if requestType == .Post { post(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } } }
apache-2.0
1115cf0cc515acb3aace870956b53ea5
25.261905
167
0.56981
4.859031
false
false
false
false
mrfour0004/AVScanner
Sources/AVScannerViewController.swift
1
2290
// // ScannerViewController.swift // AVScanner // // Created by mrfour on 2019/10/6. // import UIKit import AVFoundation open class AVScannerViewController: UIViewController, AVScannerViewDelegate { // MARK: - Scanner View public private(set) lazy var scannerView = AVScannerView(controller: .init()) // MARK: - View lifecycle open override func viewDidLoad() { super.viewDidLoad() prepareView() scannerView.initSession() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scannerView.startSession() } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let orientation = UIDevice.current.orientation guard let newVideoOrientation = AVCaptureVideoOrientation(deviceOrientation: orientation), orientation.isPortrait || orientation.isLandscape else { return } scannerView.videoOrientation = newVideoOrientation } open override var shouldAutorotate: Bool { scannerView.isSessionRunning } // MARK: - Scanner view delegate open func scannerViewDidFinishConfiguration(_ scannerView: AVScannerView) { } open func scannerView(_ scannerView: AVScannerView, didFailConfigurationWithError error: Error) { } open func scannerViewDidStartSession(_ scannerView: AVScannerView) { } open func scannerView(_ scannerView: AVScannerView, didFailStartingSessionWithError error: Error) { } open func scannerViewDidStopSession(_ scannerView: AVScannerView) { } open func scannerView(_ scannerView: AVScannerView, didCapture metadataObject: AVMetadataMachineReadableCodeObject) { } } // MARK: - Prepare views private extension AVScannerViewController { func prepareView() { prepareScannerView() } func prepareScannerView() { // Prevent scanner view covering any views set in storyboard or xib. view.insertSubview(scannerView, at: 0) scannerView.frame = view.bounds scannerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scannerView.delegate = self } }
mit
85bf5315579dae0b43c2dc3be165bcd9
24.730337
121
0.703057
5.518072
false
false
false
false
InderKumarRathore/DeviceGuru
Sources/DeviceVersion.swift
1
613
// Copyright @DeviceGuru import Foundation public struct DeviceVersion: Comparable { public let major: Int public let minor: Int public init(major: Int, minor: Int) { self.major = major self.minor = minor } public static func < (lhs: DeviceVersion, rhs: DeviceVersion) -> Bool { if lhs.major == rhs.major { return lhs.minor < rhs.minor } else { return lhs.major < rhs.major } } public static func == (lhs: DeviceVersion, rhs: DeviceVersion) -> Bool { lhs.major == rhs.major && lhs.minor == rhs.minor } }
mit
e74f54e71117cb325c831326d3f7447f
23.52
76
0.587276
4.141892
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/StrokeNode.swift
3
5857
// // StrokeNode.swift // lottie-swift // // Created by Brandon Withrow on 1/22/19. // import Foundation import QuartzCore // MARK: - StrokeNodeProperties final class StrokeNodeProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(stroke: Stroke) { keypathName = stroke.name color = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.color.keyframes)) opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.opacity.keyframes)) width = NodeProperty(provider: KeyframeInterpolator(keyframes: stroke.width.keyframes)) miterLimit = CGFloat(stroke.miterLimit) lineCap = stroke.lineCap lineJoin = stroke.lineJoin if let dashes = stroke.dashPattern { let (dashPatterns, dashPhase) = dashes.shapeLayerConfiguration dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns)) if dashPhase.count == 0 { self.dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0))) } else { self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase)) } } else { dashPattern = NodeProperty(provider: SingleValueProvider([LottieVector1D]())) dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0))) } keypathProperties = [ "Opacity" : opacity, PropertyName.color.rawValue : color, "Stroke Width" : width, "Dashes" : dashPattern, "Dash Phase" : dashPhase, ] properties = Array(keypathProperties.values) } // MARK: Internal let keypathName: String let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] let opacity: NodeProperty<LottieVector1D> let color: NodeProperty<LottieColor> let width: NodeProperty<LottieVector1D> let dashPattern: NodeProperty<[LottieVector1D]> let dashPhase: NodeProperty<LottieVector1D> let lineCap: LineCap let lineJoin: LineJoin let miterLimit: CGFloat } // MARK: - StrokeNode /// Node that manages stroking a path final class StrokeNode: AnimatorNode, RenderNode { // MARK: Lifecycle init(parentNode: AnimatorNode?, stroke: Stroke) { strokeRender = StrokeRenderer(parent: parentNode?.outputNode) strokeProperties = StrokeNodeProperties(stroke: stroke) self.parentNode = parentNode } // MARK: Internal let strokeRender: StrokeRenderer let strokeProperties: StrokeNodeProperties let parentNode: AnimatorNode? var hasLocalUpdates = false var hasUpstreamUpdates = false var lastUpdateFrame: CGFloat? = nil var renderer: NodeOutput & Renderable { strokeRender } // MARK: Animator Node Protocol var propertyMap: NodePropertyMap & KeypathSearchable { strokeProperties } var isEnabled = true { didSet { strokeRender.isEnabled = isEnabled } } func localUpdatesPermeateDownstream() -> Bool { false } func rebuildOutputs(frame _: CGFloat) { strokeRender.color = strokeProperties.color.value.cgColorValue strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue * 0.01 strokeRender.width = strokeProperties.width.value.cgFloatValue strokeRender.miterLimit = strokeProperties.miterLimit strokeRender.lineCap = strokeProperties.lineCap strokeRender.lineJoin = strokeProperties.lineJoin /// Get dash lengths let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue } if dashLengths.count > 0, dashLengths.isSupportedLayerDashPattern { strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue strokeRender.dashLengths = dashLengths } else { strokeRender.dashLengths = nil strokeRender.dashPhase = nil } } } // MARK: - [DashElement] + shapeLayerConfiguration extension Array where Element == DashElement { typealias ShapeLayerConfiguration = ( dashPatterns: ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>, dashPhase: ContiguousArray<Keyframe<LottieVector1D>>) /// Converts the `[DashElement]` data model into `lineDashPattern` and `lineDashPhase` /// representations usable in a `CAShapeLayer` var shapeLayerConfiguration: ShapeLayerConfiguration { var dashPatterns = ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>() var dashPhase = ContiguousArray<Keyframe<LottieVector1D>>() for dash in self { if dash.type == .offset { dashPhase = dash.value.keyframes } else { dashPatterns.append(dash.value.keyframes) } } dashPatterns = ContiguousArray(dashPatterns.map { pattern in ContiguousArray(pattern.map { keyframe -> Keyframe<LottieVector1D> in // The recommended way to create a stroke of round dots, in theory, // is to use a value of 0 followed by the stroke width, but for // some reason Core Animation incorrectly (?) renders these as pills // instead of circles. As a workaround, for parity with Lottie on other // platforms, we can change `0`s to `0.01`: https://stackoverflow.com/a/38036486 if keyframe.value.cgFloatValue == 0 { return keyframe.withValue(LottieVector1D(0.01)) } else { return keyframe } }) }) return (dashPatterns, dashPhase) } } extension Array where Element == CGFloat { // If all of the items in the dash pattern are zeros, then we shouldn't attempt to render it. // This causes Core Animation to have extremely poor performance for some reason, even though // it doesn't affect the appearance of the animation. // - We check for `== 0.01` instead of `== 0` because `dashPattern.shapeLayerConfiguration` // converts all `0` values to `0.01` to work around a different Core Animation rendering issue. var isSupportedLayerDashPattern: Bool { !allSatisfy { $0 == 0.01 } } }
apache-2.0
ebf945b43f4f54327e868848a52d11ef
31.538889
100
0.718457
4.796888
false
false
false
false
BluechipSystems/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Shared/Controllers/TwitterLogin/WireFrame/TwitterLoginWireFrame.swift
4
1555
// // TwitterLoginWireFrame.swift // TwitterLoginGenDemo // // Created by AUTHOR on 24/10/14. // Copyright (c) 2014 AUTHOR. All rights reserved. // import Foundation class TwitterLoginWireFrame: TwitterLoginWireFrameProtocol { class func presentTwitterLoginModule(inWindow window: UIWindow) { // Generating module components var view: TwitterLoginViewProtocol = TwitterLoginView() var presenter: protocol<TwitterLoginPresenterProtocol, TwitterLoginInteractorOutputProtocol> = TwitterLoginPresenter() var interactor: TwitterLoginInteractorInputProtocol = TwitterLoginInteractor() var APIDataManager: TwitterLoginAPIDataManagerInputProtocol = TwitterLoginAPIDataManager() var localDataManager: TwitterLoginLocalDataManagerInputProtocol = TwitterLoginLocalDataManager() var wireFrame: TwitterLoginWireFrameProtocol = TwitterLoginWireFrame() // Connecting view.presenter = presenter presenter.view = view presenter.wireFrame = wireFrame presenter.interactor = interactor interactor.presenter = presenter interactor.APIDataManager = APIDataManager interactor.localDatamanager = localDataManager // Presenting window.rootViewController = view as? TwitterLoginView } func presentHome(fromView view: AnyObject, completion: ((completed: Bool) -> ())?) { TwitterListWireFrame.presentTwitterListModule(inWindow: UIApplication.sharedApplication().delegate!.window!!) } }
mit
704dd6cf8f9c4a704738bb1db9aea5b6
37.9
126
0.73119
6.146245
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsCache.swift
1
1203
// // ProfileSettingsCache.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Foundation import ProfilePayloads extension ProfileSettings { // MARK: - // MARK: Is Enabled // swiftlint:disable:next discouraged_optional_boolean func cacheIsEnabled(_ subkey: PayloadSubkey, payloadIndex: Int) -> Bool? { guard let cacheEnabled = self.cachedEnabled[subkey.keyPath], let isEnabled = cacheEnabled[payloadIndex] else { return nil } #if DEBUGISENABLED Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled) - Cache", category: String(describing: self)) #endif return isEnabled } func setCacheIsEnabled(_ enabled: Bool, forSubkey subkey: PayloadSubkey, payloadIndex: Int) { var cacheSubkey = self.cachedEnabled[subkey.keyPath] ?? [Int: Bool]() cacheSubkey[payloadIndex] = enabled #if DEBUGISENABLED Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(enabled) - Setting Cache", category: String(describing: self)) #endif self.cachedEnabled[subkey.keyPath] = cacheSubkey } }
mit
22ec14e7df40324c29a1e6acb3014ff0
29.820513
136
0.68386
4.188153
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0043.xcplaygroundpage/Contents.swift
1
6033
/*: # Declare variables in 'case' labels with multiple patterns * Proposal: [SE-0043](0043-declare-variables-in-case-labels-with-multiple-patterns.md) * Author: [Andrew Bennett](https://github.com/therealbnut) * Review Manager: [Chris Lattner](https://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160321/013250.html) * Implementation: [apple/swift#1383](https://github.com/apple/swift/pull/1383) ## Introduction In Swift 2, it is possible to match multiple patterns in cases. However cases cannot contain multiple patterns if the case declares variables. The following code currently produces an error: ```swift enum MyEnum { case Case1(Int,Float) case Case2(Float,Int) } switch value { case let .Case1(x, 2), let .Case2(2, x): print(x) case .Case1, .Case2: break } ``` The error is: `case` labels with multiple patterns cannot declare variables. This proposal aims to remove this error when each pattern declares the same variables with the same types. Swift-evolution thread: [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/007431.html) ## Motivation This change reduces repetitive code, and therefore reduces mistakes. It's consistent with multi-pattern matching when variables aren't defined. ## Proposed solution Allow case labels with multiple patterns to declare patterns by matching variable names in each pattern. Using the following enum: ```swift enum MyEnum { case Case1(Int,Float) case Case2(Float,Int) } ``` These cases should be possible: ```swift case let .Case1(x, _), let .Case2(_, x): case let .Case1(y, x), let .Case2(x, y): case let .Case1(x), let .Case2(x): case .Case1(let x, _), .Case2(_, let x): ``` Likewise for other uses of patterns: ```swift let value = MyEnum.Case1(1, 2) if case let .Case1(x, _), let .Case2(_, x) = value { ... } ``` ## Detailed design Allow case labels with multiple patterns if the case labels match the following constraints: * All patterns declare exactly the same variables. * The same variable has the same type in each pattern. Therefore each pattern is able to produce the same variables for the case label. In the case of `if case let` usage the syntax is the same, the only issue is whether this can be combined with other variables, and whether it is unambiguous. The pattern grammar gets the following change: ```diff + enum-case-pattern-list → enum-case-pattern | + enum-case-pattern , enum-case-pattern-list + pattern → enum-case-pattern-list - pattern → enum-case-pattern ``` ## Impact on existing code This should have no impact on existing code, although it should offer many opportunities for existing code to be simplified. ## Alternatives considered ### Using a closure or inline function Code repetition can be reduced with one pattern per 'case' and handling the result with an inline function. ```swift func handleCases(value: MyEnum, apply: Int -> Int) -> Int { func handleX(x: Int) -> Int { return apply(x) + 1 } let out: Int switch value { case .Case1(let x, 2): out = handleX(x) case .Case2(2, let x): out = handleX(x) case .Case1, .Case2: out = -1 } return out } ``` This syntax is much more verbose, makes control flow more confusing, and has the limitations of what the inline function may capture. In the above example `apply` cannot be `@noescape` because handleX captures it. Also in the above example if `out` is captured and assigned by `handleX` then it must be `var`, not `let`. This can produce shorter syntax, but is not as safe; `out` may accidentally be assigned more than once, additionally `out` also needs to be initialized (which may not be possible or desirable). ### Extending the fallthrough syntax A similar reduction in code repetition can be achieved if fallthrough allowed variables to be mapped onto the next case, for example: ```swift switch test { case .Case1(let x, 2): fallthrough .Case2(_, x) case .Case2(3, .let x): print("x: \(x)") } ``` This is not as intuitive, is a hack, and fallthrough should probably be discouraged. It is much more flexible, a programmer could adjust the value of x before fallthrough. Flexibility increases the chances of programmer error, perhaps not as much as code-repetition though. ### Chainable pattern matching In my opinion `if case let` syntax is a little clumsy. It's good that it's consistent with a switch statement, but it's not easy to chain. I think a different syntax may be nicer, if a few things existed: * A case-compare syntax that returns an optional tuple: ```swift let x = MyEnum.Case1(1,2) let y: (Int,Int)? = (x case? MyEnum.Case1) assert(y == Optional.Some(1,2)) ``` * multiple field getters (similar to swizzling in GLSL). It returns multiple named fields/properties of a type as a tuple: ```swift let x = (a: 1, b: 2, c: 3) let y = x.(a,c,b,b) assert(y == (1,3,2,2)) ``` You could compose them like this: ```swift enum MyNewEnum { case MyCase1(Int,Float), MyCase2(Float,Int) } let x = MyNewEnum.Case1(1,2,3) let y: (Int,Float)? = (x case? MyNewEnum.Case1) ?? (x case! MyNewEnum.Case2).(1,0) ``` This is not a true alternative, it does not work in switch statements, but I think it still has value. ## Future Considerations It would be nice to use the `if case let` syntax to define variables of optional type. Something like this: case let .Case1(x,_) = MyEnum.Case1(1,2) Which would be the equivalent of this: let x: Int? if case let .Case1(t) = MyEnum.Case1(1,2) { x = t.0 } else { x = nil } It would support multiple patterns like so: case let .Case1(x,_), .Case2(_,x) = MyEnum.Case1(1,2) This is not necessary if [chainable pattern matching](#chainable-pattern-matching) was possible, but I've made sure this proposal is compatible. ---------- [Previous](@previous) | [Next](@next) */
mit
d6c0b84f5cdc6e02261b92d025c95869
29.286432
300
0.708313
3.541128
false
false
false
false
rmavani/SocialQP
QPrint/Utility/ComonClass/AppUtilities.swift
1
9634
// // AppUtilities.swift // Laundry // // Created by cears infotech on 7/18/16. // Copyright © 2016 cears infotech. All rights reserved. // import UIKit class AppUtilities { class var sharedInstance :AppUtilities { struct Singleton { static let instance = AppUtilities() } return Singleton.instance } /*======================================================= Function Name: isValidEmail Function Param : - String Function Return Type : - bool Function purpose :- check for valid Email ID ========================================================*/ func isValidEmail(testStr:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) let result = emailTest.evaluate(with: testStr) return result } /*======================================================= Function Name: validatePhone Function Param : - String Function Return Type : - bool Function purpose :- check for valid phone Number ========================================================*/ func validatePhone(value: String) -> Bool { let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$" let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) let result = phoneTest.evaluate(with: value) return result } func isValidPhone(phone: String) -> Bool { let PHONE_REGEX = "\\+?\\d[\\d -]{8,12}\\d" let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) let result = phoneTest.evaluate(with: phone) return result } // check internet connectivity class func isConnectedToNetwork() -> Bool { let reachability = Reachability.forInternetConnection() let status : NetworkStatus = reachability!.currentReachabilityStatus() if status == NotReachable { return false } else { return true } } /*======================================================= Function Name: bottomBoredr Function Param : - AnyObject Function Return Type : - Function purpose :- give bottom border with white color ========================================================*/ func bottomBoredr(textField :AnyObject) { let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: textField.frame.height - 1, width: textField.frame.width, height: 1.0) bottomLine.backgroundColor = UIColor.white.cgColor textField.layer.addSublayer(bottomLine) } /*======================================================= Function Name: bottomBoredrColor Function Param : - AnyObject Function Return Type : - Function purpose :- give bottom border with color code ========================================================*/ func bottomBoredrColor(textField :AnyObject) { let bottomLine = CALayer() bottomLine.frame = CGRect(x : 0, y : textField.frame.height - 1, width : textField.frame.width, height :1.0) bottomLine.backgroundColor = UIColor.red.cgColor textField.layer.addSublayer(bottomLine) } func drawRedBorderToTextfield(txtField:AnyObject, cornerRadius:CGFloat, borderRadius:CGFloat) { if #available(iOS 8.0, *) { txtField.layer.borderWidth=borderRadius txtField.layer.cornerRadius=cornerRadius txtField.layer.borderColor=UIColor.red.cgColor } else { // Fallback on earlier versions } } func drawClearBorderToTextfield(txtField:AnyObject,cornerRadius:CGFloat, borderRadius:CGFloat) { if #available(iOS 8.0, *) { txtField.layer.borderWidth=borderRadius txtField.layer.cornerRadius=cornerRadius txtField.layer.borderColor=UIColor.clear.cgColor } } func drawLightGrayBorderToTextfield(txtField:AnyObject,cornerRadius:CGFloat, borderRadius:CGFloat) { if #available(iOS 8.0, *) { txtField.layer.borderWidth=borderRadius txtField.layer.cornerRadius=cornerRadius txtField.layer.borderColor=UIColor.lightGray.cgColor } } /*======================================================= Function Name: setPlaceholder Function Param : - UITextField, String Function Return Type : - Function purpose :- set placeholder of white color ========================================================*/ func setPlaceholder (textFiled : UITextField , str : String) { textFiled.attributedPlaceholder = NSAttributedString(string:str, attributes:[NSForegroundColorAttributeName: UIColor.white]) } /*======================================================= Function Name: setPlaceholderGray Function Param : - UITextField,String Function Return Type : - Function purpose :- set placeholder of gray color ========================================================*/ func setPlaceholderGray (textFiled : UITextField , str : String) { textFiled.attributedPlaceholder = NSAttributedString(string:str, attributes:[NSForegroundColorAttributeName: UIColor.gray]) } /*======================================================= Function Name: dataTask Function Param : - URL,Strig,String,Block Function Return Type : - Function purpose :- Global Class For API Calling. ========================================================*/ func dataTask(request: NSMutableURLRequest, method: String,params:NSString, completion: @escaping (_ success: Bool, _ object: AnyObject?) -> ()) { request.httpMethod = method request.httpBody = params.data(using: String.Encoding.utf8.rawValue) let session = URLSession(configuration: URLSessionConfiguration.default) session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in if let data = data { let json = try? JSONSerialization.jsonObject(with: data, options: []) if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode { completion(true, json as AnyObject?) } else { completion(false, json as AnyObject?) } } }.resume() } func post(request: NSMutableURLRequest,params:NSString, completion: @escaping (_ success: Bool, _ object: AnyObject?) -> ()) { dataTask(request: request, method: "POST", params: params, completion: completion) } func put(request: NSMutableURLRequest,params:NSString, completion: @escaping (_ success: Bool, _ object: AnyObject?) -> ()) { dataTask(request: request, method: "PUT", params: params, completion: completion) } func get(request: NSMutableURLRequest,params:NSString, completion: @escaping (_ success: Bool, _ object: AnyObject?) -> ()) { dataTask(request: request, method: "GET", params: params, completion: completion) } /*======================================================= Function Name: showAlert Function Param : - String Function Return Type : - Function purpose :- Show Alert With specific Message ========================================================*/ func showAlert(title : NSString, msg : NSString) { let alert = UIAlertView(title: title as String, message: msg as String, delegate: nil, cancelButtonTitle: "OK") DispatchQueue.main.async { alert.show() } // DispatchQueue.main.async(execute: { () -> Void in // // alert.show() // } // }) } /*======================================================= Function Name: showLoader Function Param : - Function Return Type : - Function purpose :- Show Loader ========================================================*/ func showLoader() { var config : SwiftLoader.Config = SwiftLoader.Config() config.size = 120 config.backgroundColor = UIColor.white config.spinnerColor = UIColor.black config.titleTextColor = UIColor.black config.spinnerLineWidth = 1.5 config.foregroundColor = UIColor.black config.foregroundAlpha = 0.3 config.titleTextFont = UIFont.init(name: "Montserrat-Regular", size: 15.0)! SwiftLoader.setConfig(config) SwiftLoader.show("Loading..", animated: true) } func hideLoader() { DispatchQueue.main.async { SwiftLoader.hide() } } } //TextField Inset// class MyTextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10); override func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } }
mit
fd8616be23b806e361fc1b5754c80a21
34.285714
150
0.539915
5.53939
false
true
false
false
chrisbudro/ControllerCollections
ControllerCollection/Sample/FirstChildViewController.swift
1
2018
// // FirstChildViewController.swift // ControllerCollection // // Created by Chris Budro on 6/29/16. // Copyright © 2016 Chris Budro. All rights reserved. // import UIKit class FirstChildViewController: CollectionChildViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private struct Constants { static let CellReuseIdentifier = "Cell" } var imageCollection = [UIImage]() @IBOutlet weak var collectionView: UICollectionView! //MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self collectionView.registerNib(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: Constants.CellReuseIdentifier) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) collectionView.reloadData() } //MARK: Collection View data source func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageCollection.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.CellReuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell let image = imageCollection[indexPath.row] cell.imageView.image = image return cell } //MARK: Flow layout delegate func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return view.bounds.size } override func prepareForReuse() { imageCollection.removeAll() collectionView.setContentOffset(CGPointZero, animated: false) } }
mit
10b2fe5705f7ea980728227374bbd9ec
31.015873
169
0.70352
6.130699
false
false
false
false
pendowski/PopcornTimeIOS
Popcorn Time/UI/UpNextView.swift
1
2407
import UIKit import SwiftyTimer protocol UpNextViewDelegate: class { func constraintsWereUpdated(willHide hide: Bool) func timerFinished() } class UpNextView: UIVisualEffectView { @IBOutlet var nextEpisodeInfoLabel: UILabel! @IBOutlet var nextEpisodeTitleLabel: UILabel! @IBOutlet var nextShowTitleLabel: UILabel! @IBOutlet var nextEpsiodeThumbImageView: UIImageView! @IBOutlet var nextEpisodeCountdownLabel: UILabel! @IBOutlet var leadingConstraint: NSLayoutConstraint! @IBOutlet var trailingConstraint: NSLayoutConstraint! weak var delegate: UpNextViewDelegate? private var timer: NSTimer! private var updateTimer: NSTimer! func show() { if hidden { hidden = false trailingConstraint.active = false leadingConstraint.active = true delegate?.constraintsWereUpdated(willHide: false) startTimer() } } func hide() { if !hidden { trailingConstraint.active = true leadingConstraint.active = false delegate?.constraintsWereUpdated(willHide: true) } } func startTimer() { var delay = 10 updateTimer = NSTimer.every(1.0) { if delay - 1 >= 0 { delay -= 1 self.nextEpisodeCountdownLabel.text = String(delay) } } timer = NSTimer.after(10.0, { self.updateTimer.invalidate() self.updateTimer = nil self.delegate?.timerFinished() }) } @IBAction func closePlayNextView() { hide() timer.invalidate() timer = nil } @IBAction func playNextNow() { hide() updateTimer.invalidate() updateTimer = nil timer.invalidate() timer = nil self.delegate?.timerFinished() } } extension PCTPlayerViewController { func constraintsWereUpdated(willHide hide: Bool) { UIView.animateWithDuration(animationLength, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: { (finished) in if hide { self.upNextView.hidden = true } }) } func timerFinished() { didFinishPlaying() delegate?.playNext(nextMedia!) } }
gpl-3.0
594665ecad97b1c5d75a7e880b62f835
26.044944
115
0.593685
5.209957
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKit/Classes/HexPopupView.swift
1
963
// // HexPopupView.swift // ColorPicKitExample // // Created by Zakk Hoyt on 11/12/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit public class HexPopupView: UIView { required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } private var hexLabel: UILabel? = nil private func commonInit() { backgroundColor = UIColor.darkGray layer.cornerRadius = 4.0 layer.masksToBounds = true hexLabel = UILabel(frame: bounds) hexLabel?.textColor = .white hexLabel?.textAlignment = .center hexLabel?.text = "0xFF" hexLabel?.font.withSize(12) addSubview(hexLabel!) } func setText(text: String) { hexLabel?.text = text } }
mit
d25f349fe9583ed1ecd3ecd17b581174
19.913043
52
0.575884
4.559242
false
false
false
false
MAARK/Charts
Tests/Charts/BarChartTests.swift
5
18726
import XCTest import FBSnapshotTestCase @testable import Charts class BarChartTests: FBSnapshotTestCase { override func setUp() { super.setUp() // Set to `true` to re-capture all snapshots self.recordMode = false } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } //MARK: Prepare func setupCustomValuesDataEntries(values: [Double]) -> [ChartDataEntry] { var entries: [ChartDataEntry] = Array() for (i, value) in values.enumerated() { entries.append(BarChartDataEntry(x: Double(i), y: value, icon: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil))) } return entries } func setupDefaultValuesDataEntries() -> [ChartDataEntry] { let values: [Double] = [8, 104, -81, 93, 52, -44, 97, 101, -75, 28, -76, 25, 20, -13, 52, 44, -57, 23, 45, -91, 99, 14, -84, 48, 40, -71, 106, 41, -45, 61] return setupCustomValuesDataEntries(values: values) } func setupPositiveValuesDataEntries() -> [ChartDataEntry] { let values: [Double] = [8, 104, 81, 93, 52, 44, 97, 101, 75, 28, 76, 25, 20, 13, 52, 44, 57, 23, 45, 91, 99, 14, 84, 48, 40, 71, 106, 41, 45, 61] return setupCustomValuesDataEntries(values: values) } func setupNegativeValuesDataEntries() -> [ChartDataEntry] { let values: [Double] = [-8, -104, -81, -93, -52, -44, -97, -101, -75, -28, -76, -25, -20, -13, -52, -44, -57, -23, -45, -91, -99, -14, -84, -48, -40, -71, -106, -41, -45, -61] return setupCustomValuesDataEntries(values: values) } func setupZeroValuesDataEntries() -> [ChartDataEntry] { let values = [Double](repeating: 0.0, count: 30) return setupCustomValuesDataEntries(values: values) } func setupStackedValuesDataEntries() -> [ChartDataEntry] { var entries: [ChartDataEntry] = Array() entries.append(BarChartDataEntry(x: 0, yValues: [28, 50, 60, 30, 42], icon: UIImage(named: "icon"))) entries.append(BarChartDataEntry(x: 1, yValues: [-20, -36, -52, -40, -15], icon: UIImage(named: "icon"))) entries.append(BarChartDataEntry(x: 2, yValues: [10, 30, 40, 90, 72], icon: UIImage(named: "icon"))) entries.append(BarChartDataEntry(x: 3, yValues: [-40, -50, -30, -60, -20], icon: UIImage(named: "icon"))) entries.append(BarChartDataEntry(x: 4, yValues: [10, 40, 60, 45, 62], icon: UIImage(named: "icon"))) return entries } func setupDefaultStackedDataSet(chartDataEntries: [ChartDataEntry]) -> BarChartDataSet { let dataSet = BarChartDataSet(entries: chartDataEntries, label: "Stacked bar chart unit test data") dataSet.drawIconsEnabled = false dataSet.iconsOffset = CGPoint(x: 0, y: -10.0) dataSet.colors = Array(arrayLiteral:NSUIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0), NSUIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0), NSUIColor(red: 231/255.0, green: 76/255.0, blue: 60/255.0, alpha: 1.0), NSUIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0) ) return dataSet } func setupDefaultDataSet(chartDataEntries: [ChartDataEntry]) -> BarChartDataSet { let dataSet = BarChartDataSet(entries: chartDataEntries, label: "Bar chart unit test data") dataSet.drawIconsEnabled = false dataSet.iconsOffset = CGPoint(x: 0, y: -10.0) return dataSet } func setupDefaultChart(dataSets: [BarChartDataSet]) -> BarChartView { let data = BarChartData(dataSets: dataSets) data.barWidth = 0.85 let chart = BarChartView(frame: CGRect(x: 0, y: 0, width: 480, height: 350)) chart.backgroundColor = NSUIColor.clear chart.data = data return chart } //MARK: Start Test func testDefaultValues() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testDefaultBarDataSetLabels() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = BarChartDataSet(entries: dataEntries) dataSet.drawIconsEnabled = false let chart = setupDefaultChart(dataSets: [dataSet]) ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testZeroValues() { let dataEntries = setupZeroValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValues() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValuesWithCustomAxisMaximum() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMaximum = 50 chart.clipValuesToContentEnabled = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValuesWithCustomAxisMaximum2() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMaximum = -10 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValuesWithCustomAxisMinimum() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMinimum = 50 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValuesWithCustomAxisMinimum2() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMinimum = 110 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testPositiveValuesWithCustomAxisMaximumAndCustomAxisMaximum() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) //If min is greater than max, then min and max will be exchanged. chart.leftAxis.axisMaximum = 200 chart.leftAxis.axisMinimum = -10 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValues() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValuesWithCustomAxisMaximum() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMaximum = 10 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValuesWithCustomAxisMaximum2() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMaximum = -150 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValuesWithCustomAxisMinimum() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMinimum = -200 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValuesWithCustomAxisMinimum2() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.axisMinimum = 10 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNegativeValuesWithCustomAxisMaximumAndCustomAxisMaximum() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) //If min is greater than max, then min and max will be exchanged. chart.leftAxis.axisMaximum = 10 chart.leftAxis.axisMinimum = -200 chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testHidesValues() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) dataSet.drawValuesEnabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testNotDrawValueAboveBars() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.drawValueAboveBarEnabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testStackedDrawValues() { let dataEntries = setupStackedValuesDataEntries() let dataSet = setupDefaultStackedDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testStackedNotDrawValues() { let dataEntries = setupStackedValuesDataEntries() let dataSet = setupDefaultStackedDataSet(chartDataEntries: dataEntries) dataSet.drawValuesEnabled = false let chart = setupDefaultChart(dataSets: [dataSet]) chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testStackedNotDrawValuesAboveBars() { let dataEntries = setupStackedValuesDataEntries() let dataSet = setupDefaultStackedDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.drawValueAboveBarEnabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testHideLeftAxis() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.enabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testHideRightAxis() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.rightAxis.enabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedLeftAxis() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedLeftAxisWithNegativeValues() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedLeftAxisWithPositiveValues() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedRightAxis() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) dataSet.axisDependency = .right let chart = setupDefaultChart(dataSets: [dataSet]) chart.rightAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedRightAxisWithNegativeValues() { let dataEntries = setupNegativeValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) dataSet.axisDependency = .right let chart = setupDefaultChart(dataSets: [dataSet]) chart.rightAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testInvertedRightAxisWithPositiveValues() { let dataEntries = setupPositiveValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) dataSet.axisDependency = .right let chart = setupDefaultChart(dataSets: [dataSet]) chart.rightAxis.inverted = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testHideHorizontalGridlines() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.leftAxis.drawGridLinesEnabled = false chart.rightAxis.drawGridLinesEnabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testHideVerticalGridlines() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) chart.xAxis.drawGridLinesEnabled = false chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } func testDrawIcons() { let dataEntries = setupDefaultValuesDataEntries() let dataSet = setupDefaultDataSet(chartDataEntries: dataEntries) let chart = setupDefaultChart(dataSets: [dataSet]) dataSet.drawIconsEnabled = true chart.notifyDataSetChanged() ChartsSnapshotVerifyView(chart, identifier: Snapshot.identifier(UIScreen.main.bounds.size), overallTolerance: Snapshot.tolerance) } }
apache-2.0
f5119da07abc6b82e209c991b6efe8c4
44.014423
157
0.695824
5.424681
false
true
false
false
jngd/advanced-ios10-training
T8E01/T8E01/ViewController.swift
1
2547
// // ViewController.swift // T8E01 // // Created by jngd on 20/03/2017. // Copyright © 2017 jngd. All rights reserved. // import UIKit import StoreKit class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver { @IBOutlet weak var image: UIImageView! @IBAction func priceButtonPressed(_ sender: Any) { if (SKPaymentQueue.canMakePayments()){ print("Make payments") // (1) and (2) is product identifier let productIdentifiers: Set<String> = ["product1"] let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest.delegate = self productsRequest.start() }else{ print("Not authorized") } } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(productReady), name: NSNotification.Name(rawValue: "ProductReady"), object: nil) } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products var product : SKProduct? for productIterator in products { switch productIterator.productIdentifier { case "product1": product = productIterator case "2": product = productIterator default: fatalError("Fatal error: Product ID not available") } } if (product != nil){ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProductReady"), object: product) SKPaymentQueue.default().add(self) } } func productReady (notification: NSNotification){ let product = notification.object as! SKProduct let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions{ switch transaction.transactionState{ case .purchased: print("Completed purchase") if (transaction.payment.productIdentifier == "1") { image.image = UIImage(named: "1.png") } else if (transaction.payment.productIdentifier == "2") { image.image = UIImage(named: "2.png") } SKPaymentQueue.default().finishTransaction(transaction) break case .failed: print("Failed purchase") SKPaymentQueue.default().finishTransaction(transaction) break case .restored: print("Restored purchase") SKPaymentQueue.default().finishTransaction(transaction) break default: print("Buying") } } SKPaymentQueue.default().restoreCompletedTransactions() } }
apache-2.0
cb25173c3096f53a135c50e1c1025b9d
26.376344
93
0.725059
4.093248
false
false
false
false
KrishMunot/swift
stdlib/public/core/StringBridge.swift
1
10849
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. /// Effectively an untyped NSString that doesn't require foundation. public typealias _CocoaString = AnyObject public // @testable func _stdlib_binary_CFStringCreateCopy( _ source: _CocoaString ) -> _CocoaString { let result = _swift_stdlib_CFStringCreateCopy(nil, source) Builtin.release(result) return result } public // @testable func _stdlib_binary_CFStringGetLength( _ source: _CocoaString ) -> Int { return _swift_stdlib_CFStringGetLength(source) } public // @testable func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer<UTF16.CodeUnit> { return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII /// characters (does not apply ASCII optimizations). @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency func _cocoaStringToSwiftString_NonASCII( _ source: _CocoaString ) -> String { let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source) let length = _stdlib_binary_CFStringGetLength(cfImmutableValue) let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) return String(_StringCore( baseAddress: OpaquePointer(start), count: length, elementShift: 1, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self))) } /// Loading Foundation initializes these function variables /// with useful values /// Produces a `_StringBuffer` from a given subrange of a source /// `_CocoaString`, having the given minimum capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringToContiguous( source: _CocoaString, range: Range<Int>, minimumCapacity: Int ) -> _StringBuffer { _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil, "Known contiguously-stored strings should already be converted to Swift") let startIndex = range.startIndex let count = range.endIndex - startIndex let buffer = _StringBuffer(capacity: max(count, minimumCapacity), initialSize: count, elementWidth: 2) _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: startIndex, length: count), UnsafeMutablePointer<_swift_shims_UniChar>(buffer.start)) return buffer } /// Reads the entire contents of a _CocoaString into contiguous /// storage of sufficient capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringReadAll( _ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange( location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSlice( _ target: _StringCore, _ bounds: Range<Int> ) -> _StringCore { _sanityCheck(target.hasCocoaBuffer) let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped _sanityCheck( _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously-stored strings should already be converted to Swift") let cfResult: AnyObject = _swift_stdlib_CFStringCreateWithSubstring( nil, cfSelf, _swift_shims_CFRange( location: bounds.startIndex, length: bounds.count)) return String(_cocoaString: cfResult)._core } @_versioned @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSubscript( _ target: _StringCore, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf)._isNull, "Known contiguously-stored strings should already be converted to Swift") return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { return 0x0600 } extension String { @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public // SPI(Foundation) init(_cocoaString: AnyObject) { if let wrapped = _cocoaString as? _NSContiguousString { self._core = wrapped._core return } // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. let cfImmutableValue: _swift_shims_CFStringRef = _stdlib_binary_CFStringCreateCopy(_cocoaString) let length = _swift_stdlib_CFStringGetLength(cfImmutableValue) // Look first for null-terminated ASCII // Note: the code in clownfish appears to guarantee // nul-termination, but I'm waiting for an answer from Chris Kane // about whether we can count on it for all time or not. let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr( cfImmutableValue, kCFStringEncodingASCII) // start will hold the base pointer of contiguous storage, if it // is found. var start = UnsafeMutablePointer<_RawByte>(nulTerminatedASCII) let isUTF16 = nulTerminatedASCII._isNull if (isUTF16) { start = UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)) } self._core = _StringCore( baseAddress: OpaquePointer(start), count: length, elementShift: isUTF16 ? 1 : 0, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self)) } } // At runtime, this class is derived from `_SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase) public class _SwiftNativeNSString {} @objc public protocol _NSStringCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSString subclass. func length() -> Int func characterAtIndex(_ index: Int) -> UInt16 // We also override the following methods for efficiency. } /// An `NSString` built around a slice of contiguous Swift `String` storage. public final class _NSContiguousString : _SwiftNativeNSString { public init(_ _core: _StringCore) { _sanityCheck( _core.hasContiguousStorage, "_NSContiguousString requires contiguous storage") self._core = _core super.init() } init(coder aDecoder: AnyObject) { _sanityCheckFailure("init(coder:) not implemented for _NSContiguousString") } func length() -> Int { return _core.count } func characterAtIndex(_ index: Int) -> UInt16 { return _core[index] } func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) { _precondition(aRange.location + aRange.length <= Int(_core.count)) if _core.elementWidth == 2 { UTF16._copy( source: _core.startUTF16 + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } else { UTF16._copy( source: _core.startASCII + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } } @objc func _fastCharacterContents() -> UnsafeMutablePointer<UInt16> { return _core.elementWidth == 2 ? UnsafeMutablePointer(_core.startUTF16) : nil } // // Implement sub-slicing without adding layers of wrapping // func substringFromIndex(_ start: Int) -> _NSContiguousString { return _NSContiguousString(_core[Int(start)..<Int(_core.count)]) } func substringToIndex(_ end: Int) -> _NSContiguousString { return _NSContiguousString(_core[0..<Int(end)]) } func substringWithRange(_ aRange: _SwiftNSRange) -> _NSContiguousString { return _NSContiguousString( _core[Int(aRange.location)..<Int(aRange.location + aRange.length)]) } func copy() -> AnyObject { // Since this string is immutable we can just return ourselves. return self } /// The caller of this function guarantees that the closure 'body' does not /// escape the object referenced by the opaque pointer passed to it or /// anything transitively reachable form this object. Doing so /// will result in undefined behavior. @_semantics("self_no_escaping_closure") func _unsafeWithNotEscapedSelfPointer<Result>( @noescape _ body: (OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) defer { _fixLifetime(self) } return try body(selfAsPointer) } /// The caller of this function guarantees that the closure 'body' does not /// escape either object referenced by the opaque pointer pair passed to it or /// transitively reachable objects. Doing so will result in undefined /// behavior. @_semantics("pair_no_escaping_closure") func _unsafeWithNotEscapedSelfPointerPair<Result>( _ rhs: _NSContiguousString, @noescape _ body: (OpaquePointer, OpaquePointer) throws -> Result ) rethrows -> Result { let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self) let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self) defer { _fixLifetime(self) _fixLifetime(rhs) } return try body(selfAsPointer, rhsAsPointer) } public let _core: _StringCore } extension String { /// Same as `_bridgeToObjectiveC()`, but located inside the core standard /// library. public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject { if let ns = _core.cocoaBuffer where _swift_stdlib_CFStringGetLength(ns) == _core.count { return ns } _sanityCheck(_core.hasContiguousStorage) return _NSContiguousString(_core) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public func _bridgeToObjectiveCImpl() -> AnyObject { return _stdlib_binary_bridgeToObjectiveCImpl() } } #endif
apache-2.0
0b03024c6b42b7880de3f13312df0202
32.381538
92
0.709743
4.568
false
false
false
false
yyued/MagicDrag
MagicDrag/Responder/MGDPageViewController.swift
1
4447
// // MGDPageViewController.swift // MagicDrag // // Created by 崔 明辉 on 16/1/27. // Copyright © 2016年 swift. All rights reserved. // import UIKit class MGDPageViewController: UIViewController { var viewControllers: [MGDSceneViewController] = [] let scrollView = UIScrollView() let maskView = UIView() deinit { scrollView.delegate = nil } init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func loadView() { self.view = UIView(frame: UIScreen.mainScreen().bounds) self.view.backgroundColor = UIColor.whiteColor() } override func viewDidLoad() { super.viewDidLoad() self.configureScrollView() self.maskView.frame = UIScreen.mainScreen().bounds self.maskView.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.maskView) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.scrollView.setContentOffset(CGPoint(x: -UIScreen.mainScreen().bounds.size.width, y: 0.0), animated: false) self.view.bringSubviewToFront(self.maskView) UIView.animateWithDuration(1.0, delay: 0.25, options: [], animations: { () -> Void in self.scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: false) self.maskView.alpha = 0.0 }) { (_) -> Void in self.scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: false) self.maskView.removeFromSuperview() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func configureScrollView() { self.view.addSubview(scrollView) self.view.sendSubviewToBack(scrollView) for pageLayer in buildPageLayers() { pageLayer.frame = CGRect( x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width * CGFloat(viewControllers.count), height: UIScreen.mainScreen().bounds.size.height ) self.view.addSubview(pageLayer) } scrollView.contentSize = CGSize( width: UIScreen.mainScreen().bounds.size.width * CGFloat(viewControllers.count), height: UIScreen.mainScreen().bounds.size.height) scrollView.frame = UIScreen.mainScreen().bounds scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.delegate = self scrollView.bounces = false } override func prefersStatusBarHidden() -> Bool { return true } } extension MGDPageViewController { func buildPageLayers() -> [MGDPageLayer] { let pageLayers: [Int: MGDPageLayer] = { var tmpPageLayers: [Int: MGDPageLayer] = [:] for (pageIndex, viewController) in self.viewControllers.enumerate() { for sceneLayer in viewController.layers { if let pageLayer = tmpPageLayers[sceneLayer.layerIndex] { pageLayer.addSceneLayer(sceneLayer, atPage: pageIndex) } else if let pageLayer = MGDPageLayer.newLayer(sceneLayer.layerStyle) { tmpPageLayers[sceneLayer.layerIndex] = pageLayer pageLayer.addSceneLayer(sceneLayer, atPage: pageIndex) } } } return tmpPageLayers }() return { var tmpLayers: [MGDPageLayer] = [] let allKeys = pageLayers.keys.sort { $0 < $1 } for key in allKeys { tmpLayers.append(pageLayers[key]!) } return tmpLayers }() } } extension MGDPageViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { for view in scrollView.subviews { if let view = view as? MGDPageLayer { view.scrolling(scrollView.contentOffset.x) } } for view in self.view.subviews { if let view = view as? MGDPageLayer { view.scrolling(scrollView.contentOffset.x) } } } }
mit
f1317892933fa4f95a010b5b63847efd
31.881481
119
0.587877
4.969765
false
false
false
false
nikriek/gesundheit.space
NotYet/UIColor+CustomColors.swift
1
1208
// // UIColor+CustomColors.swift // NotYet // // Created by Niklas Riekenbrauck on 26.11.16. // Copyright © 2016 Niklas Riekenbrauck. All rights reserved. // import UIKit extension UIColor { class var customLightGreen: UIColor { return UIColor(netHex: 0x99e24b) } class var customGreen: UIColor { return UIColor(netHex: 0x47d73a) } class var customBackgroundGray: UIColor { return UIColor(netHex: 0xf2f2f2) } class var customLightGray: UIColor { return UIColor(netHex: 0xbebebe) } class var customGray: UIColor { return UIColor(netHex: 0xb1b1b1) } } extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
mit
bdb2770cd2db5f1598336fb269b0aaf3
25.822222
116
0.610605
3.52924
false
false
false
false
aschwaighofer/swift
test/SourceKit/CodeComplete/complete_checkdeps_bridged.swift
1
2505
import ClangFW import SwiftFW func foo() { /*HERE*/ } // REQUIRES: shell // RUN: %empty-directory(%t/Frameworks) // RUN: %empty-directory(%t/MyProject) // RUN: COMPILER_ARGS=( \ // RUN: -target %target-triple \ // RUN: -module-name MyProject \ // RUN: -F %t/Frameworks \ // RUN: -I %t/MyProject \ // RUN: -import-objc-header %t/MyProject/Bridging.h \ // RUN: %t/MyProject/Library.swift \ // RUN: %s \ // RUN: ) // RUN: INPUT_DIR=%S/Inputs/checkdeps // RUN: DEPCHECK_INTERVAL=1 // RUN: SLEEP_TIME=2 // RUN: cp -R $INPUT_DIR/MyProject %t/ // RUN: cp -R $INPUT_DIR/ClangFW.framework %t/Frameworks/ // RUN: %empty-directory(%t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule) // RUN: %target-swift-frontend -emit-module -module-name SwiftFW -o %t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule/%target-swiftmodule-name $INPUT_DIR/SwiftFW_src/Funcs.swift // RUN: %sourcekitd-test \ // RUN: -req=global-config -completion-check-dependency-interval ${DEPCHECK_INTERVAL} == \ // RUN: -shell -- echo "### Initial" == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -shell -- echo '### Modify bridging header library file' == \ // RUN: -shell -- cp -R $INPUT_DIR/MyProject_mod/LocalCFunc.h %t/MyProject/ == \ // RUN: -shell -- sleep $SLEEP_TIME == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -shell -- echo '### Fast completion' == \ // RUN: -shell -- sleep $SLEEP_TIME == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} \ // RUN: | %FileCheck %s // CHECK-LABEL: ### Initial // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1 // CHECK-LABEL: ### Modify bridging header library file // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc_mod()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1 // CHECK-LABEL: ### Fast completion // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc_mod()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK: key.reusingastcontext: 1
apache-2.0
64ae071d80c79f9fae83e76a2f7aa0c7
32.851351
187
0.650699
3.096415
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/SiteManagement/SiteSettingsViewController+SiteManagement.swift
1
7438
import UIKit import CocoaLumberjack import SVProgressHUD import WordPressShared /// Implements site management services triggered from SiteSettingsViewController /// public extension SiteSettingsViewController { /// Presents confirmation alert for Export Content /// public func confirmExportContent() { tableView.deselectSelectedRowWithAnimation(true) WPAppAnalytics.track(.siteSettingsExportSiteAccessed, with: self.blog) present(confirmExportController(), animated: true, completion: nil) } /// Creates confirmation alert for Export Content /// /// - Returns: UIAlertController /// fileprivate func confirmExportController() -> UIAlertController { let confirmTitle = NSLocalizedString("Export Your Content", comment: "Title of Export Content confirmation alert") let messageFormat = NSLocalizedString("Your posts, pages, and settings will be mailed to you at %@.", comment: "Message of Export Content confirmation alert; substitution is user's email address") let message = String(format: messageFormat, blog.account!.email) let alertController = UIAlertController(title: confirmTitle, message: message, preferredStyle: .alert) let cancelTitle = NSLocalizedString("Cancel", comment: "Alert dismissal title") alertController.addCancelActionWithTitle(cancelTitle, handler: nil) let exportTitle = NSLocalizedString("Export Content", comment: "Export Content confirmation action title") alertController.addDefaultActionWithTitle(exportTitle, handler: { _ in self.exportContent() }) return alertController } /// Handles triggering content export to XML file via API /// /// - Note: Email is sent on completion /// fileprivate func exportContent() { let status = NSLocalizedString("Exporting content…", comment: "Overlay message displayed while starting content export") SVProgressHUD.setDefaultMaskType(.black) SVProgressHUD.show(withStatus: status) let trackedBlog = blog WPAppAnalytics.track(.siteSettingsExportSiteRequested, with: trackedBlog) let service = SiteManagementService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.exportContentForBlog(blog, success: { WPAppAnalytics.track(.siteSettingsExportSiteResponseOK, with: trackedBlog) let status = NSLocalizedString("Email sent!", comment: "Overlay message displayed when export content started") SVProgressHUD.showDismissibleSuccess(withStatus: status) }, failure: { error in DDLogError("Error exporting content: \(error.localizedDescription)") WPAppAnalytics.track(.siteSettingsExportSiteResponseError, with: trackedBlog) SVProgressHUD.dismiss() let errorTitle = NSLocalizedString("Export Content Error", comment: "Title of alert when export content fails") let alertController = UIAlertController(title: errorTitle, message: error.localizedDescription, preferredStyle: .alert) let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") _ = alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }) } /// Requests site purchases to determine whether site is deletable /// public func checkSiteDeletable() { tableView.deselectSelectedRowWithAnimation(true) let status = NSLocalizedString("Checking purchases…", comment: "Overlay message displayed while checking if site has premium purchases") SVProgressHUD.show(withStatus: status) WPAppAnalytics.track(.siteSettingsDeleteSitePurchasesRequested, with: blog) let service = SiteManagementService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.getActivePurchasesForBlog(blog, success: { [weak self] purchases in SVProgressHUD.dismiss() guard let strongSelf = self else { return } if purchases.isEmpty { WPAppAnalytics.track(.siteSettingsDeleteSiteAccessed, with: strongSelf.blog) strongSelf.navigationController?.pushViewController(DeleteSiteViewController.controller(strongSelf.blog), animated: true) } else { WPAppAnalytics.track(.siteSettingsDeleteSitePurchasesShown, with: strongSelf.blog) strongSelf.present(strongSelf.warnPurchasesController(), animated: true, completion: nil) } }, failure: { error in DDLogError("Error getting purchases: \(error.localizedDescription)") SVProgressHUD.dismiss() let errorTitle = NSLocalizedString("Check Purchases Error", comment: "Title of alert when getting purchases fails") let alertController = UIAlertController(title: errorTitle, message: error.localizedDescription, preferredStyle: .alert) let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }) } /// Creates purchase warning alert for Delete Site /// /// - Returns: UIAlertController /// fileprivate func warnPurchasesController() -> UIAlertController { let warnTitle = NSLocalizedString("Premium Upgrades", comment: "Title of alert when attempting to delete site with purchases") let message = NSLocalizedString("You have active premium upgrades on your site. Please cancel your upgrades prior to deleting your site.", comment: "Message alert when attempting to delete site with purchases") let alertController = UIAlertController(title: warnTitle, message: message, preferredStyle: .alert) let cancelTitle = NSLocalizedString("Cancel", comment: "Alert dismissal title") alertController.addCancelActionWithTitle(cancelTitle, handler: nil) let showTitle = NSLocalizedString("Show Purchases", comment: "Show site purchases action title") alertController.addDefaultActionWithTitle(showTitle, handler: { _ in WPAppAnalytics.track(.siteSettingsDeleteSitePurchasesShowClicked, with: self.blog) self.showPurchases() }) return alertController } /// Brings up web interface showing site purchases for cancellation /// fileprivate func showPurchases() { let purchasesUrl = "https://wordpress.com/purchases" let controller = WPWebViewController() controller.authToken = blog.authToken controller.username = blog.usernameForSite controller.password = blog.password controller.wpLoginURL = URL(string: blog.loginUrl()) controller.secureInteraction = true controller.url = URL(string: purchasesUrl) controller.loadViewIfNeeded() controller.navigationItem.titleView = nil controller.title = NSLocalizedString("Purchases", comment: "Title of screen showing site purchases") navigationController?.pushViewController(controller, animated: true) } }
gpl-2.0
f54fc5e3d1aea2bd6c53e1cb5522d539
48.231788
218
0.692494
6.108463
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/More Tab/MoreViewController.swift
1
9158
// // MoreViewController.swift // PennMobile // // Created by Zhilei Zheng on 3/17/18. // Copyright © 2018 PennLabs. All rights reserved. // import UIKit class MoreViewController: GenericTableViewController, ShowsAlert { var account: Account? fileprivate var barButton: UIBarButtonItem! private var shouldShowProfile: Bool = false override func viewDidLoad() { super.viewDidLoad() if shouldShowProfile { account = Account.getAccount() } setUpTableView() self.tableView.isHidden = true barButton = UIBarButtonItem(title: Account.isLoggedIn ? "Logout" : "Login", style: .done, target: self, action: #selector(handleLoginLogout(_:))) barButton.tintColor = UIColor.navigation } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if shouldShowProfile { let account = Account.getAccount() if self.account != account { self.account = account } } tableView.reloadData() } override func setupNavBar() { self.tabBarController?.title = "More" barButton = UIBarButtonItem(title: Account.isLoggedIn ? "Logout" : "Login", style: .done, target: self, action: #selector(handleLoginLogout(_:))) barButton.tintColor = UIColor.navigation tabBarController?.navigationItem.leftBarButtonItem = nil tabBarController?.navigationItem.rightBarButtonItem = barButton } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let topSpace: CGFloat? topSpace = self.view.safeAreaInsets.top if let topSpace = topSpace, topSpace > 0 { self.tableView.isHidden = false } } func setUpTableView() { tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.uiGroupedBackground tableView.separatorStyle = .singleLine tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 50 tableView.register(MoreCell.self, forCellReuseIdentifier: "more") tableView.register(MoreCell.self, forCellReuseIdentifier: "more-with-icon") tableView.tableFooterView = UIView() } fileprivate struct PennLink { let title: String let url: String } fileprivate let pennLinks: [PennLink] = [ PennLink(title: "Penn Labs", url: "https://pennlabs.org"), PennLink(title: "Penn Homepage", url: "https://upenn.edu"), PennLink(title: "CampusExpress", url: "https://prod.campusexpress.upenn.edu"), PennLink(title: "Canvas", url: "https://canvas.upenn.edu"), PennLink(title: "PennInTouch", url: "https://pennintouch.apps.upenn.edu"), PennLink(title: "PennPortal", url: "https://portal.apps.upenn.edu/penn_portal"), PennLink(title: "Share Your Feedback", url: "https://airtable.com/shrS98E3rj5Nw1wy6")] } extension MoreViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Notification and privacy tabs aren't shown for users that aren't logged in let rows = [Account.isLoggedIn ? 4 : 3, ControllerModel.shared.moreOrder.count, pennLinks.count] return rows[section] } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = HeaderViewCell() let titles = ["ACCOUNT", "FEATURES", "LINKS"] headerView.setUpView(title: titles[section]) return headerView } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { if indexPath.row == 0 { if let cell = tableView.dequeueReusableCell(withIdentifier: "more") as? MoreCell { cell.setUpView(with: "View your profile") cell.backgroundColor = .uiGroupedBackgroundSecondary cell.accessoryType = .disclosureIndicator return cell } } else if indexPath.row == 1 { if let cell = tableView.dequeueReusableCell(withIdentifier: "more") as? MoreCell { cell.setUpView(with: "PAC Code") cell.backgroundColor = .uiGroupedBackgroundSecondary cell.accessoryType = .disclosureIndicator return cell } } else if indexPath.row <= 3 { if let cell = tableView.dequeueReusableCell(withIdentifier: "more") as? MoreCell { cell.setUpView(with: indexPath.row == 2 ? "Notifications" : "Privacy") cell.backgroundColor = .uiGroupedBackgroundSecondary cell.accessoryType = .disclosureIndicator return cell } } } else if indexPath.section == 1 { if let cell = tableView.dequeueReusableCell(withIdentifier: "more-with-icon") as? MoreCell { cell.setUpView(with: ControllerModel.shared.moreOrder[indexPath.row], icon: ControllerModel.shared.moreIcons[indexPath.row]) cell.backgroundColor = .uiGroupedBackgroundSecondary cell.accessoryType = .disclosureIndicator return cell } } else if indexPath.section == 2 { if let cell = tableView.dequeueReusableCell(withIdentifier: "more") as? MoreCell { cell.backgroundColor = .uiGroupedBackgroundSecondary cell.setUpView(with: pennLinks[indexPath.row].title) cell.accessoryType = .disclosureIndicator return cell } } return UITableViewCell() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { if indexPath.row == 0 { let targetController = ProfilePageViewController() navigationController?.pushViewController(targetController, animated: true) } else if indexPath.row == 1 { let targetController = ControllerModel.shared.viewController(for: .pacCode) navigationController?.pushViewController(targetController, animated: true) } else if indexPath.row <= 3 { let targetController = ControllerModel.shared.viewController(for: indexPath.row == 2 ? .notifications : .privacy) navigationController?.pushViewController(targetController, animated: true) } } else if indexPath.section == 1 { let targetController = ControllerModel.shared.viewController(for: ControllerModel.shared.moreOrder[indexPath.row]) navigationController?.pushViewController(targetController, animated: true) } else if indexPath.section == 2 { if let url = URL(string: pennLinks[indexPath.row].url) { UIApplication.shared.open(url, options: [:]) } } } } // MARK: - Login/Logout extension MoreViewController { @objc fileprivate func handleLoginLogout(_ sender: Any) { if Account.isLoggedIn { let alertController = UIAlertController(title: "Are you sure?", message: "Please confirm that you wish to logout.", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) alertController.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (_) in DispatchQueue.main.async { AppDelegate.shared.rootViewController.clearAccountData() AppDelegate.shared.rootViewController.switchToLogout() } })) present(alertController, animated: true, completion: nil) } else { let llc = LabsLoginController { (success) in DispatchQueue.main.async { self.loginCompletion(success) } } let nvc = UINavigationController(rootViewController: llc) present(nvc, animated: true, completion: nil) } } func loginCompletion(_ successful: Bool) { if successful { if shouldShowProfile { self.account = Account.getAccount() } tableView.reloadData() tabBarController?.navigationItem.rightBarButtonItem?.title = "Logout" // Clear cache so that home title updates with new first name guard let homeVC = ControllerModel.shared.viewController(for: .home) as? HomeViewController else { return } homeVC.clearCache() } else { showAlert(withMsg: "Something went wrong. Please try again.", title: "Uh oh!", completion: nil) } } }
mit
3dd9275b55e92260d6725e02d1b674c2
41.99061
153
0.623021
5.333139
false
false
false
false
mddub/G4ShareSpy
G4ShareSpyTests/GlucoseHistoryMessageTests.swift
1
3102
// // GlucoseHistoryMessageTests.swift // G4ShareSpyTests // // Created by Mark on 7/21/16. // Copyright © 2016 Mark Wilson. All rights reserved. // import XCTest @testable import G4ShareSpy let historyBytesHex = [ "0116020130d200001a0000000402880500000000", "00000000000000000000fe4d02cf360ed77b360e", "590015596f2ed0360e037d360e5c001455025ad1", "360e2f7e360e6b00148d3586d2360e5b7f360e6c", "0013b91ab2d3360e8780360e670014501cded436", "0eb381360e68001416ec0ad6360edf82360e6a00", "1468ba37d7360e0b84360e680014c36262d8360e", "3785360e5b0014277e8ed9360e6386360e4e0015", "add8bada360e8f87360e43001678bae6db360ebb", "88360e3b0016fd1b12dd360ee789360e36001553", "843ede360e138b360e370014202e6adf360e3f8c", "360e34001446ac96e0360e6b8d360e3500145ccf", "c2e1360e978e360e350014a553eee2360ec38f36", "0e39001449a01ae4360eee90360e3e0014626e46", "e5360e1a92360e400014114572e6360e4693360e", "480014230e9ee7360e7294360e4b0014f0fccae8", "360e9e95360e4b0014c6e5f6e9360eca96360e59", "009437df22eb360ef697360e580094ceb122eb36", "0ef797360e588014bf83ffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffffffffffffffffffff", "ffffffffffffffffffffffff6d52", ].joined(separator: "") class GlucoseHistoryMessageTests: XCTestCase { func testHistory() { let data = Data(hexadecimalString: historyBytesHex)! let history = GlucoseHistoryMessage(data: data) XCTAssertNotNil(history) if let history = history { XCTAssertEqual(history.records.count, 26) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" XCTAssertEqual(history.records[0].sequence, 53808) XCTAssertEqual(history.records[0].glucose, 89) XCTAssertEqual(history.records[0].trend, 5) XCTAssertEqual(history.records[0].isDisplayOnly, false) XCTAssertEqual(history.records[0].systemTime, 238472962) XCTAssertEqual(history.records[0].wallTime, dateFormatter.date(from: "2016-07-23T4:34:31Z")) XCTAssertEqual(history.records[25].sequence, 53833) XCTAssertEqual(history.records[25].glucose, 88) XCTAssertEqual(history.records[25].trend, 4) XCTAssertEqual(history.records[25].isDisplayOnly, true) XCTAssertEqual(history.records[25].systemTime, 238480162) XCTAssertEqual(history.records[25].wallTime, dateFormatter.date(from: "2016-07-23T06:34:31Z")) } } func testBadCRC() { let data = Data( hexadecimalString: historyBytesHex.substring(to: historyBytesHex.characters.index(historyBytesHex.endIndex, offsetBy: -1)) + "3" )! XCTAssertNil(GlucoseHistoryMessage(data: data)) } }
mit
0e4541e0f24e612cb2fa3725ea8df86b
37.7625
140
0.731699
3.449388
false
true
false
false
gizmosachin/VolumeBar
Sources/VolumeBarStyle.swift
1
3170
// // VolumeBarStyle.swift // // Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// A value type wrapping parameters used to customize the appearance of VolumeBar. public struct VolumeBarStyle { // MARK: Layout /// The height of the bar that will be displayed on screen. public var height: CGFloat = 10 /// Insets from the top edge of the device screen. /// /// If `respectsSafeAreaInsets` is `false`, VolumeBar will be inset from screen edges /// by exactly these insets. /// /// If `respectsSafeAreaInsets` is `true`, VolumeBar will be /// inset by the sum of the safe area insets of the device and `edgeInsets`. /// /// - seealso: `respectsSafeAreaInsets` public var edgeInsets: UIEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) /// Whether or not VolumeBar should respect `safeAreaInsets` when displaying. /// /// - seealso: `edgeInsets` public var respectsSafeAreaInsets: Bool = false // MARK: Appearance /// The number of segments that the VolumeBar is made up of. /// Use this with `segmentSpacing` to give VolumeBar a segmented appearance. /// /// The default value, 16, is equal to the number of volume steps on iOS devices. /// (When the volume is 0%, pressing volume up exactly 16 times will cause the volume to reach 100%) /// /// - seealso: `segmentSpacing` public var segmentCount: UInt = 16 /// The number of points between individual segments in the VolumeBar. /// /// - seealso: `segmentCount` public var segmentSpacing: CGFloat = 0 /// The corner radius of the VolumeBar. public var cornerRadius: CGFloat = 0 // MARK: Colors /// The color of the progress displayed on the bar. public var progressTintColor: UIColor = .black /// The background color of the track. public var trackTintColor: UIColor = UIColor.black.withAlphaComponent(0.5) /// The background color behind the track view. /// This should match the color of the view behind the VolumeBar, which might be the color of your navigation bar. public var backgroundColor: UIColor = .white }
mit
4b6f9c32cb3b27e0ff5a2014b9c62c01
39.126582
115
0.730599
4.171053
false
false
false
false
huonw/swift
test/decl/var/properties.swift
1
31149
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} struct X { } var _x: X class SomeClass {} func takeTrailingClosure(_ fn: () -> ()) -> Int {} func takeIntTrailingClosure(_ fn: () -> Int) -> Int {} //===--- // Stored properties //===--- var stored_prop_1: Int = 0 var stored_prop_2: Int = takeTrailingClosure {} //===--- // Computed properties -- basic parsing //===--- var a1: X { get { return _x } } var a2: X { get { return _x } set { _x = newValue } } var a3: X { get { return _x } set(newValue) { _x = newValue } } var a4: X { set { _x = newValue } get { return _x } } var a5: X { set(newValue) { _x = newValue } get { return _x } } // Reading/writing properties func accept_x(_ x: X) { } func accept_x_inout(_ x: inout X) { } func test_global_properties(_ x: X) { accept_x(a1) accept_x(a2) accept_x(a3) accept_x(a4) accept_x(a5) a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}} a2 = x a3 = x a4 = x a5 = x accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}} accept_x_inout(&a2) accept_x_inout(&a3) accept_x_inout(&a4) accept_x_inout(&a5) } //===--- Implicit 'get'. var implicitGet1: X { return _x } var implicitGet2: Int { var zzz = 0 // For the purpose of this test, any other function attribute work as well. @inline(__always) func foo() {} return 0 } var implicitGet3: Int { @inline(__always) func foo() {} return 0 } // Here we used apply weak to the getter itself, not to the variable. var x15: Int { // For the purpose of this test we need to use an attribute that cannot be // applied to the getter. weak var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}} // expected-warning@-1 {{instance will be immediately deallocated because variable 'foo' is 'weak'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'foo' declared here}} return 0 } // Disambiguated as stored property with a trailing closure in the initializer. // var disambiguateGetSet1a: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get {} } var disambiguateGetSet1b: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get { return 42 } } var disambiguateGetSet1c: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set {} // expected-error {{variable with a setter must also have a getter}} } var disambiguateGetSet1d: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set(newValue) {} // expected-error {{variable with a setter must also have a getter}} } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet2() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { get {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet2Attr() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} get {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet3() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { set {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet3Attr() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet4() { func set(_ x: Int, fn: () -> ()) {} let newValue: Int = 0 var a: Int = takeTrailingClosure { set(newValue) {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet4Attr() { func set(_ x: Int, fn: () -> ()) {} var newValue: Int = 0 var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set(newValue) {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. var disambiguateImplicitGet1: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} return 42 } var disambiguateImplicitGet2: Int = takeIntTrailingClosure { return 42 } //===--- // Observed properties //===--- class C { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } } protocol TrivialInit { init() } class CT<T : TrivialInit> { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } var prop5: T? = nil { didSet { } } var prop6: T? = nil { willSet { } } var prop7 = T() { didSet { } } var prop8 = T() { willSet { } } } //===--- // Parsing problems //===--- var computed_prop_with_init_1: X { get {} } = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}} var x2 { // expected-error{{computed property must have an explicit type}} {{7-7=: <# Type #>}} expected-error{{type annotation missing in pattern}} get { return _x } } var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}} get { return _x } } var duplicateAccessors1: X { get { // expected-note {{previous definition of getter is here}} return _x } set { // expected-note {{previous definition of setter is here}} _x = value } get { // expected-error {{duplicate definition of getter}} return _x } set(v) { // expected-error {{duplicate definition of setter}} _x = v } } var duplicateAccessors2: Int = 0 { willSet { // expected-note {{previous definition of willSet is here}} } didSet { // expected-note {{previous definition of didSet is here}} } willSet { // expected-error {{duplicate definition of willSet}} } didSet { // expected-error {{duplicate definition of didSet}} } } var extraTokensInAccessorBlock1: X { get {} a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} } var extraTokensInAccessorBlock2: X { get {} weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} a } var extraTokensInAccessorBlock3: X { get {} a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} set {} get {} } var extraTokensInAccessorBlock4: X { get blah wibble // expected-error{{expected '{' to start getter definition}} } var extraTokensInAccessorBlock5: X { set blah wibble // expected-error{{expected '{' to start setter definition}} } var extraTokensInAccessorBlock6: X { willSet blah wibble // expected-error{{expected '{' to start willSet definition}} } var extraTokensInAccessorBlock7: X { didSet blah wibble // expected-error{{expected '{' to start didSet definition}} } var extraTokensInAccessorBlock8: X { foo // expected-error {{use of unresolved identifier 'foo'}} get {} // expected-error{{use of unresolved identifier 'get'}} set {} // expected-error{{use of unresolved identifier 'set'}} } var extraTokensInAccessorBlock9: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } struct extraTokensInAccessorBlock10 { var x: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } init() {} } var x9: X { get ( ) { // expected-error{{expected '{' to start getter definition}} } } var x10: X { set ( : ) { // expected-error{{expected setter parameter name}} } get {} } var x11 : X { set { // expected-error{{variable with a setter must also have a getter}} } } var x12: X { set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start setter definition}} } } var x13: X {} // expected-error {{computed property must have accessors specified}} // Type checking problems struct Y { } var y: Y var x20: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set { y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x21: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set(v) { y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 } var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 }, x26: Int // Properties of struct/enum/extensions struct S { var _backed_x: X, _backed_x2: X var x: X { get { return _backed_x } mutating set(v) { _backed_x = v } } } extension S { var x2: X { get { return self._backed_x2 } mutating set { _backed_x2 = newValue } } var x3: X { get { return self._backed_x2 } } } struct StructWithExtension1 { var foo: Int static var fooStatic = 4 } extension StructWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } class ClassWithExtension1 { var foo: Int = 0 class var fooStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } extension ClassWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} class var fooExtStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } enum EnumWithExtension1 { var foo: Int // expected-error {{enums must not contain stored properties}} static var fooStatic = 4 } extension EnumWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } protocol ProtocolWithExtension1 { var foo: Int { get } static var fooStatic : Int { get } } extension ProtocolWithExtension1 { var fooExt: Int // expected-error{{extensions must not contain stored properties}} static var fooExtStatic = 4 // expected-error{{static stored properties not supported in protocol extensions}} } protocol ProtocolWithExtension2 { var bar: String { get } } struct StructureImplementingProtocolWithExtension2: ProtocolWithExtension2 { let bar: String } extension ProtocolWithExtension2 { static let baz: ProtocolWithExtension2 = StructureImplementingProtocolWithExtension2(bar: "baz") // expected-error{{static stored properties not supported in protocol extensions}} } func getS() -> S { let s: S return s } func test_extension_properties(_ s: inout S, x: inout X) { accept_x(s.x) accept_x(s.x2) accept_x(s.x3) accept_x(getS().x) accept_x(getS().x2) accept_x(getS().x3) s.x = x s.x2 = x s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} x = getS().x x = getS().x2 x = getS().x3 accept_x_inout(&s.x) accept_x_inout(&s.x2) accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} } extension S { mutating func test(other_x: inout X) { x = other_x x2 = other_x x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}} other_x = x other_x = x2 other_x = x3 } } // Accessor on non-settable type struct Aleph { var b: Beth { get { return Beth(c: 1) } } } struct Beth { var c: Int } func accept_int_inout(_ c: inout Int) { } func accept_int(_ c: Int) { } func test_settable_of_nonsettable(_ a: Aleph) { a.b.c = 1 // expected-error{{cannot assign}} let x:Int = a.b.c _ = x accept_int(a.b.c) accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}} } // TODO: Static properties are only implemented for nongeneric structs yet. struct MonoStruct { static var foo: Int = 0 static var (bar, bas): (String, UnicodeScalar) = ("zero", "0") static var zim: UInt8 { return 0 } static var zang = UnicodeScalar("\0") static var zung: UInt16 { get { return 0 } set {} } var a: Double var b: Double } struct MonoStructOneProperty { static var foo: Int = 22 } enum MonoEnum { static var foo: Int = 0 static var zim: UInt8 { return 0 } } struct GenStruct<T> { static var foo: Int = 0 // expected-error{{static stored properties not supported in generic types}} } class MonoClass { class var foo: Int = 0 // expected-error{{class stored properties not supported in classes; did you mean 'static'?}} } protocol Proto { static var foo: Int { get } } func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) { return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas, MonoStruct.zim) } func staticPropRefThroughInstance(_ foo: MonoStruct) -> Int { return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}} } func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct { return MonoStruct(a: 1.2, b: 3.4) } func getSetStaticProperties() -> (UInt8, UInt16) { MonoStruct.zim = 12 // expected-error{{cannot assign}} MonoStruct.zung = 34 return (MonoStruct.zim, MonoStruct.zung) } var selfRefTopLevel: Int { return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}} } var selfRefTopLevelSetter: Int { get { return 42 } set { markUsed(selfRefTopLevelSetter) // no-warning selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}} } } var selfRefTopLevelSilenced: Int { get { return properties.selfRefTopLevelSilenced // no-warning } set { properties.selfRefTopLevelSilenced = newValue // no-warning } } class SelfRefProperties { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}} setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}} } } var silenced: Int { get { return self.silenced // no-warning } set { self.silenced = newValue // no-warning } } var someOtherInstance: SelfRefProperties = SelfRefProperties() var delegatingVar: Int { // This particular example causes infinite access, but it's easily possible // for the delegating instance to do something else. return someOtherInstance.delegatingVar // no-warning } } func selfRefLocal() { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} } } } struct WillSetDidSetProperties { var a: Int { willSet { markUsed("almost") } didSet { markUsed("here") } } var b: Int { willSet { markUsed(b) markUsed(newValue) } } var c: Int { willSet(newC) { markUsed(c) markUsed(newC) } } var d: Int { didSet { markUsed("woot") } get { // expected-error {{didSet variable must not also have a get specifier}} return 4 } } var e: Int { willSet { markUsed("woot") } set { // expected-error {{willSet variable must not also have a set specifier}} return 4 } } var f: Int { willSet(5) {} // expected-error {{expected willSet parameter name}} didSet(^) {} // expected-error {{expected didSet parameter name}} } var g: Int { willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start willSet definition}} } var h: Int { didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start didSet definition}} } // didSet/willSet with initializers. // Disambiguate trailing closures. var disambiguate1: Int = 42 { // simple initializer, simple label didSet { markUsed("eek") } } var disambiguate2: Int = 42 { // simple initializer, complex label willSet(v) { markUsed("eek") } } var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case. willSet(v) { markUsed("eek") } } var disambiguate4: Int = 42 { willSet {} } var disambiguate5: Int = 42 { didSet {} } var disambiguate6: Int = takeTrailingClosure { @inline(__always) func f() {} return () } var inferred1 = 42 { willSet { markUsed("almost") } didSet { markUsed("here") } } var inferred2 = 40 { willSet { markUsed(b) markUsed(newValue) } } var inferred3 = 50 { willSet(newC) { markUsed(c) markUsed(newC) } } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate1 { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start willSet definition}} } } struct WillSetDidSetDisambiguate1Attr { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start willSet definition}} } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate2 { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } struct WillSetDidSetDisambiguate2Attr { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } // No need to disambiguate -- this is clearly a function call. func willSet(_: () -> Int) {} struct WillSetDidSetDisambiguate3 { var x: Int = takeTrailingClosure({ willSet { 42 } }) } protocol ProtocolGetSet1 { var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} } protocol ProtocolGetSet2 { var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} } protocol ProtocolGetSet3 { var a: Int { get } } protocol ProtocolGetSet4 { var a: Int { set } // expected-error {{variable with a setter must also have a getter}} } protocol ProtocolGetSet5 { var a: Int { get set } } protocol ProtocolGetSet6 { var a: Int { set get } } protocol ProtocolWillSetDidSet1 { var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet2 { var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet3 { var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet4 { var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}} didSet {} } var globalDidsetWillSet2 : Int = 42 { didSet {} } class Box { var num: Int init(num: Int) { self.num = num } } func double(_ val: inout Int) { val *= 2 } class ObservingPropertiesNotMutableInWillSet { var anotherObj : ObservingPropertiesNotMutableInWillSet init() {} var property: Int = 42 { willSet { // <rdar://problem/16826319> willSet immutability behavior is incorrect anotherObj.property = 19 // ok property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&self.property) // no-warning } } // <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load var _oldBox : Int weak var weakProperty: Box? { willSet { _oldBox = weakProperty?.num ?? -1 } } func localCase() { var localProperty: Int = 42 { willSet { localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}} } } } } func doLater(_ fn : () -> ()) {} // rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet class MutableInWillSetInClosureClass { var bounds: Int = 0 { willSet { let oldBounds = bounds doLater { self.bounds = oldBounds } } } } // <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties var didSetPropertyTakingOldValue : Int = 0 { didSet(oldValue) { markUsed(oldValue) markUsed(didSetPropertyTakingOldValue) } } // rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types protocol AbstractPropertyProtocol { associatedtype Index var a : Index { get } } struct AbstractPropertyStruct<T> : AbstractPropertyProtocol { typealias Index = T var a : T } // Allow _silgen_name accessors without bodies. var _silgen_nameGet1: Int { @_silgen_name("get1") get set { } } var _silgen_nameGet2: Int { set { } @_silgen_name("get2") get } var _silgen_nameGet3: Int { @_silgen_name("get3") get } var _silgen_nameGetSet: Int { @_silgen_name("get4") get @_silgen_name("set4") set } // <rdar://problem/16375910> reject observing properties overriding readonly properties class Base16375910 { var x : Int { // expected-note {{attempt to override property here}} return 42 } var y : Int { // expected-note {{attempt to override property here}} get { return 4 } set {} } } class Derived16375910 : Base16375910 { override init() {} override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}} willSet { markUsed(newValue) } } } // <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth class Derived16382967 : Base16375910 { override var y : Int { willSet { markUsed(newValue) } } } // <rdar://problem/16659058> Read-write properties can be made read-only in a property override class Derived16659058 : Base16375910 { override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}} get { return 42 } } } // <rdar://problem/16406886> Observing properties don't work with ownership types struct PropertiesWithOwnershipTypes { unowned var p1 : SomeClass { didSet { } } init(res: SomeClass) { p1 = res } } // <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers class Test16608609 { let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}} {{4-7=var}} willSet { } didSet { } } } // <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter" class rdar16941124Base { var x = 0 } class rdar16941124Derived : rdar16941124Base { var y = 0 override var x: Int { didSet { y = x + 1 // no warning. } } } // Overrides of properties with custom ownership. class OwnershipBase { class var defaultObject: AnyObject { fatalError("") } var strongVar: AnyObject? // expected-note{{overridden declaration is here}} weak var weakVar: AnyObject? // FIXME: These should be optional to properly test overriding. unowned var unownedVar: AnyObject = defaultObject unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}} } class OwnershipExplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } } class OwnershipImplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } } class OwnershipBadSub : OwnershipBase { override weak var strongVar: AnyObject? { // expected-error {{cannot override 'strong' property with 'weak' property}} didSet {} } override unowned var weakVar: AnyObject? { // expected-error {{'unowned' variable cannot have optional type}} didSet {} } override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}} didSet {} } override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override 'unowned(unsafe)' property with 'unowned' property}} didSet {} } } // <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension class rdar17391625 { var prop = 42 // expected-note {{overri}} } extension rdar17391625 { var someStoredVar: Int // expected-error {{extensions must not contain stored properties}} var someObservedVar: Int { // expected-error {{extensions must not contain stored properties}} didSet { } } } class rdar17391625derived : rdar17391625 { } extension rdar17391625derived { // Not a stored property, computed because it is an override. override var prop: Int { // expected-error {{overri}} didSet { } } } // <rdar://problem/27671033> Crash when defining property inside an invalid extension // (This extension is no longer invalid.) public protocol rdar27671033P {} struct rdar27671033S<Key, Value> {} extension rdar27671033S : rdar27671033P where Key == String { let d = rdar27671033S<Int, Int>() // expected-error {{extensions must not contain stored properties}} } // <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property struct r19874152S1 { let number : Int = 42 } _ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S1() // Ok struct r19874152S2 { var number : Int = 42 } _ = r19874152S2(number:64) // Ok, property is a var. _ = r19874152S2() // Ok struct r19874152S3 { // expected-note {{'init(flavor:)' declared here}} let number : Int = 42 let flavor : Int } _ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavor:')}} {{17-23=flavor}} _ = r19874152S3(number:64, flavor: 17) // expected-error {{extra argument 'number' in call}} _ = r19874152S3(flavor: 17) // ok _ = r19874152S3() // expected-error {{missing argument for parameter 'flavor' in call}} struct r19874152S4 { let number : Int? = nil } _ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S4() // Ok struct r19874152S5 { } _ = r19874152S5() // ok struct r19874152S6 { let (a,b) = (1,2) // Cannot handle implicit synth of this yet. } _ = r19874152S5() // ok // <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:] class r24314506 { // expected-error {{class 'r24314506' has no initializers}} var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}} } // https://bugs.swift.org/browse/SR-3893 // Generic type is not inferenced from its initial value for properties with // will/didSet struct SR3893Box<Foo> { let value: Foo } struct SR3893 { // Each of these "bad" properties used to produce errors. var bad: SR3893Box = SR3893Box(value: 0) { willSet { print(newValue.value) } } var bad2: SR3893Box = SR3893Box(value: 0) { willSet(new) { print(new.value) } } var bad3: SR3893Box = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var good: SR3893Box<Int> = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var plain: SR3893Box = SR3893Box(value: 0) } protocol WFI_P1 : class {} protocol WFI_P2 : class {} class WeakFixItTest { init() {} // expected-error @+1 {{'weak' variable should have optional type 'WeakFixItTest?'}} {{31-31=?}} weak var foo : WeakFixItTest // expected-error @+1 {{'weak' variable should have optional type '(WFI_P1 & WFI_P2)?'}} {{18-18=(}} {{33-33=)?}} weak var bar : WFI_P1 & WFI_P2 }
apache-2.0
d6933346ab35dc949acf6b41be779a81
23.899281
188
0.656907
3.74297
false
false
false
false
kylef/cocoapods-deintegrate
spec/fixtures/Project_Pre_1.0.0/Frameworks/Pods/QueryKit/QueryKit/QuerySet.swift
11
7483
// // QuerySet.swift // QueryKit // // Created by Kyle Fuller on 06/07/2014. // // import Foundation import CoreData /// Represents a lazy database lookup for a set of objects. public class QuerySet<T : NSManagedObject> : SequenceType, Equatable { /// Returns the managed object context that will be used to execute any requests. public let context:NSManagedObjectContext /// Returns the name of the entity the request is configured to fetch. public let entityName:String /// Returns the sort descriptors of the receiver. public let sortDescriptors = [NSSortDescriptor]() /// Returns the predicate of the receiver. public let predicate:NSPredicate? public let range:Range<Int>? // MARK: Initialization public init(_ context:NSManagedObjectContext, _ entityName:String) { self.context = context self.entityName = entityName } public init(queryset:QuerySet<T>, sortDescriptors:[NSSortDescriptor]?, predicate:NSPredicate?, range:Range<Int>?) { self.context = queryset.context self.entityName = queryset.entityName if let sortDescriptors = sortDescriptors { self.sortDescriptors = sortDescriptors } self.predicate = predicate self.range = range } // MARK: Sorting /// Returns a new QuerySet containing objects ordered by the given sort descriptor. public func orderBy(sortDescriptor:NSSortDescriptor) -> QuerySet<T> { return orderBy([sortDescriptor]) } /// Returns a new QuerySet containing objects ordered by the given sort descriptors. public func orderBy(sortDescriptors:[NSSortDescriptor]) -> QuerySet<T> { return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:predicate, range:range) } /// Reverses the ordering of the QuerySet public func reverse() -> QuerySet<T> { return QuerySet(queryset:self, sortDescriptors:sortDescriptors.reverse(), predicate:predicate, range:range) } // MARK: Filtering /// Returns a new QuerySet containing objects that match the given predicate. public func filter(predicate:NSPredicate) -> QuerySet<T> { var futurePredicate = predicate if let existingPredicate = self.predicate { futurePredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [existingPredicate, predicate]) } return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:futurePredicate, range:range) } /// Returns a new QuerySet containing objects that match the given predicates. public func filter(predicates:[NSPredicate]) -> QuerySet<T> { let newPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: predicates) return filter(newPredicate) } /// Returns a new QuerySet containing objects that exclude the given predicate. public func exclude(predicate:NSPredicate) -> QuerySet<T> { let excludePredicate = NSCompoundPredicate(type: NSCompoundPredicateType.NotPredicateType, subpredicates: [predicate]) return filter(excludePredicate) } /// Returns a new QuerySet containing objects that exclude the given predicates. public func exclude(predicates:[NSPredicate]) -> QuerySet<T> { let excludePredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: predicates) return exclude(excludePredicate) } // MARK: Subscripting public subscript(index: Int) -> (object:T?, error:NSError?) { get { var request = fetchRequest request.fetchOffset = index request.fetchLimit = 1 var error:NSError? if let items = context.executeFetchRequest(request, error:&error) { return (object:items.first as T?, error:error) } else { return (object: nil, error: error) } } } /// Returns the object at the specified index. public subscript(index: Int) -> T? { get { return self[index].object } } public subscript(range:Range<Int>) -> QuerySet<T> { get { var fullRange = range if let currentRange = self.range { fullRange = Range<Int>(start: currentRange.startIndex + range.startIndex, end: range.endIndex) } return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:predicate, range:fullRange) } } // Mark: Getters public var first: T? { get { return self[0].object } } // MARK: Conversion public var fetchRequest:NSFetchRequest { var request = NSFetchRequest(entityName:entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors if let range = range { request.fetchOffset = range.startIndex request.fetchLimit = range.endIndex - range.startIndex } return request } public func array() -> (objects:([T]?), error:NSError?) { var error:NSError? var objects = context.executeFetchRequest(fetchRequest, error:&error) as? [T] return (objects:objects, error:error) } public func array() -> [T]? { return array().objects } // MARK: Count public func count() -> (count:Int?, error:NSError?) { var error:NSError? var count:Int? = context.countForFetchRequest(fetchRequest, error: &error) if count! == NSNotFound { count = nil } return (count:count, error:error) } /// Returns the count of objects matching the QuerySet. public func count() -> Int? { return count().count } // MARK: Exists /** Returns true if the QuerySet contains any results, and false if not. :note: Returns nil if the operation could not be completed. */ public func exists() -> Bool? { let result:Int? = count() if let result = result { return result > 0 } return nil } // MARK: Deletion /// Deletes all the objects matching the QuerySet. public func delete() -> (count:Int, error:NSError?) { var result = array() as (objects:([T]?), error:NSError?) var deletedCount = 0 if let objects = result.objects { for object in objects { context.deleteObject(object) } deletedCount = objects.count } return (count:deletedCount, error:result.error) } // MARK: Sequence public func generate() -> IndexingGenerator<Array<T>> { var result = self.array() as (objects:([T]?), error:NSError?) if let objects = result.objects { return objects.generate() } return [].generate() } } public func == <T : NSManagedObject>(lhs: QuerySet<T>, rhs: QuerySet<T>) -> Bool { let context = lhs.context == rhs.context let entityName = lhs.entityName == rhs.entityName let sortDescriptors = lhs.sortDescriptors == rhs.sortDescriptors let predicate = lhs.predicate == rhs.predicate let startIndex = lhs.range?.startIndex == rhs.range?.startIndex let endIndex = lhs.range?.endIndex == rhs.range?.endIndex return context && entityName && sortDescriptors && predicate && startIndex && endIndex }
mit
37eb1cf3ad5f0ae0299abccddceb7813
30.57384
144
0.643191
4.975399
false
false
false
false
vimfung/LuaScriptCore
Sample/iOS_OSX/Sample-iOS-Swift/ModuleViewControllers/HttpModuleViewController.swift
1
1064
// // HttpModuleViewController.swift // Sample-iOS-Swift // // Created by 冯鸿杰 on 2018/8/21. // Copyright © 2018年 vimfung. All rights reserved. // import UIKit import LuaScriptCore_iOS_Swift class HttpModuleViewController: UITableViewController { let context : LuaContext = LuaContext(); override func viewDidLoad() { context.onException { (msg) in print("lua exception = \(msg!)"); } _ = context.evalScript(filePath: "HTTP-Sample.lua"); } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: _ = context.evalScript(script: "HTTP_Sample_get()"); case 1: _ = context.evalScript(script: "HTTP_Sample_post()"); case 2: _ = context.evalScript(script: "HTTP_Sample_upload()"); case 3: _ = context.evalScript(script: "HTTP_Sample_download()"); default: break; } } }
apache-2.0
0ee5ba90b4ecbded2b58fa06bf0bf256
24.119048
92
0.56872
4.236948
false
false
false
false
danger/danger-swift
Sources/Danger/Danger.swift
1
2866
import Foundation #if os(Linux) import Glibc #else import Darwin.C #endif import Logger // MARK: - DangerRunner final class DangerRunner { static let shared = DangerRunner() let logger: Logger let dsl: DangerDSL let outputPath: String var results = DangerResults() { didSet { dumpResults() } } private init() { let isVerbose = CommandLine.arguments.contains("--verbose") || (ProcessInfo.processInfo.environment["DEBUG"] != nil) let isSilent = CommandLine.arguments.contains("--silent") logger = Logger(isVerbose: isVerbose, isSilent: isSilent) logger.debug("Ran with: \(CommandLine.arguments.joined(separator: " "))") let cliLength = CommandLine.arguments.count guard cliLength - 2 > 0 else { logger.logError("To execute Danger run danger-swift ci, " + "danger-swift pr or danger-swift local on your terminal") exit(1) } let dslJSONArg: String? = CommandLine.arguments[cliLength - 2] let outputJSONPath = CommandLine.arguments[cliLength - 1] guard let dslJSONPath = dslJSONArg else { logger.logError("could not find DSL JSON arg") exit(1) } guard let dslJSONContents = FileManager.default.contents(atPath: dslJSONPath) else { logger.logError("could not find DSL JSON at path: \(dslJSONPath)") exit(1) } do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(DateFormatter.dateFormatterHandler) logger.debug("Decoding the DSL into Swift types") dsl = try decoder.decode(DSL.self, from: dslJSONContents).danger } catch { logger.logError("Failed to parse JSON:", error) exit(1) } logger.debug("Setting up to dump results") outputPath = outputJSONPath dumpResults() } private func dumpResults() { logger.debug("Sending results back to Danger") do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(results) if !FileManager.default.createFile(atPath: outputPath, contents: data, attributes: nil) { logger.logError("Could not create a temporary file " + "for the Dangerfile DSL at: \(outputPath)") exit(0) } } catch { logger.logError("Failed to generate result JSON:", error) exit(1) } } } // MARK: - Public Functions // swiftlint:disable:next identifier_name public func Danger() -> DangerDSL { DangerRunner.shared.dsl }
mit
06fc7332e2361ae9a58055671b9e9170
29.817204
92
0.578507
4.833052
false
false
false
false
brentdax/swift
test/stdlib/UnsafeRawBufferPointer.swift
8
16408
// RUN: %target-run-simple-swiftgyb // REQUIRES: executable_test // // Test corner cases specific to UnsafeRawBufferPointer. // General Collection behavior tests are in // validation-test/stdlib/UnsafeBufferPointer.swift. // FIXME: The optimized-build behavior of UnsafeBufferPointer bounds/overflow // checking cannot be tested. The standard library always compiles with debug // checking enabled, so the behavior of the optimized test depends on whether // the inlining heuristics decide to inline these methods. To fix this, we need // a way to force @inlinable UnsafeBufferPointer methods to be emitted inside // the client code, and thereby subject the stdlib implementation to the test // case's compile options. // // REQUIRES: swift_test_mode_optimize_none import StdlibUnittest var UnsafeRawBufferPointerTestSuite = TestSuite("UnsafeRawBufferPointer") // View an in-memory value's bytes. // Use copyBytes to overwrite the value's bytes. UnsafeRawBufferPointerTestSuite.test("initFromValue") { var value1: Int32 = -1 var value2: Int32 = 0 // Immutable view of value1's bytes. withUnsafeBytes(of: &value1) { bytes1 in expectEqual(bytes1.count, 4) for b in bytes1 { expectEqual(b, 0xFF) } // Mutable view of value2's bytes. withUnsafeMutableBytes(of: &value2) { bytes2 in expectEqual(bytes1.count, bytes2.count) bytes2.copyMemory(from: bytes1) } } expectEqual(value2, value1) } // Test mutability and subscript getter/setters. UnsafeRawBufferPointerTestSuite.test("nonmutating_subscript_setter") { var value1: Int32 = -1 var value2: Int32 = 0 withUnsafeMutableBytes(of: &value1) { bytes1 in withUnsafeMutableBytes(of: &value2) { bytes2 in bytes2[0..<bytes2.count] = bytes1[0..<bytes1.count] } } expectEqual(value2, value1) let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 4, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } buffer.copyBytes(from: [0, 1, 2, 3] as [UInt8]) let leftBytes = buffer[0..<2] // Subscript assign. var rightBytes = buffer[2..<4] buffer[2..<4] = leftBytes expectEqualSequence(leftBytes, rightBytes) // Subscript assign into a `var` mutable slice. buffer.copyBytes(from: [0, 1, 2, 3] as [UInt8]) rightBytes[2..<4] = leftBytes expectEqualSequence(leftBytes, rightBytes) } // View an array's elements as bytes. // Use copyBytes to overwrite the array element's bytes. UnsafeRawBufferPointerTestSuite.test("initFromArray") { let array1: [Int32] = [0, 1, 2, 3] var array2 = [Int32](repeating: 0, count: 4) // Immutable view of array1's bytes. array1.withUnsafeBytes { bytes1 in expectEqual(bytes1.count, 16) for (i, b) in bytes1.enumerated() { var num = i #if _endian(big) num = num + 1 #endif if num % 4 == 0 { expectEqual(Int(b), i / 4) } else { expectEqual(b, 0) } } // Mutable view of array2's bytes. array2.withUnsafeMutableBytes { bytes2 in expectEqual(bytes1.count, bytes2.count) bytes2.copyMemory(from: bytes1) } } expectEqual(array2, array1) } UnsafeRawBufferPointerTestSuite.test("initializeMemory(as:from:).underflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 30, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let source = stride(from: 5 as Int64, to: 0, by: -1) if _isDebugAssertConfiguration() { expectCrashLater() } var (it, bound) = buffer.initializeMemory(as: Int64.self, from: source) let idx = bound.endIndex * MemoryLayout<Int64>.stride expectEqual(it.next()!, 2) expectEqual(idx, 24) let expected: [Int64] = [5,4,3] expected.withUnsafeBytes { expectEqualSequence($0,buffer[0..<idx]) } expectEqualSequence([5, 4, 3],bound) } UnsafeRawBufferPointerTestSuite.test("initializeMemory(as:from:).overflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 30, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let source: [Int64] = [5, 4, 3, 2, 1] if _isDebugAssertConfiguration() { expectCrashLater() } var (it,bound) = buffer.initializeMemory(as: Int64.self, from: source) let idx = bound.endIndex * MemoryLayout<Int64>.stride expectEqual(it.next()!, 2) expectEqual(idx, 24) let expected: [Int64] = [5,4,3] expected.withUnsafeBytes { expectEqualSequence($0,buffer[0..<idx]) } expectEqualSequence([5, 4, 3],bound) } UnsafeRawBufferPointerTestSuite.test("initializeMemory(as:from:).exact") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 24, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let source: [Int64] = [5, 4, 3] var (it,bound) = buffer.initializeMemory(as: Int64.self, from: source) let idx = bound.endIndex * MemoryLayout<Int64>.stride expectNil(it.next()) expectEqual(idx, buffer.endIndex) source.withUnsafeBytes { expectEqualSequence($0,buffer) } expectEqualSequence([5, 4, 3],bound) } UnsafeRawBufferPointerTestSuite.test("initializeMemory(as:from:).invalidNilPtr") { let buffer = UnsafeMutableRawBufferPointer(start: nil, count: 0) let source: [Int64] = [5, 4, 3, 2, 1] expectCrashLater() _ = buffer.initializeMemory(as: Int64.self, from: source) } UnsafeRawBufferPointerTestSuite.test("initializeMemory(as:from:).validNilPtr") { let buffer = UnsafeMutableRawBufferPointer(start: nil, count: 0) let source: [Int64] = [] var (it, bound) = buffer.initializeMemory(as: Int64.self, from: source) let idx = bound.endIndex * MemoryLayout<Int64>.stride expectNil(it.next()) expectEqual(idx, source.endIndex) } // Directly test the byte Sequence produced by withUnsafeBytes. UnsafeRawBufferPointerTestSuite.test("withUnsafeBytes.Sequence") { let array1: [Int32] = [0, 1, 2, 3] array1.withUnsafeBytes { bytes1 in // Initialize an array from a sequence of bytes. let byteArray = [UInt8](bytes1) for (b1, b2) in zip(byteArray, bytes1) { expectEqual(b1, b2) } } } // Test the empty buffer. UnsafeRawBufferPointerTestSuite.test("empty") { let emptyBytes = UnsafeRawBufferPointer(start: nil, count: 0) for _ in emptyBytes { expectUnreachable() } let emptyMutableBytes = UnsafeMutableRawBufferPointer.allocate(byteCount: 0, alignment: MemoryLayout<UInt>.alignment) for _ in emptyMutableBytes { expectUnreachable() } emptyMutableBytes.deallocate() } // Store a sequence of integers to raw memory, and reload them as structs. // Store structs to raw memory, and reload them as integers. UnsafeRawBufferPointerTestSuite.test("reinterpret") { struct Pair { var x: Int32 var y: Int32 } let numPairs = 2 let bytes = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Pair>.stride * numPairs, alignment: MemoryLayout<UInt>.alignment) defer { bytes.deallocate() } for i in 0..<(numPairs * 2) { bytes.storeBytes(of: Int32(i), toByteOffset: i * MemoryLayout<Int32>.stride, as: Int32.self) } let pair1 = bytes.load(as: Pair.self) let pair2 = bytes.load(fromByteOffset: MemoryLayout<Pair>.stride, as: Pair.self) expectEqual(0, pair1.x) expectEqual(1, pair1.y) expectEqual(2, pair2.x) expectEqual(3, pair2.y) bytes.storeBytes(of: Pair(x: -1, y: 0), as: Pair.self) for i in 0..<MemoryLayout<Int32>.stride { expectEqual(0xFF, bytes[i]) } let bytes2 = UnsafeMutableRawBufferPointer( rebasing: bytes[MemoryLayout<Int32>.stride..<bytes.count]) for i in 0..<MemoryLayout<Int32>.stride { expectEqual(0, bytes2[i]) } } // Store, load, subscript, and slice at all valid byte offsets. UnsafeRawBufferPointerTestSuite.test("inBounds") { let numInts = 4 let bytes = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int>.stride * numInts, alignment: MemoryLayout<UInt>.alignment) defer { bytes.deallocate() } for i in 0..<numInts { bytes.storeBytes( of: i, toByteOffset: i * MemoryLayout<Int>.stride, as: Int.self) } for i in 0..<numInts { let x = bytes.load( fromByteOffset: i * MemoryLayout<Int>.stride, as: Int.self) expectEqual(x, i) } for i in 0..<numInts { var x = i withUnsafeBytes(of: &x) { for (offset, byte) in $0.enumerated() { expectEqual(bytes[i * MemoryLayout<Int>.stride + offset], byte) } } } let median = (numInts/2 * MemoryLayout<Int>.stride) var firstHalf = bytes[0..<median] let secondHalf = bytes[median..<bytes.count] firstHalf[0..<firstHalf.count] = secondHalf expectEqualSequence(firstHalf, secondHalf) } UnsafeRawBufferPointerTestSuite.test("subscript.get.underflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 2, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = UnsafeRawBufferPointer(rebasing: buffer[1..<2]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. _ = bytes[-1] } UnsafeRawBufferPointerTestSuite.test("subscript.get.overflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 2, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = UnsafeRawBufferPointer(rebasing: buffer[0..<1]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. _ = bytes[1] } UnsafeRawBufferPointerTestSuite.test("subscript.set.underflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 2, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } var bytes = UnsafeMutableRawBufferPointer(rebasing: buffer[1..<2]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. bytes[-1] = 0 } UnsafeRawBufferPointerTestSuite.test("subscript.set.overflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 2, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } var bytes = UnsafeMutableRawBufferPointer(rebasing: buffer[0..<1]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. bytes[1] = 0 } UnsafeRawBufferPointerTestSuite.test("subscript.range.get.underflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = UnsafeRawBufferPointer(rebasing: buffer[1..<3]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. _ = bytes[-1..<1] } UnsafeRawBufferPointerTestSuite.test("subscript.range.get.overflow") { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = UnsafeRawBufferPointer(rebasing: buffer[0..<2]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. _ = bytes[1..<3] } UnsafeRawBufferPointerTestSuite.test("subscript.range.set.underflow") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } var bytes = UnsafeMutableRawBufferPointer(rebasing: buffer[1..<3]) if _isDebugAssertConfiguration() { expectCrashLater() } // Accesses a valid buffer location but triggers a debug bounds check. bytes[-1..<1] = bytes[0..<2] } UnsafeRawBufferPointerTestSuite.test("subscript.range.set.overflow") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } var bytes = UnsafeMutableRawBufferPointer(rebasing: buffer[0..<2]) if _isDebugAssertConfiguration() { expectCrashLater() } // Performs a valid byte-wise copy but triggers a debug bounds check. bytes[1..<3] = bytes[0..<2] } UnsafeRawBufferPointerTestSuite.test("subscript.range.narrow") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } if _isDebugAssertConfiguration() { expectCrashLater() } // Performs a valid byte-wise copy but triggers a debug bounds check. buffer[0..<3] = buffer[0..<2] } UnsafeRawBufferPointerTestSuite.test("subscript.range.wide") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } if _isDebugAssertConfiguration() { expectCrashLater() } // Performs a valid byte-wise copy but triggers a debug bounds check. buffer[0..<2] = buffer[0..<3] } UnsafeRawBufferPointerTestSuite.test("copyMemory.overflow") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = buffer[0..<2] if _isDebugAssertConfiguration() { expectCrashLater() } // Performs a valid byte-wise copy but triggers a debug range size check. UnsafeMutableRawBufferPointer(rebasing: bytes).copyMemory( from: UnsafeRawBufferPointer(buffer)) } UnsafeRawBufferPointerTestSuite.test("copyBytes.sequence.overflow") { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 3, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let bytes = buffer[0..<2] if _isDebugAssertConfiguration() { expectCrashLater() } // Performs a valid byte-wise copy but triggers a debug range size check. UnsafeMutableRawBufferPointer(rebasing: bytes).copyBytes( from: [0, 1, 2] as [UInt8]) } UnsafeRawBufferPointerTestSuite.test("load.before") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition.")) .code { expectCrashLater() var x: Int32 = 0 withUnsafeBytes(of: &x) { _ = $0.load(fromByteOffset: -1, as: UInt8.self) } } UnsafeRawBufferPointerTestSuite.test("load.after") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition..")) .code { expectCrashLater() var x: Int32 = 0 withUnsafeBytes(of: &x) { _ = $0.load(as: UInt64.self) } } UnsafeRawBufferPointerTestSuite.test("store.before") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition..")) .code { expectCrashLater() var x: Int32 = 0 withUnsafeMutableBytes(of: &x) { $0.storeBytes(of: UInt8(0), toByteOffset: -1, as: UInt8.self) } } UnsafeRawBufferPointerTestSuite.test("store.after") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition..")) .code { expectCrashLater() var x: Int32 = 0 withUnsafeMutableBytes(of: &x) { $0.storeBytes(of: UInt64(0), as: UInt64.self) } } UnsafeRawBufferPointerTestSuite.test("copy.bytes.overflow") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition..")) .code { expectCrashLater() var x: Int64 = 0 var y: Int32 = 0 withUnsafeBytes(of: &x) { srcBytes in withUnsafeMutableBytes(of: &y) { destBytes in destBytes.copyMemory( from: srcBytes) } } } UnsafeRawBufferPointerTestSuite.test("copy.sequence.overflow") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "This tests a debug precondition..")) .code { expectCrashLater() var x: Int64 = 0 var y: Int32 = 0 withUnsafeBytes(of: &x) { srcBytes in withUnsafeMutableBytes(of: &y) { destBytes in destBytes.copyMemory(from: srcBytes) } } } UnsafeRawBufferPointerTestSuite.test("copy.overlap") { let bytes = UnsafeMutableRawBufferPointer.allocate(byteCount: 4, alignment: MemoryLayout<UInt>.alignment) // Right Overlap bytes[0] = 1 bytes[1] = 2 bytes[1..<3] = bytes[0..<2] expectEqual(1, bytes[1]) expectEqual(2, bytes[2]) // Left Overlap bytes[1] = 2 bytes[2] = 3 bytes[0..<2] = bytes[1..<3] expectEqual(2, bytes[0]) expectEqual(3, bytes[1]) // Disjoint bytes[2] = 2 bytes[3] = 3 bytes[0..<2] = bytes[2..<4] expectEqual(2, bytes[0]) expectEqual(3, bytes[1]) bytes[0] = 0 bytes[1] = 1 bytes[2..<4] = bytes[0..<2] expectEqual(0, bytes[2]) expectEqual(1, bytes[3]) } runAllTests()
apache-2.0
2266e1a13b65d49bff4de06d6562a5b2
31.109589
119
0.712518
4.013699
false
true
false
false
mcberros/onTheMap
onTheMap/ParseApiClient.swift
1
5206
// // ParseApiClient.swift // onTheMap // // Created by Carmen Berros on 07/03/16. // Copyright © 2016 mcberros. All rights reserved. // import UIKit import Foundation class ParseApiClient: NSObject { var session: NSURLSession override init() { session = NSURLSession.sharedSession() super.init() } func taskForGETMethod(urlString: String, completionHandler: (success: Bool, result: AnyObject!, errorString: String) -> Void) { if let url = NSURL(string: urlString) { let request = NSMutableURLRequest(URL: url) request.addValue(ParseApiClient.Constants.ParseApplicationID, forHTTPHeaderField: "X-Parse-Application-Id") request.addValue(ParseApiClient.Constants.RestApiKey, forHTTPHeaderField: "X-Parse-REST-API-Key") let task = session.dataTaskWithRequest(request) { data, response, error in guard (error == nil) else { completionHandler(success: false, result: nil, errorString: "Connection error") return } guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { completionHandler(success: false, result: nil, errorString: "Your request returned an invalid response") return } guard let data = data else { completionHandler(success: false, result: nil, errorString: "No data was returned by the request") return } ParseApiClient.parseJSONWithCompletionHandler(data, completionHandler: completionHandler) } task.resume() } } func taskForPOSTMethod(urlString: String, jsonBody: [String: AnyObject], completionHandler: (success: Bool, result: AnyObject!, errorString: String) -> Void){ if let url = NSURL(string: urlString) { let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.addValue(ParseApiClient.Constants.ParseApplicationID, forHTTPHeaderField: "X-Parse-Application-Id") request.addValue(ParseApiClient.Constants.RestApiKey, forHTTPHeaderField: "X-Parse-REST-API-Key") request.addValue("application/json", forHTTPHeaderField: "Content-Type") do { request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonBody, options: .PrettyPrinted) } let task = session.dataTaskWithRequest(request) { data, response, error in guard error == nil else { completionHandler(success: false, result: nil, errorString: "Connection error") return } guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else { print((response as? NSHTTPURLResponse)?.statusCode) completionHandler(success: false, result: nil, errorString: "Your request returned an invalid response") return } guard let data = data else { completionHandler(success: false, result: nil, errorString: "No data was returned by the request") return } ParseApiClient.parseJSONWithCompletionHandler(data, completionHandler: completionHandler) } task.resume() } } class func parseJSONWithCompletionHandler(data: NSData, completionHandler: (success: Bool, result: AnyObject!, error: String) -> Void){ var parsedResult: AnyObject! do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch { completionHandler(success: false, result: nil, error: "The response data could not be parsed") return } completionHandler(success: true, result: parsedResult, error: "") } class func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { /* Make sure that it is a string value */ let stringValue = "\(value)" /* Escape it */ let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) /* Append it */ urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&") } class func sharedInstance() -> ParseApiClient { struct Singleton { static var sharedInstance = ParseApiClient() } return Singleton.sharedInstance } class func substituteKeyInMethod(method: String, key: String, value: String) -> String? { if method.rangeOfString("{\(key)}") != nil { return method.stringByReplacingOccurrencesOfString("{\(key)}", withString: value) } else { return nil } } }
mit
6757262c17896d92a2a3dd6d6a5f5a86
35.914894
162
0.605956
5.513771
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/OrderConfirmationService.swift
1
4239
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Combine import DIKit import Errors import FeatureCardPaymentDomain /// Used to execute the order once created public protocol OrderConfirmationServiceAPI: AnyObject { func confirm( checkoutData: CheckoutData ) -> AnyPublisher<CheckoutData, OrderConfirmationServiceError> } public enum OrderConfirmationServiceError: Error { case mappingError case applePay(ApplePayError) case nabu(NabuNetworkError) case ux(UX.Error) } final class OrderConfirmationService: OrderConfirmationServiceAPI { // MARK: - Properties private let analyticsRecorder: AnalyticsEventRecorderAPI private let client: CardOrderConfirmationClientAPI private let applePayService: ApplePayServiceAPI // MARK: - Setup init( analyticsRecorder: AnalyticsEventRecorderAPI, client: CardOrderConfirmationClientAPI, applePayService: ApplePayServiceAPI ) { self.analyticsRecorder = analyticsRecorder self.client = client self.applePayService = applePayService } func confirm(checkoutData: CheckoutData) -> AnyPublisher<CheckoutData, OrderConfirmationServiceError> { let orderId = checkoutData.order.identifier let paymentMethodId = checkoutData.order.paymentMethodId let confirmParams: AnyPublisher< ( partner: OrderPayload.ConfirmOrder.Partner, paymentMethodId: String? ), OrderConfirmationServiceError > switch checkoutData.order.paymentMethod { case .bankAccount, .bankTransfer: confirmParams = .just((partner: .bank, paymentMethodId: paymentMethodId)) case .applePay where paymentMethodId?.isEmpty ?? true, .card where paymentMethodId?.isEmpty ?? true: let amount = checkoutData.order.inputValue.displayMajorValue let currencyCode = checkoutData.order.inputValue.currency.code confirmParams = applePayService .getToken( amount: amount, currencyCode: currencyCode ) .map { params -> ( partner: OrderPayload.ConfirmOrder.Partner, paymentMethodId: String? ) in ( partner: OrderPayload.ConfirmOrder.Partner.applePay(params.token), paymentMethodId: params.beneficiaryId ) } .mapError(OrderConfirmationServiceError.applePay) .eraseToAnyPublisher() case .applePay, .card: confirmParams = .just(( partner: .card(redirectURL: PartnerAuthorizationData.exitLink), paymentMethodId: paymentMethodId )) case .funds: confirmParams = .just((partner: .funds, paymentMethodId: paymentMethodId)) } return confirmParams .flatMap { [client] params -> AnyPublisher<OrderPayload.Response, OrderConfirmationServiceError> in client .confirmOrder( with: orderId, partner: params.partner, paymentMethodId: params.paymentMethodId ) .mapError(OrderConfirmationServiceError.nabu) .eraseToAnyPublisher() } .map { [analyticsRecorder] response -> OrderDetails? in OrderDetails(recorder: analyticsRecorder, response: response) } .flatMap { details -> AnyPublisher<OrderDetails, OrderConfirmationServiceError> in guard let details = details else { return .failure(OrderConfirmationServiceError.mappingError) } if [.failed, .expired].contains(details.state), let ux = details.ux { return .failure(.ux(UX.Error(nabu: ux))) } return .just(details) } .map { checkoutData.checkoutData(byAppending: $0) } .eraseToAnyPublisher() } }
lgpl-3.0
04ff07f22ffd599064ddb4fc3ada478d
36.839286
111
0.607126
6.232353
false
false
false
false
modocache/swift
test/decl/protocol/objc.swift
6
5501
// RUN: %target-parse-verify-swift // Test requirements and conformance for Objective-C protocols. @objc class ObjCClass { } @objc protocol P1 { func method1() var property1: ObjCClass { get } var property2: ObjCClass { get set } } @objc class C1 : P1 { @objc(method1renamed) func method1() { // expected-error{{Objective-C method 'method1renamed' provided by method 'method1()' does not match the requirement's selector ('method1')}}{{9-23=method1}} } var property1: ObjCClass { @objc(getProperty1) get { // expected-error{{Objective-C method 'getProperty1' provided by getter for 'property1' does not match the requirement's selector ('property1')}}{{11-23=property1}} return ObjCClass() } } var property2: ObjCClass { get { return ObjCClass() } @objc(setProperty2Please:) set { } // expected-error{{Objective-C method 'setProperty2Please:' provided by setter for 'property2' does not match the requirement's selector ('setProperty2:')}}{{11-30=setProperty2:}} } } class C1b : P1 { func method1() { } var property1: ObjCClass = ObjCClass() var property2: ObjCClass = ObjCClass() } @objc protocol P2 { @objc(methodWithInt:withClass:) func method(_: Int, class: ObjCClass) var empty: Bool { @objc(checkIfEmpty) get } } class C2a : P2 { func method(_: Int, class: ObjCClass) { } var empty: Bool { get { } // expected-error{{Objective-C method 'empty' provided by getter for 'empty' does not match the requirement's selector ('checkIfEmpty')}} } } class C2b : P2 { @objc func method(_: Int, class: ObjCClass) { } @objc var empty: Bool { @objc get { } // expected-error{{Objective-C method 'empty' provided by getter for 'empty' does not match the requirement's selector ('checkIfEmpty')}}{{10-10=(checkIfEmpty)}} } } @objc protocol P3 { @objc optional func doSomething(x: Int) @objc optional func doSomething(y: Int) } class C3a : P3 { @objc func doSomething(x: Int) { } } // Complain about optional requirements that aren't satisfied // according to Swift, but would conflict in Objective-C. @objc protocol OptP1 { @objc optional func method() // expected-note 2{{requirement 'method()' declared here}} @objc optional var property1: ObjCClass { get } // expected-note 2{{requirement 'property1' declared here}} @objc optional var property2: ObjCClass { get set } // expected-note{{requirement 'property2' declared here}} } @objc class OptC1a : OptP1 { // expected-note 3{{class 'OptC1a' declares conformance to protocol 'OptP1' here}} @objc(method) func otherMethod() { } // expected-error{{Objective-C method 'method' provided by method 'otherMethod()' conflicts with optional requirement method 'method()' in protocol 'OptP1'}} // expected-note@-1{{rename method to match requirement 'method()'}}{{22-33=method}} var otherProp1: ObjCClass { @objc(property1) get { return ObjCClass() } // expected-error{{Objective-C method 'property1' provided by getter for 'otherProp1' conflicts with optional requirement getter for 'property1' in protocol 'OptP1'}} } var otherProp2: ObjCClass { get { return ObjCClass() } @objc(setProperty2:) set { } // expected-error{{Objective-C method 'setProperty2:' provided by setter for 'otherProp2' conflicts with optional requirement setter for 'property2' in protocol 'OptP1'}} } } @objc class OptC1b : OptP1 { // expected-note 2{{class 'OptC1b' declares conformance to protocol 'OptP1' here}} @objc(property1) func someMethod() { } // expected-error{{Objective-C method 'property1' provided by method 'someMethod()' conflicts with optional requirement getter for 'property1' in protocol 'OptP1'}} var someProp: ObjCClass { @objc(method) get { return ObjCClass() } // expected-error{{Objective-C method 'method' provided by getter for 'someProp' conflicts with optional requirement method 'method()' in protocol 'OptP1'}} } } // rdar://problem/19879598 @objc protocol Foo { init() } class Bar: Foo { required init() {} } @objc protocol P4 { @objc(foo:bar:) func method(x: Int, y: Int) } // Infer @objc and selector from requirement. class C4a : P4 { func method(x: Int, y: Int) { } } // Infer selector from requirement. class C4b : P4 { @objc func method(x: Int, y: Int) { } } @objc protocol P5 { @objc(wibble:wobble:) func method(x: Int, y: Int) } // Don't infer when there is an ambiguity. class C4_5a : P4, P5 { func method(x: Int, y: Int) { } // expected-error@-1{{ambiguous inference of Objective-C name for instance method 'method(x:y:)' ('foo:bar:' vs 'wibble:wobble:')}} // expected-note@-2{{'method(x:y:)' (in protocol 'P4') provides Objective-C name 'foo:bar:'}}{{3-3=@objc(foo:bar:) }} // expected-note@-3{{'method(x:y:)' (in protocol 'P5') provides Objective-C name 'wibble:wobble:'}}{{3-3=@objc(wibble:wobble:) }} // expected-note@-4{{add '@nonobjc' to silence this error}}{{3-3=@nonobjc }} // expected-error@-5{{Objective-C method 'foo:bar:' provided by method 'method(x:y:)' does not match the requirement's selector ('wibble:wobble:')}} } // Don't complain about a selector mismatch in cases where the // selector will be inferred. @objc protocol P6 { func doSomething(_ sender: AnyObject?) // expected-note{{requirement 'doSomething' declared here}} } class C6a : P6 { func doSomething(sender: AnyObject?) { } // expected-error{{method 'doSomething(sender:)' has different argument names from those required by protocol 'P6' ('doSomething')}}{{20-20=_ }}{{none}} }
apache-2.0
899538dc6b71ca7c7e8cda8ddd5f8334
36.168919
218
0.692783
3.61195
false
false
false
false
idea4good/GuiLiteSamples
HelloParticle/BuildIos/BuildIos/GuiLiteImage.swift
1
2110
import UIKit class GuiLiteImage { let width, height, colorBytes : Int let buffer: UnsafeMutableRawPointer init(width: Int, height: Int, colorBytes: Int) { self.width = width self.height = height self.colorBytes = colorBytes self.buffer = malloc(width * height * 4) } func getUiImage() -> UIImage?{ let pixData = (colorBytes == 2) ? getPixelsFrom16bits() : getPixelsFrom32bits() if(pixData == nil){ return nil } let providerRef = CGDataProvider(data: pixData!) let bitmapInfo:CGBitmapInfo = [.byteOrder32Little, CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue)] let cgimg = CGImage(width: Int(width), height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) return UIImage(cgImage: cgimg!) } func getPixelsFrom16bits()->CFData?{ let rawData = getUiOfHelloParticle() if rawData == nil{ return nil } for index in 0..<width * height { let rgb16 = rawData?.load(fromByteOffset: index * 2, as: UInt16.self) let rgb32 = UInt32(rgb16!) let color = ((rgb32 & 0xF800) << 8 | ((rgb32 & 0x7E0) << 5) | ((rgb32 & 0x1F) << 3)) buffer.storeBytes(of: color, toByteOffset: index * 4, as: UInt32.self) } let rawPointer = UnsafeRawPointer(buffer) let pixData: UnsafePointer = rawPointer.assumingMemoryBound(to: UInt8.self) return CFDataCreate(nil, pixData, width * height * 4) } func getPixelsFrom32bits()->CFData?{ let rawData = getUiOfHelloParticle() if rawData == nil{ return nil } let rawPointer = UnsafeRawPointer(rawData) let pixData: UnsafePointer = rawPointer!.assumingMemoryBound(to: UInt8.self) return CFDataCreate(nil, pixData, width * height * 4) } }
apache-2.0
fc30f877b26b4b0e61e9b0ee29c6f516
38.074074
273
0.615166
4.40501
false
false
false
false
zs40x/PairProgrammingTimer
PairProgrammingTimer/ViewController/MainViewController.swift
1
2849
// // MainViewController.swift // PairProgrammingTimer // // Created by Stefan Mehnert on 11.04.17. // Copyright © 2017 Stefan Mehnert. All rights reserved. // import UIKit class MainViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { let sessionLog = SessionLog(dateTime: SystemDateTime(), sessionLogService: SessionUserDefaultsLogService()) let pages = ["SessionViewController", "SessionLogViewController"] override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self } override func viewDidAppear(_ animated: Bool) { setViewControllers( [(instantiateAndInitViewController(withIdentifier: pages[0]))!], direction: .forward, animated: true, completion: nil) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let identifier = viewController.restorationIdentifier { if let index = pages.index(of: identifier) { if index > 0 { return instantiateAndInitViewController(withIdentifier: pages[index-1]) } } } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let identifier = viewController.restorationIdentifier { if let index = pages.index(of: identifier) { if index < pages.count - 1 { return instantiateAndInitViewController(withIdentifier: pages[index+1]) } } } return nil } func presentationCount(for pageViewController: UIPageViewController) -> Int { return pages.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { if let identifier = viewControllers?.first?.restorationIdentifier { if let index = pages.index(of: identifier) { return index } } return 0 } private func instantiateAndInitViewController(withIdentifier identifier: String) -> UIViewController? { guard let viewController = self.storyboard?.instantiateViewController(withIdentifier: identifier) else { NSLog("Failed to instantiate viewController with identifier: \(identifier)") return nil } if var sessionLogConsumer = viewController as? SessionLogConsumer { sessionLogConsumer.sessionLog = sessionLog } return viewController } }
mit
56e875bdddd95a81628c1671b191ea26
33.313253
112
0.629916
6.177874
false
false
false
false
PimCoumans/Foil
Foil/Data/Color.swift
2
3523
// // Color.swift // Foil // // Created by Pim Coumans on 23/01/17. // Copyright © 2017 pixelrock. All rights reserved. // import Foundation #if os(iOS) import UIKit typealias NativeColor = UIColor #elseif os(OSX) import Cocoa typealias NativeColor = NSColor #endif struct Color { var red: Float var green: Float var blue: Float var alpha: Float = 1 init(red: Float, green: Float, blue: Float, alpha: Float = 1) { self.red = red self.green = green self.blue = blue self.alpha = alpha } } // Equatable extension Color: Equatable { static func ==(_ lhs: Color, _ rhs: Color) -> Bool { return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue && lhs.alpha == rhs.alpha } } // Native color support extension Color { init(_ color: NativeColor) { var r, g, b, a: Float #if os(OSX) if color.numberOfComponents < 4 { let white = Float(color.whiteComponent) r = white g = white b = white a = Float(color.alphaComponent) } else { r = Float(color.redComponent) g = Float(color.greenComponent) b = Float(color.blueComponent) a = Float(color.alphaComponent) } #elseif os(iOS) var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 if !color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) { color.getWhite(&red, alpha: &alpha) green = red blue = red } r = Float(red) g = Float(green) b = Float(blue) a = Float(alpha) #endif self.red = r self.green = g self.blue = b self.alpha = a } } // Convenience extension Color { func with(alpha: Float) -> Color { var color = self color.alpha = alpha return color } static var black: Color { return Color(red: 0, green: 0, blue: 0) } static var white: Color { return Color(red: 1, green: 1, blue: 1) } static var red: Color { return Color(red: 1, green: 0, blue: 0) } static var green: Color { return Color(red: 0, green: 1, blue: 0) } static var blue: Color { return Color(red: 0, green: 0, blue: 1) } static var purple: Color { return Color(red: 1, green: 0, blue: 1) } static var yellow: Color { return Color(red: 1, green: 1, blue: 0) } } // Animation extension Color: Lerpable { internal static func +(lhs: Color, rhs: Color) -> Color { return Color(red: lhs.red + rhs.red, green: lhs.green + rhs.green, blue: lhs.blue + rhs.blue, alpha: lhs.alpha + rhs.alpha) } mutating func lerp(to color: Color, t: Double) { if self == color { return } red.lerp(to: color.red, t: t) green.lerp(to: color.green, t: t) blue.lerp(to: color.blue, t: t) alpha.lerp(to: color.alpha, t: t) } } fileprivate extension Float { mutating func lerp(to float: Float, t: Double) { if self == float { return } let difference = float - self if abs(difference) < 0.001 { self = float return } self += Float(Double(difference) * t) } }
mit
75afc8903d2b8708997a86fdca95bf0e
22.48
131
0.52243
3.754797
false
false
false
false
whong7/swift-knowledge
思维导图/4-3:网易新闻/Pods/Alamofire/Source/Response.swift
80
13254
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
mit
0c4d24522fa599ef875895b9e0324865
37.417391
119
0.67474
4.777938
false
false
false
false
apple/swift
test/AutoDiff/validation-test/storeborrow.swift
2
4515
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import DifferentiationUnittest var StoreBorrowAdjTest = TestSuite("StoreBorrowAdjTest") public struct ConstantTimeAccessor<Element>: Differentiable where Element: Differentiable, Element: AdditiveArithmetic { public struct TangentVector: Differentiable, AdditiveArithmetic { public typealias TangentVector = ConstantTimeAccessor.TangentVector public var _base: [Element.TangentVector] public var accessed: Element.TangentVector public init(_base: [Element.TangentVector], accessed: Element.TangentVector) { self._base = _base self.accessed = accessed } } @usableFromInline var _values: [Element] public var accessed: Element @inlinable @differentiable(reverse) public init(_ values: [Element], accessed: Element = .zero) { self._values = values self.accessed = accessed } @inlinable @differentiable(reverse) public var array: [Element] { return _values } @noDerivative public var count: Int { return _values.count } } public extension ConstantTimeAccessor { @inlinable @derivative(of: init(_:accessed:)) static func _vjpInit(_ values: [Element], accessed: Element = .zero) -> (value: ConstantTimeAccessor, pullback: (TangentVector) -> (Array<Element>.TangentVector, Element.TangentVector)) { return (ConstantTimeAccessor(values, accessed: accessed), { v in let base: Array<Element>.TangentVector if v._base.count < values.count { base = Array<Element> .TangentVector(v._base + Array<Element.TangentVector>(repeating: .zero, count: values.count - v._base.count)) } else { base = Array<Element>.TangentVector(v._base) } return (base, v.accessed) }) } @inlinable @derivative(of: array) func vjpArray() -> (value: [Element], pullback: (Array<Element>.TangentVector) -> TangentVector) { func pullback(v: Array<Element>.TangentVector) -> TangentVector { var base: [Element.TangentVector] let localZero = Element.TangentVector.zero if v.base.allSatisfy({ $0 == localZero }) { base = [] } else { base = v.base } return TangentVector(_base: base, accessed: Element.TangentVector.zero) } return (_values, pullback) } mutating func move(by offset: TangentVector) { self.accessed.move(by: offset.accessed) _values.move(by: Array<Element>.TangentVector(offset._base)) } } public extension ConstantTimeAccessor.TangentVector { @inlinable static func + (lhs: Self, rhs: Self) -> Self { if rhs._base.isEmpty { return lhs } else if lhs._base.isEmpty { return rhs } else { var base = zip(lhs._base, rhs._base).map(+) if lhs._base.count < rhs._base.count { base.append(contentsOf: rhs._base.suffix(from: lhs._base.count)) } else if lhs._base.count > rhs._base.count { base.append(contentsOf: lhs._base.suffix(from: rhs._base.count)) } return Self(_base: base, accessed: lhs.accessed + rhs.accessed) } } @inlinable static func - (lhs: Self, rhs: Self) -> Self { if rhs._base.isEmpty { return lhs } else { var base = zip(lhs._base, rhs._base).map(-) if lhs._base.count < rhs._base.count { base.append(contentsOf: rhs._base.suffix(from: lhs._base.count).map { .zero - $0 }) } else if lhs._base.count > rhs._base.count { base.append(contentsOf: lhs._base.suffix(from: rhs._base.count)) } return Self(_base: base, accessed: lhs.accessed - rhs.accessed) } } @inlinable static var zero: Self { Self(_base: [], accessed: .zero) } } StoreBorrowAdjTest.test("NonZeroGrad") { @differentiable(reverse) func testInits(input: [Float]) -> Float { let internalAccessor = ConstantTimeAccessor(input) let internalArray = internalAccessor.array return internalArray[1] } let grad = gradient(at: [42.0, 146.0, 73.0], of: testInits) expectEqual(grad[1], 1.0) } runAllTests()
apache-2.0
5c4a2c7e1fcaf846e317f31c80d8635e
31.25
129
0.595792
4.400585
false
true
false
false
TouchInstinct/LeadKit
Sources/Structures/DrawingOperations/ImageDrawingOperation.swift
1
2072
// // Copyright (c) 2017 Touch Instinct // // 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 CoreGraphics struct ImageDrawingOperation: DrawingOperation { private let image: CGImage private let newSize: CGSize private let origin: CGPoint public let opaque: Bool private let flipY: Bool public init(image: CGImage, newSize: CGSize, origin: CGPoint = .zero, opaque: Bool = false, flipY: Bool = false) { self.image = image self.newSize = newSize self.origin = origin self.opaque = opaque self.flipY = flipY } public var contextSize: CGContextSize { newSize.ceiledContextSize } public func apply(in context: CGContext) { if flipY { context.translateBy(x: 0, y: newSize.height) context.scaleBy(x: 1, y: -1) } context.interpolationQuality = .high context.draw(image, in: CGRect(origin: origin, size: newSize)) } }
apache-2.0
2bfd6f118e1a0c8c85dc58cc7545626e
34.118644
81
0.678571
4.494577
false
false
false
false
vector-im/vector-ios
Riot/Managers/UserSessions/UserSessionProperties.swift
1
2629
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// User properties that are tied to a particular user ID. class UserSessionProperties: NSObject { // MARK: - Constants private enum Constants { static let useCaseKey = "useCase" } // MARK: - Properties // MARK: Private /// The user ID for these properties private let userId: String /// The underlying dictionary for this userId from user defaults. private var dictionary: [String: Any] { get { RiotSettings.shared.userSessionProperties[userId] ?? [:] } set { var sharedProperties = RiotSettings.shared.userSessionProperties sharedProperties[userId] = newValue RiotSettings.shared.userSessionProperties = sharedProperties } } // MARK: Public /// The user's use case selection if this session was the one used to register the account. var useCase: UseCase? { get { guard let useCaseRawValue = dictionary[Constants.useCaseKey] as? String else { return nil } return UseCase(rawValue: useCaseRawValue) } set { dictionary[Constants.useCaseKey] = newValue?.rawValue } } /// Represents a selected use case for the app. /// Note: The raw string value is used for storage. enum UseCase: String { case personalMessaging case workMessaging case communityMessaging case skipped } // MARK: - Setup /// Create new properties for the specified user ID. /// - Parameter userId: The user ID to load properties for. init(userId: String) { self.userId = userId super.init() } // MARK: - Public /// Clear all of the stored properties. func delete() { dictionary = [:] var sharedProperties = RiotSettings.shared.userSessionProperties sharedProperties[userId] = nil RiotSettings.shared.userSessionProperties = sharedProperties } }
apache-2.0
eafb7bc1c10671105617a1bbc4e91f64
29.569767
103
0.64283
5.007619
false
false
false
false
fs/Social-iOS
SocialNetworks/Source/Pinterest/SocialPinterest.swift
1
2198
import UIKit public class PinterestNetwork: NSObject { public static var permissions: [String] = [PDKClientReadPublicPermissions, PDKClientWritePublicPermissions] public static var boardName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String public class var shared: PinterestNetwork { struct Static { static var instance: PinterestNetwork? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { PDKClient.sharedInstance().silentlyAuthenticateWithSuccess(nil, andFailure: nil) let instance = PinterestNetwork() Static.instance = instance } return Static.instance! } private override init() { super.init() } } //MARK: - extension PinterestNetwork: SocialNetwork { public class var name: String { return "Pinterest" } public class var isAuthorized: Bool { return PDKClient.sharedInstance().authorized } public class func authorization(completion: SocialNetworkSignInCompletionHandler?) { if self.isAuthorized == true { completion?(success: true, error: nil) } else { self.openNewSession(completion) } } public class func logout(completion: SocialNetworkSignOutCompletionHandler?) { if self.isAuthorized == true { PDKClient.clearAuthorizedUser() } completion?() } private class func openNewSession(completion: SocialNetworkSignInCompletionHandler?) { PDKClient.sharedInstance().authenticateWithPermissions(PinterestNetwork.permissions, withSuccess: { (response) in completion?(success: true, error: nil) }) { (error) in completion?(success: false, error: error) } } } //MARK: - internal extension NSError { internal class func pdk_getAPIClientError() -> NSError { return NSError.init(domain: "com.TwitterNetwork", code: -100, userInfo: [NSLocalizedDescriptionKey : "API client can not initialization"]) } }
mit
a44440d9bcf91c546795d20ec70f7e7c
29.957746
146
0.624204
5.374083
false
false
false
false
SwiftStudies/OysterKit
Sources/stlrc/Framework/Extensions/DictionaryExtensions.swift
1
1082
// // DictionaryExtensions.swift // CommandKit // // Created by Sean Alling on 11/8/17. // import Foundation extension Array where Element == Command { /** */ var numberOfTabs: Int { let keys = self.map({ $0.name }) let largestKey = keys.reduce(into: "", { largest, newValue in largest = newValue.count > largest.count ? newValue : largest }) let rawNumberOfTabs = largestKey.count / 4 let modulo = 10 % rawNumberOfTabs return (modulo == 0) ? (rawNumberOfTabs + 1) : rawNumberOfTabs } } extension Array where Element == Option { /** */ var numberOfTabs: Int { let keys = self.map({ $0.shortForm ?? $0.longForm }) let largestKey = keys.reduce(into: "", { largest, newValue in largest = newValue.count > largest.count ? newValue : largest }) let rawNumberOfTabs = largestKey.count < 4 ? 1 : largestKey.count / 4 let modulo = 10 % rawNumberOfTabs return (modulo == 0) ? (rawNumberOfTabs + 1) : rawNumberOfTabs } }
bsd-2-clause
4e512a77209e0e41d48ff62cf7e070e0
26.74359
77
0.588725
4.210117
false
false
false
false