repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
KiiPlatform/thing-if-iOSSample
SampleProject/IoTSchema.swift
1
6129
// // IoTSchema.swift // SampleProject // // Created by Yongping on 8/28/15. // Copyright © 2015 Kii Corporation. All rights reserved. // import Foundation import ThingIFSDK enum StatusType: String{ case BoolType = "boolean" case IntType = "integer" case DoubleType = "double" case StringType = "string" init?(string: String) { switch string { case StatusType.BoolType.rawValue: self = .BoolType case StatusType.IntType.rawValue: self = .IntType case StatusType.DoubleType.rawValue: self = .DoubleType case StatusType.StringType.rawValue: self = .StringType default: return nil } } } struct ActionStruct { let actionSchema: ActionSchema! var value: AnyObject! // the return Ditionary will be like: ["actionName": ["requiredStatus": value] ], where value can be Bool, Int or Double. ie. ["TurnPower": ["power": true]] func getActionDict() -> Dictionary<String, AnyObject> { let actionDict: Dictionary<String, AnyObject> = [actionSchema.name: [actionSchema.status.name: value]] return actionDict } init(actionSchema: ActionSchema, value: AnyObject) { self.actionSchema = actionSchema self.value = value } init?(actionSchema: ActionSchema, actionDict: Dictionary<String, AnyObject>) { self.actionSchema = actionSchema if actionDict.keys.count == 0 { return nil } let actionNameKey = Array(actionDict.keys)[0] if actionSchema.name == actionNameKey { if let statusDict = actionDict[actionNameKey] as? Dictionary<String, AnyObject> { let statusNameKey = Array(statusDict.keys)[0] if actionSchema.status.name == statusNameKey { self.value = statusDict[statusNameKey] }else{ return nil } }else { return nil } }else { return nil } } } class StatusSchema: NSObject, NSCoding { let name: String! let type: StatusType! var minValue: AnyObject? var maxValue: AnyObject? func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.type.rawValue, forKey: "type") aCoder.encodeObject(self.minValue, forKey: "minValue") aCoder.encodeObject(self.maxValue, forKey: "maxValue") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.type = StatusType(string: aDecoder.decodeObjectForKey("type") as! String)! self.minValue = aDecoder.decodeObjectForKey("minValue") self.maxValue = aDecoder.decodeObjectForKey("maxValue") } init(name: String, type: StatusType, minValue: AnyObject?, maxValue: AnyObject?) { self.name = name self.type = type self.minValue = minValue self.maxValue = maxValue } } class ActionSchema: NSObject, NSCoding { let name: String! let status: StatusSchema! func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.status, forKey: "status") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.status = aDecoder.decodeObjectForKey("status") as! StatusSchema } init(actionName: String, status: StatusSchema) { self.name = actionName self.status = status } } class IoTSchema: NSObject,NSCoding { let name: String! let version: Int! private var statusSchemaDict = Dictionary<String, StatusSchema>() private var actionSchemaDict = Dictionary<String, ActionSchema>() func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.version, forKey: "version") aCoder.encodeObject(self.statusSchemaDict, forKey: "statusSchemaDict") aCoder.encodeObject(self.actionSchemaDict, forKey: "actionSchemaDict") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.version = aDecoder.decodeObjectForKey("version") as! Int self.statusSchemaDict = aDecoder.decodeObjectForKey("statusSchemaDict") as! Dictionary<String, StatusSchema> self.actionSchemaDict = aDecoder.decodeObjectForKey("actionSchemaDict") as! Dictionary<String, ActionSchema> } init(name: String, version: Int) { self.name = name self.version = version } func addStatus(statusName: String, statusType: StatusType) { statusSchemaDict[statusName] = StatusSchema(name: statusName, type: statusType, minValue: nil, maxValue: nil) } func addStatus(statusName: String, statusType: StatusType, minValue: AnyObject?, maxvalue: AnyObject?) { statusSchemaDict[statusName] = StatusSchema(name: statusName, type: statusType, minValue: minValue, maxValue: maxvalue) } func getStatusType(status: String) -> StatusType? { return statusSchemaDict[status]?.type } func getStatusSchema(status: String) -> StatusSchema? { return statusSchemaDict[status] } func addAction(actionName: String, statusName: String) -> Bool { if let statusSchema = getStatusSchema(statusName) { actionSchemaDict[actionName] = ActionSchema(actionName: actionName, status: statusSchema) return true }else { return false } } func getActionSchema(actionName: String) -> ActionSchema? { return actionSchemaDict[actionName] } func getActionNames() -> [String] { return Array(actionSchemaDict.keys) } func getStatusNames() -> [String] { return Array(statusSchemaDict.keys) } }
mit
tsolomko/SWCompression
Sources/7-Zip/7zContainer.swift
1
11445
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData /// Provides functions for work with 7-Zip containers. public class SevenZipContainer: Container { static let signatureHeaderSize = 32 /** Processes 7-Zip container and returns an array of `SevenZipEntry` with information and data for all entries. - Important: The order of entries is defined by 7-Zip container and, particularly, by the creator of a given 7-Zip container. It is likely that directories will be encountered earlier than files stored in those directories, but no particular order is guaranteed. - Parameter container: 7-Zip container's data. - Throws: `SevenZipError` or any other error associated with compression type depending on the type of the problem. It may indicate that either container is damaged or it might not be 7-Zip container at all. - Returns: Array of `SevenZipEntry`. */ public static func open(container data: Data) throws -> [SevenZipEntry] { var entries = [SevenZipEntry]() guard let header = try readHeader(data), let files = header.fileInfo?.files else { return [] } /// Total count of non-empty files. Used to iterate over SubstreamInfo. var nonEmptyFileIndex = 0 /// Index of currently opened folder in `streamInfo.coderInfo.folders`. var folderIndex = 0 /// Index of currently extracted file in `headerInfo.fileInfo.files`. var folderFileIndex = 0 /// Index of currently read stream. var streamIndex = -1 /// Total size of unpacked data for current folder. Used for consistency check. var folderUnpackSize = 0 /// Combined calculated CRC of entire folder == all files in folder. var folderCRC = CheckSums.crc32(Data()) /// `LittleEndianByteReader` object with unpacked stream's data. var unpackedStreamData = LittleEndianByteReader(data: Data()) let byteReader = LittleEndianByteReader(data: data) for file in files { if file.isEmptyStream { let info = file.isEmptyFile && !file.isAntiFile ? SevenZipEntryInfo(file, 0) : SevenZipEntryInfo(file) let data = file.isEmptyFile && !file.isAntiFile ? Data() : nil entries.append(SevenZipEntry(info, data)) continue } // Without `SevenZipStreamInfo` and `SevenZipPackInfo` we cannot find file data in container. guard let streamInfo = header.mainStreams, let packInfo = streamInfo.packInfo else { throw SevenZipError.internalStructureError } // SubstreamInfo is required to get files' data, and without it we can only return files' info. guard let substreamInfo = streamInfo.substreamInfo else { entries.append(SevenZipEntry(SevenZipEntryInfo(file), nil)) continue } // Check if there is enough folders. guard folderIndex < streamInfo.coderInfo.numFolders else { throw SevenZipError.internalStructureError } /// Folder which contains current file. let folder = streamInfo.coderInfo.folders[folderIndex] // There may be several streams in a single folder, so we have to iterate over them, if necessary. // If we switched folders or completed reading of a stream we need to move to the next stream. if folderFileIndex == 0 || unpackedStreamData.isFinished { streamIndex += 1 // First, we move to the stream's offset. We don't have any guarantees that streams will be // enountered in the same order, as they are placed in the container. Thus, we have to start moving // to stream's offset from the beginning. // TODO: Is this correct or the order of streams is guaranteed? byteReader.offset = signatureHeaderSize + packInfo.packPosition // Pack offset. if streamIndex != 0 { for i in 0..<streamIndex { byteReader.offset += packInfo.packSizes[i] } } // Load the stream. let streamData = Data(byteReader.bytes(count: packInfo.packSizes[streamIndex])) // Check stream's CRC, if it's available. if streamIndex < packInfo.digests.count, let storedStreamCRC = packInfo.digests[streamIndex] { guard CheckSums.crc32(streamData) == storedStreamCRC else { throw SevenZipError.wrongCRC } } // One stream can contain data for several files, so we need to decode the stream first, then split // it into files. unpackedStreamData = LittleEndianByteReader(data: try folder.unpack(data: streamData)) } // `SevenZipSubstreamInfo` object must contain information about file's size and may also contain // information about file's CRC32. // File's unpacked size is required to proceed. guard nonEmptyFileIndex < substreamInfo.unpackSizes.count else { throw SevenZipError.internalStructureError } let fileSize = substreamInfo.unpackSizes[nonEmptyFileIndex] // Check, if we aren't about to read too much from a stream. guard fileSize <= unpackedStreamData.bytesLeft else { throw SevenZipError.internalStructureError } let fileData = Data(unpackedStreamData.bytes(count: fileSize)) let calculatedFileCRC = CheckSums.crc32(fileData) if nonEmptyFileIndex < substreamInfo.digests.count { guard calculatedFileCRC == substreamInfo.digests[nonEmptyFileIndex] else { throw SevenZipError.wrongCRC } } let info = SevenZipEntryInfo(file, fileSize, calculatedFileCRC) let data = fileData entries.append(SevenZipEntry(info, data)) // Update folder's crc and unpack size. folderUnpackSize += fileSize folderCRC = CheckSums.crc32(fileData, prevValue: folderCRC) folderFileIndex += 1 nonEmptyFileIndex += 1 if folderFileIndex >= folder.numUnpackSubstreams { // If we read all files in folder... // Check folder's unpacked size as well as its CRC32 (if it is available). guard folderUnpackSize == folder.unpackSize() else { throw SevenZipError.wrongSize } if let storedFolderCRC = folder.crc { guard folderCRC == storedFolderCRC else { throw SevenZipError.wrongCRC } } // Reset folder's unpack size and CRC32. folderCRC = CheckSums.crc32(Data()) folderUnpackSize = 0 // Reset file index for the next folder. folderFileIndex = 0 // Move to the next folder. folderIndex += 1 } } return entries } /** Processes 7-Zip container and returns an array of `SevenZipEntryInfo` with information about entries in this container. - Important: The order of entries is defined by 7-Zip container and, particularly, by the creator of a given 7-Zip container. It is likely that directories will be encountered earlier than files stored in those directories, but no particular order is guaranteed. - Parameter container: 7-Zip container's data. - Throws: `SevenZipError` or any other error associated with compression type depending on the type of the problem. It may indicate that either container is damaged or it might not be 7-Zip container at all. - Returns: Array of `SevenZipEntryInfo`. */ public static func info(container data: Data) throws -> [SevenZipEntryInfo] { var entries = [SevenZipEntryInfo]() guard let header = try readHeader(data), let files = header.fileInfo?.files else { return [] } var nonEmptyFileIndex = 0 for file in files { if !file.isEmptyStream, let substreamInfo = header.mainStreams?.substreamInfo { let size = nonEmptyFileIndex < substreamInfo.unpackSizes.count ? substreamInfo.unpackSizes[nonEmptyFileIndex] : nil let crc = nonEmptyFileIndex < substreamInfo.digests.count ? substreamInfo.digests[nonEmptyFileIndex] : nil entries.append(SevenZipEntryInfo(file, size, crc)) nonEmptyFileIndex += 1 } else { let info = file.isEmptyFile ? SevenZipEntryInfo(file, 0) : SevenZipEntryInfo(file) entries.append(info) } } return entries } private static func readHeader(_ data: Data) throws -> SevenZipHeader? { // Valid 7-Zip container must contain at least a SignatureHeader, which is 32 bytes long. guard data.count >= 32 else { throw SevenZipError.wrongSignature } let bitReader = MsbBitReader(data: data) // **SignatureHeader** // Check signature. guard bitReader.bytes(count: 6) == [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C] else { throw SevenZipError.wrongSignature } // Check archive version. let majorVersion = bitReader.byte() let minorVersion = bitReader.byte() guard majorVersion == 0 && minorVersion > 0 && minorVersion <= 4 else { throw SevenZipError.wrongFormatVersion } let startHeaderCRC = bitReader.uint32() /// - Note: Relative to SignatureHeader let nextHeaderOffset = bitReader.int(fromBytes: 8) let nextHeaderSize = bitReader.int(fromBytes: 8) let nextHeaderCRC = bitReader.uint32() bitReader.offset -= 20 guard CheckSums.crc32(bitReader.bytes(count: 20)) == startHeaderCRC else { throw SevenZipError.wrongCRC } // **Header** bitReader.offset += nextHeaderOffset if bitReader.isFinished { return nil // In case of completely empty container. } let headerStartIndex = bitReader.offset let headerEndIndex: Int let type = bitReader.byte() let header: SevenZipHeader if type == 0x17 { let packedHeaderStreamInfo = try SevenZipStreamInfo(bitReader) headerEndIndex = bitReader.offset header = try SevenZipHeader(bitReader, using: packedHeaderStreamInfo) } else if type == 0x01 { header = try SevenZipHeader(bitReader) headerEndIndex = bitReader.offset } else { throw SevenZipError.internalStructureError } // Check header size guard headerEndIndex - headerStartIndex == nextHeaderSize else { throw SevenZipError.wrongSize } // Check header CRC bitReader.offset = headerStartIndex guard CheckSums.crc32(bitReader.bytes(count: nextHeaderSize)) == nextHeaderCRC else { throw SevenZipError.wrongCRC } return header } }
mit
nguyenantinhbk77/practice-swift
Views/SegmentedControl/SegmentedControl With images/SegmentedControl With images/AppDelegate.swift
3
246
// // AppDelegate.swift // SegmentedControl With images // // Created by Domenico Solazzo on 05/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
mit
Yummypets/YPImagePicker
Source/Models/YPError.swift
1
308
// // YPError.swift // YPImagePicker // // Created by Nik Kov on 13.08.2021. // import UIKit enum YPError: Error, LocalizedError { case custom(message: String) var errorDescription: String? { switch self { case .custom(let message): return message } } }
mit
trill-lang/LLVMSwift
Sources/LLVM/Operation.swift
1
13240
#if SWIFT_PACKAGE import cllvm #endif /// Species the behavior that should occur on overflow during mathematical /// operations. public enum OverflowBehavior { /// The result value of the operator is the mathematical result modulo `2^n`, /// where `n` is the bit width of the result. case `default` /// The result value of the operator is a poison value if signed overflow /// occurs. case noSignedWrap /// The result value of the operator is a poison value if unsigned overflow /// occurs. case noUnsignedWrap } /// The condition codes available for integer comparison instructions. public enum IntPredicate { /// Yields `true` if the operands are equal, false otherwise without sign /// interpretation. case equal /// Yields `true` if the operands are unequal, false otherwise without sign /// interpretation. case notEqual /// Interprets the operands as unsigned values and yields true if the first is /// greater than the second. case unsignedGreaterThan /// Interprets the operands as unsigned values and yields true if the first is /// greater than or equal to the second. case unsignedGreaterThanOrEqual /// Interprets the operands as unsigned values and yields true if the first is /// less than the second. case unsignedLessThan /// Interprets the operands as unsigned values and yields true if the first is /// less than or equal to the second. case unsignedLessThanOrEqual /// Interprets the operands as signed values and yields true if the first is /// greater than the second. case signedGreaterThan /// Interprets the operands as signed values and yields true if the first is /// greater than or equal to the second. case signedGreaterThanOrEqual /// Interprets the operands as signed values and yields true if the first is /// less than the second. case signedLessThan /// Interprets the operands as signed values and yields true if the first is /// less than or equal to the second. case signedLessThanOrEqual private static let predicateMapping: [IntPredicate: LLVMIntPredicate] = [ .equal: LLVMIntEQ, .notEqual: LLVMIntNE, .unsignedGreaterThan: LLVMIntUGT, .unsignedGreaterThanOrEqual: LLVMIntUGE, .unsignedLessThan: LLVMIntULT, .unsignedLessThanOrEqual: LLVMIntULE, .signedGreaterThan: LLVMIntSGT, .signedGreaterThanOrEqual: LLVMIntSGE, .signedLessThan: LLVMIntSLT, .signedLessThanOrEqual: LLVMIntSLE, ] /// Retrieves the corresponding `LLVMIntPredicate`. var llvm: LLVMIntPredicate { return IntPredicate.predicateMapping[self]! } } /// The condition codes available for floating comparison instructions. public enum RealPredicate { /// No comparison, always returns `false`. case `false` /// Ordered and equal. case orderedEqual /// Ordered greater than. case orderedGreaterThan /// Ordered greater than or equal. case orderedGreaterThanOrEqual /// Ordered less than. case orderedLessThan /// Ordered less than or equal. case orderedLessThanOrEqual /// Ordered and not equal. case orderedNotEqual /// Ordered (no nans). case ordered /// Unordered (either nans). case unordered /// Unordered or equal. case unorderedEqual /// Unordered or greater than. case unorderedGreaterThan /// Unordered or greater than or equal. case unorderedGreaterThanOrEqual /// Unordered or less than. case unorderedLessThan /// Unordered or less than or equal. case unorderedLessThanOrEqual /// Unordered or not equal. case unorderedNotEqual /// No comparison, always returns `true`. case `true` private static let predicateMapping: [RealPredicate: LLVMRealPredicate] = [ .false: LLVMRealPredicateFalse, .orderedEqual: LLVMRealOEQ, .orderedGreaterThan: LLVMRealOGT, .orderedGreaterThanOrEqual: LLVMRealOGE, .orderedLessThan: LLVMRealOLT, .orderedLessThanOrEqual: LLVMRealOLE, .orderedNotEqual: LLVMRealONE, .ordered: LLVMRealORD, .unordered: LLVMRealUNO, .unorderedEqual: LLVMRealUEQ, .unorderedGreaterThan: LLVMRealUGT, .unorderedGreaterThanOrEqual: LLVMRealUGE, .unorderedLessThan: LLVMRealULT, .unorderedLessThanOrEqual: LLVMRealULE, .unorderedNotEqual: LLVMRealUNE, .true: LLVMRealPredicateTrue, ] /// Retrieves the corresponding `LLVMRealPredicate`. var llvm: LLVMRealPredicate { return RealPredicate.predicateMapping[self]! } } /// `AtomicOrdering` enumerates available memory ordering semantics. /// /// Atomic instructions (`cmpxchg`, `atomicrmw`, `fence`, `atomic load`, and /// `atomic store`) take ordering parameters that determine which other atomic /// instructions on the same address they synchronize with. These semantics are /// borrowed from Java and C++0x, but are somewhat more colloquial. If these /// descriptions aren’t precise enough, check those specs (see spec references /// in the atomics guide). fence instructions treat these orderings somewhat /// differently since they don’t take an address. See that instruction’s /// documentation for details. public enum AtomicOrdering: Comparable { /// A load or store which is not atomic case notAtomic /// Lowest level of atomicity, guarantees somewhat sane results, lock free. /// /// The set of values that can be read is governed by the happens-before /// partial order. A value cannot be read unless some operation wrote it. This /// is intended to provide a guarantee strong enough to model Java’s /// non-volatile shared variables. This ordering cannot be specified for /// read-modify-write operations; it is not strong enough to make them atomic /// in any interesting way. case unordered /// Guarantees that if you take all the operations affecting a specific /// address, a consistent ordering exists. /// /// In addition to the guarantees of unordered, there is a single total order /// for modifications by monotonic operations on each address. All /// modification orders must be compatible with the happens-before order. /// There is no guarantee that the modification orders can be combined to a /// global total order for the whole program (and this often will not be /// possible). The read in an atomic read-modify-write operation (cmpxchg and /// atomicrmw) reads the value in the modification order immediately before /// the value it writes. If one atomic read happens before another atomic read /// of the same address, the later read must see the same value or a later /// value in the address’s modification order. This disallows reordering of /// monotonic (or stronger) operations on the same address. If an address is /// written monotonic-ally by one thread, and other threads monotonic-ally /// read that address repeatedly, the other threads must eventually see the /// write. This corresponds to the C++0x/C1x memory_order_relaxed. case monotonic /// Acquire provides a barrier of the sort necessary to acquire a lock to /// access other memory with normal loads and stores. /// /// In addition to the guarantees of monotonic, a synchronizes-with edge may /// be formed with a release operation. This is intended to model C++’s /// `memory_order_acquire`. case acquire /// Release is similar to Acquire, but with a barrier of the sort necessary to /// release a lock. /// /// In addition to the guarantees of monotonic, if this operation writes a /// value which is subsequently read by an acquire operation, it /// synchronizes-with that operation. (This isn’t a complete description; see /// the C++0x definition of a release sequence.) This corresponds to the /// C++0x/C1x memory_order_release. case release /// provides both an Acquire and a Release barrier (for fences and operations /// which both read and write memory). /// /// This corresponds to the C++0x/C1x memory_order_acq_rel. case acquireRelease /// Provides Acquire semantics for loads and Release semantics for stores. /// /// In addition to the guarantees of acq_rel (acquire for an operation that /// only reads, release for an operation that only writes), there is a global /// total order on all sequentially-consistent operations on all addresses, /// which is consistent with the happens-before partial order and with the /// modification orders of all the affected addresses. Each /// sequentially-consistent read sees the last preceding write to the same /// address in this global order. This corresponds to the C++0x/C1x /// `memory_order_seq_cst` and Java volatile. case sequentiallyConsistent private static let orderingMapping: [AtomicOrdering: LLVMAtomicOrdering] = [ .notAtomic: LLVMAtomicOrderingNotAtomic, .unordered: LLVMAtomicOrderingUnordered, .monotonic: LLVMAtomicOrderingMonotonic, .acquire: LLVMAtomicOrderingAcquire, .release: LLVMAtomicOrderingRelease, .acquireRelease: LLVMAtomicOrderingAcquireRelease, .sequentiallyConsistent: LLVMAtomicOrderingSequentiallyConsistent, ] /// Returns whether the left atomic ordering is strictly weaker than the /// right atomic order. public static func <(lhs: AtomicOrdering, rhs: AtomicOrdering) -> Bool { return lhs.llvm.rawValue < rhs.llvm.rawValue } /// Retrieves the corresponding `LLVMAtomicOrdering`. var llvm: LLVMAtomicOrdering { return AtomicOrdering.orderingMapping[self]! } } /// `AtomicReadModifyWriteOperation` enumerates the kinds of supported atomic /// read-write-modify operations. public enum AtomicReadModifyWriteOperation { /// Set the new value and return the one old /// /// ``` /// *ptr = val /// ``` case xchg /// Add a value and return the old one /// /// ``` /// *ptr = *ptr + val /// ``` case add /// Subtract a value and return the old one /// /// ``` /// *ptr = *ptr - val /// ``` case sub /// And a value and return the old one /// /// ``` /// *ptr = *ptr & val /// ``` case and /// Not-And a value and return the old one /// /// ``` /// *ptr = ~(*ptr & val) /// ``` case nand /// OR a value and return the old one /// /// ``` /// *ptr = *ptr | val /// ``` case or /// Xor a value and return the old one /// /// ``` /// *ptr = *ptr ^ val /// ``` case xor /// Sets the value if it's greater than the original using a signed comparison /// and return the old one. /// /// ``` /// // Using a signed comparison /// *ptr = *ptr > val ? *ptr : val /// ``` case max /// Sets the value if it's Smaller than the original using a signed comparison /// and return the old one. /// /// ``` /// // Using a signed comparison /// *ptr = *ptr < val ? *ptr : val /// ``` case min /// Sets the value if it's greater than the original using an unsigned /// comparison and return the old one. /// /// ``` /// // Using an unsigned comparison /// *ptr = *ptr > val ? *ptr : val /// ``` case umax /// Sets the value if it's greater than the original using an unsigned /// comparison and return the old one. /// /// ``` /// // Using an unsigned comparison /// *ptr = *ptr < val ? *ptr : val /// ``` case umin private static let atomicRMWMapping: [AtomicReadModifyWriteOperation: LLVMAtomicRMWBinOp] = [ .xchg: LLVMAtomicRMWBinOpXchg, .add: LLVMAtomicRMWBinOpAdd, .sub: LLVMAtomicRMWBinOpSub, .and: LLVMAtomicRMWBinOpAnd, .nand: LLVMAtomicRMWBinOpNand, .or: LLVMAtomicRMWBinOpOr, .xor: LLVMAtomicRMWBinOpXor, .max: LLVMAtomicRMWBinOpMax, .min: LLVMAtomicRMWBinOpMin, .umax: LLVMAtomicRMWBinOpUMax, .umin: LLVMAtomicRMWBinOpUMin, ] /// Retrieves the corresponding `LLVMAtomicRMWBinOp`. var llvm: LLVMAtomicRMWBinOp { return AtomicReadModifyWriteOperation.atomicRMWMapping[self]! } } /// Enumerates the dialects of inline assembly LLVM's parsers can handle. public enum InlineAssemblyDialect { /// The dialect of assembly created at Bell Labs by AT&T. /// /// AT&T syntax differs from Intel syntax in a number of ways. Notably: /// /// - The source operand is before the destination operand /// - Immediate operands are prefixed by a dollar-sign (`$`) /// - Register operands are preceded by a percent-sign (`%`) /// - The size of memory operands is determined from the last character of the /// the opcode name. Valid suffixes include `b` for "byte" (8-bit), /// `w` for "word" (16-bit), `l` for "long-word" (32-bit), and `q` for /// "quad-word" (64-bit) memory references case att /// The dialect of assembly created at Intel. /// /// Intel syntax differs from AT&T syntax in a number of ways. Notably: /// /// - The destination operand is before the source operand /// - Immediate and register operands have no prefix. /// - Memory operands are annotated with their sizes. Valid annotations /// include `byte ptr` (8-bit), `word ptr` (16-bit), `dword ptr` (32-bit) and /// `qword ptr` (64-bit). case intel private static let dialectMapping: [InlineAssemblyDialect: LLVMInlineAsmDialect] = [ .att: LLVMInlineAsmDialectATT, .intel: LLVMInlineAsmDialectIntel, ] /// Retrieves the corresponding `LLVMInlineAsmDialect`. var llvm: LLVMInlineAsmDialect { return InlineAssemblyDialect.dialectMapping[self]! } }
mit
LoopKit/LoopKit
LoopKit/DeviceManager/PumpManager.swift
1
12933
// // PumpManager.swift // Loop // // Copyright © 2018 LoopKit Authors. All rights reserved. // import Foundation import HealthKit public enum PumpManagerResult<T> { case success(T) case failure(PumpManagerError) } public protocol PumpManagerStatusObserver: AnyObject { func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) } public enum BolusActivationType: String, Codable { case manualNoRecommendation case manualRecommendationAccepted case manualRecommendationChanged case automatic public var isAutomatic: Bool { self == .automatic } static public func activationTypeFor(recommendedAmount: Double?, bolusAmount: Double) -> BolusActivationType { guard let recommendedAmount = recommendedAmount else { return .manualNoRecommendation } return recommendedAmount =~ bolusAmount ? .manualRecommendationAccepted : .manualRecommendationChanged } } public protocol PumpManagerDelegate: DeviceManagerDelegate, PumpManagerStatusObserver { func pumpManagerBLEHeartbeatDidFire(_ pumpManager: PumpManager) /// Queries the delegate as to whether Loop requires the pump to provide its own periodic scheduling /// via BLE. /// This is the companion to `PumpManager.setMustProvideBLEHeartbeat(_:)` func pumpManagerMustProvideBLEHeartbeat(_ pumpManager: PumpManager) -> Bool /// Informs the delegate that the manager is deactivating and should be deleted func pumpManagerWillDeactivate(_ pumpManager: PumpManager) /// Informs the delegate that the hardware this PumpManager has been reporting for has been replaced. func pumpManagerPumpWasReplaced(_ pumpManager: PumpManager) /// Triggered when pump model changes. With a more formalized setup flow (which requires a successful model fetch), /// this delegate method could go away. func pumpManager(_ pumpManager: PumpManager, didUpdatePumpRecordsBasalProfileStartEvents pumpRecordsBasalProfileStartEvents: Bool) /// Reports an error that should be surfaced to the user func pumpManager(_ pumpManager: PumpManager, didError error: PumpManagerError) /// This should be called any time the PumpManager synchronizes with the pump, even if there are no new doses in the log, as changes to lastReconciliation /// indicate we can trust insulin delivery status up until that point, even if there are no new doses. /// For pumps whose only source of dosing adjustments is Loop, lastReconciliation should be reflective of the last time we received telemetry from the pump. /// For pumps with a user interface and dosing history capabilities, lastReconciliation should be reflective of the last time we reconciled fully with pump history, and know /// that we have accounted for any external doses. It is possible for the pump to report reservoir data beyond the date of lastReconciliation, and Loop can use it for /// calculating IOB. func pumpManager(_ pumpManager: PumpManager, hasNewPumpEvents events: [NewPumpEvent], lastReconciliation: Date?, completion: @escaping (_ error: Error?) -> Void) func pumpManager(_ pumpManager: PumpManager, didReadReservoirValue units: Double, at date: Date, completion: @escaping (_ result: Result<(newValue: ReservoirValue, lastValue: ReservoirValue?, areStoredValuesContinuous: Bool), Error>) -> Void) func pumpManager(_ pumpManager: PumpManager, didAdjustPumpClockBy adjustment: TimeInterval) func pumpManagerDidUpdateState(_ pumpManager: PumpManager) func startDateToFilterNewPumpEvents(for manager: PumpManager) -> Date /// Indicates the system time offset from a trusted time source. If the return value is added to the system time, the result is the trusted time source value. If the trusted time source is earlier than the system time, the return value is negative. var detectedSystemTimeOffset: TimeInterval { get } } public protocol PumpManager: DeviceManager { /// The maximum number of scheduled basal rates in a single day supported by the pump. Used during onboarding by therapy settings. static var onboardingMaximumBasalScheduleEntryCount: Int { get } /// All user-selectable basal rates, in Units per Hour. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedBasalRates: [Double] { get } /// All user-selectable bolus volumes, in Units. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedBolusVolumes: [Double] { get } /// All user-selectable maximum bolus volumes, in Units. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedMaximumBolusVolumes: [Double] { get } /// The queue on which PumpManagerDelegate methods are called /// Setting to nil resets to a default provided by the manager var delegateQueue: DispatchQueue! { get set } /// Rounds a basal rate in U/hr to a rate supported by this pump. /// /// - Parameters: /// - unitsPerHour: A desired rate of delivery in Units per Hour /// - Returns: The rounded rate of delivery in Units per Hour. The rate returned should not be larger than the passed in rate. func roundToSupportedBasalRate(unitsPerHour: Double) -> Double /// Rounds a bolus volume in Units to a volume supported by this pump. /// /// - Parameters: /// - units: A desired volume of delivery in Units /// - Returns: The rounded bolus volume in Units. The volume returned should not be larger than the passed in rate. func roundToSupportedBolusVolume(units: Double) -> Double /// All user-selectable basal rates, in Units per Hour. Must be non-empty. var supportedBasalRates: [Double] { get } /// All user-selectable bolus volumes, in Units. Must be non-empty. var supportedBolusVolumes: [Double] { get } /// All user-selectable bolus volumes for setting the maximum allowed bolus, in Units. Must be non-empty. var supportedMaximumBolusVolumes: [Double] { get } /// The maximum number of scheduled basal rates in a single day supported by the pump var maximumBasalScheduleEntryCount: Int { get } /// The basal schedule duration increment, beginning at midnight, supported by the pump var minimumBasalScheduleEntryDuration: TimeInterval { get } /// The primary client receiving notifications about the pump lifecycle /// All delegate methods are called on `delegateQueue` var pumpManagerDelegate: PumpManagerDelegate? { get set } /// Whether the PumpManager provides DoseEntry values for scheduled basal delivery. If false, Loop will use the basal schedule to infer normal basal delivery during times not overridden by: /// - Temporary basal delivery /// - Suspend/Resume pairs /// - Rewind/Prime pairs var pumpRecordsBasalProfileStartEvents: Bool { get } /// The maximum reservoir volume of the pump var pumpReservoirCapacity: Double { get } /// The time of the last sync with the pump's event history, or reservoir, or last status check if pump does not provide history. var lastSync: Date? { get } /// The most-recent status var status: PumpManagerStatus { get } /// Adds an observer of changes in PumpManagerStatus /// /// Observers are held by weak reference. /// /// - Parameters: /// - observer: The observing object /// - queue: The queue on which the observer methods should be called func addStatusObserver(_ observer: PumpManagerStatusObserver, queue: DispatchQueue) /// Removes an observer of changes in PumpManagerStatus /// /// Since observers are held weakly, calling this method is not required when the observer is deallocated /// /// - Parameter observer: The observing object func removeStatusObserver(_ observer: PumpManagerStatusObserver) /// Ensure that the pump's data (reservoir/events) is up to date. If not, fetch it. /// The PumpManager should call the completion block with the date of last sync with the pump, nil if no sync has occurred func ensureCurrentPumpData(completion: ((_ lastSync: Date?) -> Void)?) /// Loop calls this method when the current environment requires the pump to provide its own periodic /// scheduling via BLE. /// The manager may choose to still enable its own heartbeat even if `mustProvideBLEHeartbeat` is false func setMustProvideBLEHeartbeat(_ mustProvideBLEHeartbeat: Bool) /// Returns a dose estimator for the current bolus, if one is in progress func createBolusProgressReporter(reportingOn dispatchQueue: DispatchQueue) -> DoseProgressReporter? /// Returns the estimated time for the bolus amount to be delivered func estimatedDuration(toBolus units: Double) -> TimeInterval /// Send a bolus command and handle the result /// /// - Parameters: /// - units: The number of units to deliver /// - automatic: Whether the dose was triggered automatically as opposed to commanded by user /// - completion: A closure called after the command is complete /// - error: An optional error describing why the command failed func enactBolus(units: Double, activationType: BolusActivationType, completion: @escaping (_ error: PumpManagerError?) -> Void) /// Cancels the current, in progress, bolus. /// /// - Parameters: /// - completion: A closure called after the command is complete /// - result: A DoseEntry containing the actual delivery amount of the canceled bolus, nil if canceled bolus information is not available, or an error describing why the command failed. func cancelBolus(completion: @escaping (_ result: PumpManagerResult<DoseEntry?>) -> Void) /// Send a temporary basal rate command and handle the result /// /// - Parameters: /// - unitsPerHour: The temporary basal rate to set /// - duration: The duration of the temporary basal rate. If you pass in a duration of 0, that cancels any currently running Temp Basal /// - completion: A closure called after the command is complete /// - error: An optional error describing why the command failed func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval, completion: @escaping (_ error: PumpManagerError?) -> Void) /// Send a command to the pump to suspend delivery /// /// - Parameters: /// - completion: A closure called after the command is complete /// - error: An error describing why the command failed func suspendDelivery(completion: @escaping (_ error: Error?) -> Void) /// Send a command to the pump to resume delivery /// /// - Parameters: /// - completion: A closure called after the command is complete /// - error: An error describing why the command failed func resumeDelivery(completion: @escaping (_ error: Error?) -> Void) /// Sync the schedule of basal rates to the pump, annotating the result with the proper time zone. /// /// - Precondition: /// - `scheduleItems` must not be empty. /// /// - Parameters: /// - scheduleItems: The items comprising the basal rate schedule /// - completion: A closure called after the command is complete /// - result: A BasalRateSchedule or an error describing why the command failed func syncBasalRateSchedule(items scheduleItems: [RepeatingScheduleValue<Double>], completion: @escaping (_ result: Result<BasalRateSchedule, Error>) -> Void) /// Sync the delivery limits for basal rate and bolus. If the pump does not support setting max bolus or max basal rates, the completion should be called with success including the provided delivery limits. /// /// - Parameters: /// - deliveryLimits: The delivery limits /// - completion: A closure called after the command is complete /// - result: The delivery limits set or an error describing why the command failed func syncDeliveryLimits(limits deliveryLimits: DeliveryLimits, completion: @escaping (_ result: Result<DeliveryLimits, Error>) -> Void) } public extension PumpManager { func roundToSupportedBasalRate(unitsPerHour: Double) -> Double { return supportedBasalRates.filter({$0 <= unitsPerHour}).max() ?? 0 } func roundToSupportedBolusVolume(units: Double) -> Double { return supportedBolusVolumes.filter({$0 <= units}).max() ?? 0 } /// Convenience wrapper for notifying the delegate of deactivation on the delegate queue /// /// - Parameters: /// - completion: A closure called from the delegate queue after the delegate is called func notifyDelegateOfDeactivation(completion: @escaping () -> Void) { delegateQueue.async { self.pumpManagerDelegate?.pumpManagerWillDeactivate(self) completion() } } }
mit
natecook1000/swift-compiler-crashes
fixed/25587-swift-typebase-getanyoptionalobjecttype.swift
7
255
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{class A{class B{class A{class A{func f<d}}}}enum a{{}enum S<T where T:a{class B
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/17131-swift-declcontext-lookupqualified.swift
11
234
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { class A { { } class B var d { class a<T where T : T> : a
mit
OpenStreetMap-Monitoring/OsMoiOs
iOsmo/AuthViewController.swift
2
7052
// // AuthViewController.swift // iOsmo // // Created by Olga Grineva on 22/12/14. // Copyright (c) 2014 Olga Grineva. All rights reserved. // import UIKit enum SignActions: Int { case SignIn = 1 //default case SignUp = 2 } protocol AuthResultProtocol { func succesfullLoginWithToken (_ controller: AuthViewController, info : AuthInfo) -> Void func loginCancelled (_ controller: AuthViewController) -> Void } open class AuthViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate { let log = LogQueue.sharedLogQueue @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passField: UITextField! @IBOutlet weak var nickField: UITextField! @IBOutlet weak var pass2Field: UITextField! @IBOutlet weak var signButton: UIButton! @IBOutlet weak var actButton: UIButton! @IBOutlet weak var forgotButton: UIButton! @IBOutlet weak var signLabel: UILabel! @IBOutlet weak var registerView: UIView! @IBOutlet weak var signToRegConstraint: NSLayoutConstraint! @IBOutlet weak var signToPassConstraint: NSLayoutConstraint! var signAction: SignActions = SignActions.SignIn @IBAction func OnCancel(_ sender: AnyObject) { delegate?.loginCancelled(self) } var delegate: AuthResultProtocol? override open func viewDidLoad() { super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Смена режима формы с логина на регистрацию и обратоно @IBAction func setSignMode(_ sender: UIButton) { if signAction == SignActions.SignIn { signAction = SignActions.SignUp } else { signAction = SignActions.SignIn } switch signAction { case SignActions.SignIn: signButton.setTitle(NSLocalizedString("Register", comment: "Register label"), for: .normal) actButton.setTitle(NSLocalizedString("Sign-In", comment: "Sign-in label"), for: .normal) signLabel.text = NSLocalizedString("Sign-In", comment: "Sign-in label") signToRegConstraint.priority = UILayoutPriority(rawValue: 500) signToPassConstraint.priority = UILayoutPriority(rawValue: 999) registerView.isHidden = true forgotButton.isHidden = false default: signButton.setTitle(NSLocalizedString("Sign-In", comment: "Sign-in label"), for: .normal) actButton.setTitle(NSLocalizedString("Register", comment: "Register label"), for: .normal) signLabel.text = NSLocalizedString("Register", comment: "Register label") signToRegConstraint.priority = UILayoutPriority(rawValue: 999) signToPassConstraint.priority = UILayoutPriority(rawValue: 500) registerView.isHidden = false forgotButton.isHidden = true } } @IBAction func signAction(_ sender: UIButton) { if (signAction == SignActions.SignUp ) { if (passField.text != pass2Field.text) { self.alert("OsMo registration", message: NSLocalizedString("Passwords didn't match!", comment: "Passwords didn't match!")) return } if (nickField.text == "") { self.alert("OsMo registration", message: NSLocalizedString("Enter nick!", comment: "Enter nick!")) return } } let device = SettingsManager.getKey(SettingKeys.device)! as String let url = URL(string: signAction == SignActions.SignIn ? "https://\(URLs.osmoDomain)/signin?" : "https://api2.osmo.mobi/signup?") let session = URLSession.shared; var urlReq = URLRequest(url: url!); var requestBody:String = "key=\(device)&email=\(emailField.text!)&password=\(passField.text!)" if (signAction == SignActions.SignUp) { requestBody = "\(requestBody)&nick=\(nickField.text!)" } urlReq.httpMethod = "POST" urlReq.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData urlReq.httpBody = requestBody.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let task = session.dataTask(with: urlReq as URLRequest) {(data, response, error) in var res : NSDictionary = [:] guard let data = data, let _:URLResponse = response, error == nil else { print("error: on send post request") LogQueue.sharedLogQueue.enqueue("error: on send post request") return } //let dataStr = NSString(data: data, encoding: String.Encoding.utf8.rawValue) do { let jsonDict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers); res = (jsonDict as? NSDictionary)! print(res) if let user = res["nick"] { DispatchQueue.main.async { self.delegate?.succesfullLoginWithToken(self, info: AuthInfo(accountName: user as! String, key: "")) } } else { if let error = res["error_description"] { DispatchQueue.main.async { self.alert("OsMo registration", message: error as! String ) } } } } catch { print("error serializing JSON from POST") LogQueue.sharedLogQueue.enqueue("error serializing JSON from POST") return } } task.resume() } @IBAction func forgotPassword(_ sender: UIButton) { UIApplication.shared.open(URL(string: "https://osmo.mobi/forgot?utm_campaign=OsMo.App&utm_source=iOsMo&utm_term=forgot")!, options: [:], completionHandler: nil) } func alert(_ title: String, message: String) { let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert) myAlert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"OK"), style: .default, handler: nil)) self.present(myAlert, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK UITextFieldDelegate public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
gpl-3.0
leonereveel/Moya
Source/Moya.swift
1
6075
import Foundation import Result /// Closure to be executed when a request has completed. public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> () /// Closure to be executed when progress changes. public typealias ProgressBlock = (progress: ProgressResponse) -> Void public struct ProgressResponse { public let totalBytes: Int64 public let bytesExpected: Int64 public let response: Response? init(totalBytes: Int64 = 0, bytesExpected: Int64 = 0, response: Response? = nil) { self.totalBytes = totalBytes self.bytesExpected = bytesExpected self.response = response } public var progress: Double { return bytesExpected > 0 ? min(Double(totalBytes) / Double(bytesExpected), 1.0) : 1.0 } public var completed: Bool { return totalBytes >= bytesExpected && response != nil } } /// Request provider class. Requests should be made through this class only. public class MoyaProvider<Target: TargetType> { /// Closure that defines the endpoints for the provider. public typealias EndpointClosure = Target -> Endpoint<Target> /// Closure that decides if and what request should be performed public typealias RequestResultClosure = Result<NSURLRequest, Moya.Error> -> Void /// Closure that resolves an `Endpoint` into a `RequestResult`. public typealias RequestClosure = (Endpoint<Target>, RequestResultClosure) -> Void /// Closure that decides if/how a request should be stubbed. public typealias StubClosure = Target -> Moya.StubBehavior public let endpointClosure: EndpointClosure public let requestClosure: RequestClosure public let stubClosure: StubClosure public let manager: Manager /// A list of plugins /// e.g. for logging, network activity indicator or credentials public let plugins: [PluginType] public let trackInflights: Bool public internal(set) var inflightRequests = Dictionary<Endpoint<Target>, [Moya.Completion]>() /// Initializes a provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = MoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false) { self.endpointClosure = endpointClosure self.requestClosure = requestClosure self.stubClosure = stubClosure self.manager = manager self.plugins = plugins self.trackInflights = trackInflights } /// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`. public func endpoint(token: Target) -> Endpoint<Target> { return endpointClosure(token) } /// Designated request-making method. Returns a `Cancellable` token to cancel the request later. public func request(target: Target, completion: Moya.Completion) -> Cancellable { return self.request(target, queue: nil, completion: completion) } /// Designated request-making method with queue option. Returns a `Cancellable` token to cancel the request later. public func request(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> Cancellable { return requestNormal(target, queue: queue, progress: progress, completion: completion) } /// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method. /// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override. func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { let cancellableToken = CancellableToken { } notifyPluginsOfImpendingStub(request, target: target) let plugins = self.plugins let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins) switch stubBehavior { case .Immediate: stub() case .Delayed(let delay): let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC)) let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset) dispatch_after(killTime, dispatch_get_main_queue()) { stub() } case .Never: fatalError("Method called to stub request when stubbing is disabled.") } return cancellableToken } } /// Mark: Stubbing public extension MoyaProvider { // Swift won't let us put the StubBehavior enum inside the provider class, so we'll // at least add some class functions to allow easy access to common stubbing closures. public final class func NeverStub(_: Target) -> Moya.StubBehavior { return .Never } public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior { return .Immediate } public final class func DelayedStub(seconds: NSTimeInterval) -> (Target) -> Moya.StubBehavior { return { _ in return .Delayed(seconds: seconds) } } } public func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> Result<Moya.Response, Moya.Error> { switch (response, data, error) { case let (.Some(response), data, .None): let response = Moya.Response(statusCode: response.statusCode, data: data ?? NSData(), response: response) return .Success(response) case let (_, _, .Some(error)): let error = Moya.Error.Underlying(error) return .Failure(error) default: let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil)) return .Failure(error) } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/03206-swift-sourcemanager-getmessage.swift
11
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ([Void{ extension NSData { func a<T where g: a { protocol c { class case c,
mit
tapglue/ios_sample
TapglueSample/LoginSignInVC.swift
1
3217
// // LoginSignInVC.swift // TapglueSample // // Created by Özgür Celebi on 14/12/15. // Copyright © 2015 Özgür Celebi. All rights reserved. // import UIKit import Tapglue class LoginSignInVC: UIViewController { @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate override func viewDidLoad() { super.viewDidLoad() } override func viewWillDisappear(animated: Bool) { // Show navigationBar again when view disappears self.navigationController?.navigationBarHidden = false } @IBAction func signInButtonPressed(sender: UIButton) { // If textFields have more then 2 characters, begin Tapglue login if userNameTextField.text?.characters.count > 2 && passwordTextField.text?.characters.count > 2 { let username = userNameTextField.text! let password = passwordTextField.text! // NewSDK appDel.rxTapglue.loginUser(username, password: password).subscribe({ (event) in switch event { case .Next(let user): print("User logged in: \(user)") case .Error(let error): let err = error as! TapglueError switch err.code! { case 1001: let alertController = UIAlertController(title: "Error", message: "User does not exist.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) case 0: let alertController = UIAlertController(title: "Error", message: "Wrong password.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) default: "Error code was not added to switch" } case .Completed: self.navigationController?.popToRootViewControllerAnimated(false) } }).addDisposableTo(self.appDel.disposeBag) } else { let alertController = UIAlertController(title: "Not enough characters", message: "Username and Password must be at least 3 characters.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } }
apache-2.0
grandiere/box
box/Model/GridVisor/Camera/MGridVisorCamera.swift
1
5900
import UIKit import AVFoundation import ImageIO class MGridVisorCamera:NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { private var captureSession:AVCaptureSession? private weak var controller:CGridVisor! private weak var videoDataOutput:AVCaptureVideoDataOutput? private weak var captureDeviceInput:AVCaptureDeviceInput? private let queueCamera:DispatchQueue private let queueOutput:DispatchQueue private let kDevicePosition:AVCaptureDevicePosition = AVCaptureDevicePosition.back private let kMediaType:String = AVMediaTypeVideo private let kSessionPreset:String = AVCaptureSessionPreset640x480 private let kVideoGravity:String = AVLayerVideoGravityResizeAspect private let kVideoCodec:String = AVVideoCodecJPEG private let kQueueCameraLabel:String = "visorCameraQueue" private let kQueueOutputLabel:String = "visorOutputQueue" private let kImageOrientationUp:Int32 = 6 init(controller:CGridVisor) { self.controller = controller queueCamera = DispatchQueue( label:kQueueCameraLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency:DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global(qos:DispatchQoS.QoSClass.background)) queueOutput = DispatchQueue( label:kQueueOutputLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency:DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global(qos:DispatchQoS.QoSClass.background)) super.init() askAuthorization() } deinit { cleanSession() } //MARK: private private func askAuthorization() { AVCaptureDevice.requestAccess(forMediaType:kMediaType) { [weak self] (granted:Bool) in if granted { self?.queueCamera.async { [weak self] in self?.startSession() } } else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoAuth", comment:"") VAlert.messageOrange(message:error) } } } private func startSession() { let captureSession:AVCaptureSession = AVCaptureSession() captureSession.sessionPreset = kSessionPreset self.captureSession = captureSession var captureDevice:AVCaptureDevice? if #available(iOS 10.0, *) { captureDevice = AVCaptureDevice.defaultDevice( withDeviceType:AVCaptureDeviceType.builtInWideAngleCamera, mediaType:kMediaType, position:kDevicePosition) } else { let devices:[Any] = AVCaptureDevice.devices( withMediaType:kMediaType) for device:Any in devices { guard let capture:AVCaptureDevice = device as? AVCaptureDevice else { continue } if capture.position == kDevicePosition { captureDevice = capture break } } } guard let foundCaptureDevice:AVCaptureDevice = captureDevice else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoCaptureDevice", comment:"") VAlert.messageOrange(message:error) return } let captureDeviceInput:AVCaptureDeviceInput do { try captureDeviceInput = AVCaptureDeviceInput( device:foundCaptureDevice) } catch let error { print(error.localizedDescription) return } self.captureDeviceInput = captureDeviceInput captureSession.addInput(captureDeviceInput) let videoDataOutput:AVCaptureVideoDataOutput = AVCaptureVideoDataOutput() videoDataOutput.videoSettings = [String(kCVPixelBufferPixelFormatTypeKey) : Int(kCVPixelFormatType_32BGRA) as NSNumber] videoDataOutput.setSampleBufferDelegate( self, queue:queueOutput) self.videoDataOutput = videoDataOutput if captureSession.canAddOutput(videoDataOutput) { captureSession.addOutput(videoDataOutput) captureSession.startRunning() } else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoOutput", comment:"") VAlert.messageOrange(message:error) } } //MARK: public func cleanSession() { captureSession?.stopRunning() captureSession?.removeInput(captureDeviceInput) captureSession?.removeOutput(videoDataOutput) } //MARK: captureOutput delegate func captureOutput(_ captureOutput:AVCaptureOutput!, didOutputSampleBuffer sampleBuffer:CMSampleBuffer!, from connection:AVCaptureConnection!) { guard let pixelBuffer:CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } let ciimage:CIImage = CIImage(cvImageBuffer:pixelBuffer) let imageOriented:CIImage = ciimage.applyingOrientation(kImageOrientationUp) controller.modelRender?.updateCameraImage(cIImage:imageOriented) } }
mit
cruisediary/Diving
Diving/Scenes/UserList/UserListScene.swift
1
188
// // UserListScene.swift // Diving // // Created by CruzDiary on 6/15/16. // Copyright © 2016 DigitalNomad. All rights reserved. // import UIKit class UserListScene: NSObject { }
mit
ryanchang0827/SwiftPlugin-God
SwiftPlugin-GodTests/SwiftPlugin_GodTests.swift
1
998
// // SwiftPlugin_GodTests.swift // SwiftPlugin-GodTests // // Created by Ryan on 2015/10/20. // Copyright © 2015年 Ryan. All rights reserved. // import XCTest @testable import SwiftPlugin_God class SwiftPlugin_GodTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
ffreling/pigeon
Pigeon/Pigeon/PAppDelegate.swift
1
1017
// // AppDelegate.swift // Pigeon // // Created by Fabien on 2014-10-18. // Copyright (c) 2014 Fabien. All rights reserved. // import Cocoa import AppKit @NSApplicationMain class PAppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow! var pigeonStatus: NSStatusItem! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application activateStatusMenu() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func activateStatusMenu() { var bar = NSStatusBar.systemStatusBar() // self.pigeonStatus = bar.statusItemWithLength(NSVariableStatusItemLength) // // self.pigeonStatus.title = "Pigeon" // self.pigeonStatus.highlightMode = true // self.pigeonStatus.action = "self.openBrowser" } func openBrowser(sender: AnyObject?) { NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://www.fastmail.fm")!) } }
bsd-2-clause
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/SandboxUpdateProductRequest.swift
1
1591
// // SandboxUpdateProductRequest.swift // UberGoCore // // Created by Nghia Tran on 6/20/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Alamofire import RxSwift import Unbox struct SandboxUpdateProductRequestParam: Parameter { public var productID: String? public var surgeMultiplier: Float? public var driversAvailable: Bool? func toDictionary() -> [String: Any] { var dict: [String: Any] = [:] if let surgeMultiplier = self.surgeMultiplier { dict["surge_multiplier"] = surgeMultiplier } if let driversAvailable = self.driversAvailable { dict["drivers_available"] = driversAvailable } return dict } } final class SandboxUpdateProductRequest: Request { // Type typealias Element = Void // Endpoint var endpoint: String { guard let param = self.param as? SandboxUpdateProductRequestParam else { return Constants.UberAPI.SandboxUpdateProduct } return Constants.UberAPI.SandboxUpdateProduct.replacingOccurrences(of: ":id", with: param.productID!) } // HTTP var httpMethod: HTTPMethod { return .put } // Param var param: Parameter? { return self._param } fileprivate var _param: SandboxUpdateProductRequestParam // MARK: - Init init(_ param: SandboxUpdateProductRequestParam) { self._param = param } // MARK: - Decode func decode(data: Any) throws -> Element? { return nil } }
mit
uptech/Constraid
Sources/Constraid/ProxyExtensions/ConstraidProxy+FlushWithMargins.swift
1
7323
// We don't conditional import AppKit like normal here because AppKit Autolayout doesn't support // the margin attributes that UIKit does. And of course this file isn't included in the MacOS // build target. #if os(iOS) import UIKit extension ConstraidProxy { /** Constrains the object's leading edge to the leading margin of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withLeadingMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withLeadingMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's trailing edge to the trailing margin of `item` - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to trailing margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the trailing margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTrailingMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTrailingMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top edge to the top margin of `item` - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTopMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTopMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's bottom edge to the bottom margin of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to bottom margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the bottom margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withBottomMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withBottomMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top & bottom edge to the top & bottom margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top & bottom margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top & bottom margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withVerticalMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withVerticalMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading & trailing edge to the leading & trailing margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading & trailing margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading & trailing margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withHorizontalMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withHorizontalMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading, trailing, top, & bottom edge to the leading, trailing, top & bottom margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading, trailing, top & bottom margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading, trailing, top and bottom margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } } #endif
mit
BenEmdon/swift-algorithm-club
Binary Search Tree/Solution 2/BinarySearchTree.swift
1
2911
/* Binary search tree using value types The tree is immutable. Any insertions or deletions will create a new tree. */ public enum BinarySearchTree<T: Comparable> { case Empty case Leaf(T) indirect case Node(BinarySearchTree, T, BinarySearchTree) /* How many nodes are in this subtree. Performance: O(n). */ public var count: Int { switch self { case .Empty: return 0 case .Leaf: return 1 case let .Node(left, _, right): return left.count + 1 + right.count } } /* Distance of this node to its lowest leaf. Performance: O(n). */ public var height: Int { switch self { case .Empty: return 0 case .Leaf: return 1 case let .Node(left, _, right): return 1 + max(left.height, right.height) } } /* Inserts a new element into the tree. Performance: runs in O(h) time, where h is the height of the tree. */ public func insert(newValue: T) -> BinarySearchTree { switch self { case .Empty: return .Leaf(newValue) case .Leaf(let value): if newValue < value { return .Node(.Leaf(newValue), value, .Empty) } else { return .Node(.Empty, value, .Leaf(newValue)) } case .Node(let left, let value, let right): if newValue < value { return .Node(left.insert(newValue), value, right) } else { return .Node(left, value, right.insert(newValue)) } } } /* Finds the "highest" node with the specified value. Performance: runs in O(h) time, where h is the height of the tree. */ public func search(x: T) -> BinarySearchTree? { switch self { case .Empty: return nil case .Leaf(let y): return (x == y) ? self : nil case let .Node(left, y, right): if x < y { return left.search(x) } else if y < x { return right.search(x) } else { return self } } } public func contains(x: T) -> Bool { return search(x) != nil } /* Returns the leftmost descendent. O(h) time. */ public func minimum() -> BinarySearchTree { var node = self var prev = node while case let .Node(next, _, _) = node { prev = node node = next } if case .Leaf = node { return node } return prev } /* Returns the rightmost descendent. O(h) time. */ public func maximum() -> BinarySearchTree { var node = self var prev = node while case let .Node(_, _, next) = node { prev = node node = next } if case .Leaf = node { return node } return prev } } extension BinarySearchTree: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .Empty: return "." case .Leaf(let value): return "\(value)" case .Node(let left, let value, let right): return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))" } } }
mit
lyft/SwiftLint
Source/swiftlint/Commands/GenerateDocsCommand.swift
1
1267
import Commandant import Result import SwiftLintFramework struct GenerateDocsCommand: CommandProtocol { let verb = "generate-docs" let function = "Generates markdown documentation for all rules" func run(_ options: GenerateDocsOptions) -> Result<(), CommandantError<()>> { let text = masterRuleList.generateDocumentation() if let path = options.path { do { try text.write(toFile: path, atomically: true, encoding: .utf8) } catch { return .failure(.usageError(description: error.localizedDescription)) } } else { queuedPrint(text) } return .success(()) } } struct GenerateDocsOptions: OptionsProtocol { let path: String? static func create(_ path: String?) -> GenerateDocsOptions { return self.init(path: path) } static func evaluate(_ mode: CommandMode) -> Result<GenerateDocsOptions, CommandantError<CommandantError<()>>> { return create <*> mode <| Option(key: "path", defaultValue: nil, usage: "the path where the documentation should be saved. " + "If not present, it'll be printed to the output.") } }
mit
dreamsxin/swift
validation-test/stdlib/Collection/MinimalRangeReplaceableBidirectionalCollection.swift
2
2766
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %S/../../../utils/gyb %s -o %t/main.swift // RUN: %S/../../../utils/line-directive %t/main.swift -- %target-build-swift %t/main.swift -o %t/MinimalRangeReplaceableBidirectionalCollection.swift.a.out // RUN: %S/../../../utils/line-directive %t/main.swift -- %target-run %t/MinimalRangeReplaceableBidirectionalCollection.swift.a.out // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var CollectionTests = TestSuite("Collection") // Test collections using value types as elements. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableBidirectionalCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return MinimalRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return MinimalRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) } // Test collections using a reference type as element. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableBidirectionalCollectionTests( makeCollection: { (elements: [LifetimeTracked]) in return MinimalRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValue: { (element: OpaqueValue<Int>) in LifetimeTracked(element.value, identity: element.identity) }, extractValue: { (element: LifetimeTracked) in OpaqueValue(element.value, identity: element.identity) }, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in // FIXME: use LifetimeTracked. return MinimalRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) } runAllTests()
apache-2.0
yangalex/WeMeet
WeMeet/View Controllers/LoginViewController.swift
1
3527
// // LoginViewController.swift // WeMeet // // Created by Alexandre Yang on 8/9/15. // Copyright (c) 2015 Alex Yang. All rights reserved. // import UIKit import SVProgressHUD class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // check if user is already logged in // if let user = PFUser.currentUser() { // if user.isAuthenticated() { // performSegueWithIdentifier("SignInSegue", sender: nil) // } // } let viewTapGesture = UITapGestureRecognizer(target: self, action: "dismissTextFields") viewTapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(viewTapGesture) setUpTextFields() setUpButton() } func dismissTextFields() { if usernameTextField.isFirstResponder() { usernameTextField.resignFirstResponder() } else if passwordTextField.isFirstResponder() { passwordTextField.resignFirstResponder() } } func setUpTextFields() { let bottomBorder = CALayer() bottomBorder.frame = CGRectMake(0, usernameTextField.frame.height-1, usernameTextField.frame.width, 1.0) bottomBorder.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5).CGColor usernameTextField.tintColor = UIColor.whiteColor() passwordTextField.tintColor = UIColor.whiteColor() usernameTextField.layer.addSublayer(bottomBorder) usernameTextField.delegate = self passwordTextField.delegate = self } func setUpButton() { loginButton.backgroundColor = UIColor.whiteColor() signUpButton.backgroundColor = UIColor.whiteColor() } @IBAction func signInPressed(sender: UIButton) { let usernameText = usernameTextField.text let passwordText = passwordTextField.text SVProgressHUD.show() UIApplication.sharedApplication().beginIgnoringInteractionEvents() PFUser.logInWithUsernameInBackground(usernameText, password: passwordText) { (user: PFUser?, error: NSError?) in if user != nil { self.performSegueWithIdentifier("SignInSegue", sender: nil) } else { AlertControllerHelper.displayErrorController(self, withMessage: error!.localizedDescription) } SVProgressHUD.dismiss() UIApplication.sharedApplication().endIgnoringInteractionEvents() } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == usernameTextField { passwordTextField.becomeFirstResponder() } else if textField == passwordTextField { signInPressed(loginButton) } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
DAloG/BlueCap
BlueCapKit/Extensions/StringExtensions.swift
1
799
// // StringExtensions.swift // BlueCap // // Created by Troy Stribling on 6/29/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation public extension String { public var floatValue : Float { return (self as NSString).floatValue } public func dataFromHexString() -> NSData { var bytes = [UInt8]() for i in 0..<(self.characters.count/2) { let stringBytes = self.substringWithRange(Range( start:self.startIndex.advancedBy(2*i), end:self.startIndex.advancedBy(2*i+2) )) let byte = strtol((stringBytes as NSString).UTF8String, nil, 16) bytes.append(UInt8(byte)) } return NSData(bytes:bytes, length:bytes.count) } }
mit
kosicki123/eidolon
Kiosk/Bid Fulfillment/BalancedManager.swift
1
1323
import UIKit import balanced_ios class BalancedManager: NSObject { let marketplace: String dynamic var cardName = "" dynamic var cardLastDigits = "" dynamic var cardToken = "" init(marketplace: String) { self.marketplace = marketplace } func registerCard(digits: String, month: Int, year: Int) -> RACSignal { let registeredCardSignal = RACSubject() let card = BPCard(number: digits, expirationMonth: UInt(month), expirationYear: UInt(year), optionalFields: nil) let balanced = Balanced(marketplaceURI:"/v1/marketplaces/\(marketplace)") balanced.tokenizeCard(card, onSuccess: { (dict) -> Void in if let data = dict["data"] as? [String: AnyObject] { // TODO: We don't capture names if let uri = data["uri"] as? String { self.cardToken = uri } if let last4 = data["last_four"] as? String { self.cardLastDigits = last4 } self.cardName = data["name"] as? String ?? "" registeredCardSignal.sendNext(self) } }) { (error) -> Void in registeredCardSignal.sendError(error) logger.error("Error tokenizing via balanced: \(error)") } return registeredCardSignal } }
mit
daniel-barros/TV-Calendar
TraktKit/Common/TraktTrendingShow.swift
1
625
// // TraktTrendingShow.swift // TraktKit // // Created by Maximilian Litteral on 4/13/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktTrendingShow: TraktProtocol { // Extended: Min public let watchers: Int public let show: TraktShow // Initialize public init?(json: RawJSON?) { guard let json = json, let watchers = json["watchers"] as? Int, let show = TraktShow(json: json["show"] as? RawJSON) else { return nil } self.watchers = watchers self.show = show } }
gpl-3.0
ainopara/Stage1st-Reader
Stage1st/Vendors/Gagat/Gagat.swift
1
3719
// // Gagat.swift // Gagat // // Created by Tim Andersson on 2017-02-17. // Copyright © 2017 Cocoabeans Software. All rights reserved. // import Foundation import UIKit /// A type that knows how to toggle between two alternative visual styles. public protocol GagatStyleable { /// Activates the alternative style that is currently not active. /// /// This method is called by Gagat at the start of a transition /// and at the end of a _cancelled_ transition (to revert to the /// previous style). func toggleActiveStyle() func shouldStartTransition(with direction: TransitionCoordinator.Direction) -> Bool } public struct Gagat { /// The `Configuration` struct allows clients to configure certain /// aspects of the transition. /// /// Initialize an empty instance of the struct to use the defaults. public struct Configuration { /// Controls how much the border between the new and /// previous style is deformed when panning. The larger the /// factor is, the more the border is deformed. /// Specify a factor of 0 to entirely disable the deformation. /// /// Defaults to 1.0. public let jellyFactor: Double public init(jellyFactor: Double = 1.0) { self.jellyFactor = jellyFactor } } /// Represents a configured transition and allows clients to /// access properties that can be modified after configuration. public struct TransitionHandle { private let coordinator: TransitionCoordinator fileprivate init(coordinator: TransitionCoordinator) { self.coordinator = coordinator } /// The pan gesture recognizer that Gagat uses to trigger and drive the /// transition. /// /// You may use this property to configure the minimum or maximum number /// of required touches if you don't want to use the default two-finger /// pan. You may also use it to setup dependencies between this gesture /// recognizer and any other gesture recognizers in your application. /// /// - important: You *must not* change the gesture recognizer's delegate /// or remove targets not added by the client. public var panGestureRecognizer: UIPanGestureRecognizer { return coordinator.panGestureRecognizer } } /// Configures everything that's needed by Gagat to begin handling the transition /// in the specified window. /// /// - important: You *must* keep a reference to the `TransitionHandle` /// returned by this method even if you don't intend to access /// any of its properties. /// All Gagat-related objects will be torn down when the /// handle is deallocated, and the client will need to call /// `Gagat.configure(for:with:using:)` again to re-enable /// the Gagat transition. /// /// - note: This method shouldn't be called multiple times for the same window /// unless the returned handle has been deallocated. /// /// - parameter window: The window that the user will pan in to trigger the /// transition. /// - parameter styleableObject: An object that conforms to `GagatStyleable` and /// which is responsible for toggling to the alternative style when /// the transition is triggered or cancelled. /// - parameter configuration: The configuration to use for the transition. /// /// - returns: A new instance of `TransitionHandle`. public static func configure(for window: UIWindow, with styleableObject: GagatStyleable, using configuration: Configuration = Configuration()) -> TransitionHandle { let coordinator = TransitionCoordinator(targetView: window, styleableObject: styleableObject, configuration: configuration) return TransitionHandle(coordinator: coordinator) } }
bsd-3-clause
ben-ng/swift
validation-test/compiler_crashers_fixed/25507-void.swift
1
438
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck c{p}class B<f where B:a{class a{var f=1
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/27266-swift-constraints-constraintsystem-solverec.swift
1
459
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck <T struct c<T where k:a{ struct b protocol b class x{let a=b
apache-2.0
svbeemen/Eve
Eve/Eve/CalendarClass.swift
1
4900
// // CalendarClass.swift // Eve // // Created by Sangeeta van Beemen on 23/06/15. // Copyright (c) 2015 Sangeeta van Beemen. All rights reserved. // import Foundation class CalendarClass { var currentDate: NSDate var currentCalendar: NSCalendar var calenderDates: [[CycleDate]] var selectedDates: [CycleDate] var menstruationCycle: MenstrualCycle! var firstCalendarDate: NSDate! var lastCalendarDate: NSDate! init() { self.currentDate = NSDate() self.currentCalendar = NSCalendar.currentCalendar() self.calenderDates = [[CycleDate]]() self.selectedDates = [CycleDate]() self.firstCalendarDate = self.currentDate.firstYearDate().dateBySubtractingYears(1) self.lastCalendarDate = self.currentDate.lastYearDate().dateByAddingYears(1) self.menstruationCycle = MenstrualCycle(currentDate: self.currentDate, endPredictionDate: self.lastCalendarDate) } // Calculate dates for calendar func getDates() { let startCalendarDate = CycleDate(date: self.firstCalendarDate) let endCalendarDate = CycleDate(date: self.lastCalendarDate) self.calenderDates = [[CycleDate]]() while startCalendarDate.date.isEarlierThanOrEqualTo(endCalendarDate.date) { let daysInMonth = startCalendarDate.date.daysInMonth() var datesInMonth = [CycleDate]() for _ in 0 ..< daysInMonth { let date = CycleDate(date: startCalendarDate.date) datesInMonth.append(date) startCalendarDate.date = startCalendarDate.date.dateByAddingDays(1) } self.calenderDates.append(datesInMonth) } } // Adds and deletes selected date to menstruation array. func setSelectedDate(selectedDate: CycleDate) { if self.selectedDates.contains(selectedDate) { self.selectedDates = self.selectedDates.filter( {$0 != selectedDate} ) selectedDate.type = "" } else { self.selectedDates.append(selectedDate) selectedDate.type = "menstruation" } } // Calls function to calculate cycle in menstrualCycleClass // Sets the type date of the predicted dates to the calendar dates. func setDateTypes() { let datesTypes = self.menstruationCycle.predictedCycleDates + self.menstruationCycle.pastMenstruationDates + self.menstruationCycle.pastCycleDates // reset date type for months in calenderDates { for days in months { days.type = "" } } // set date type for dates in datesTypes { for months in self.calenderDates { for calandardays in months { if currentCalendar.isDate(dates.date, inSameDayAsDate: calandardays.date) { calandardays.type = dates.type } } } } } // Retrieve selected date and set type. func getSelectedDate() { // reset date type for months in calenderDates { for days in months { days.type = "" } } // set selected date type for dates in self.selectedDates { for months in self.calenderDates { for calandardays in months { if currentCalendar.isDate(dates.date, inSameDayAsDate: calandardays.date) { calandardays.type = "menstruation" } } } } } // Remove pased dates from predicted cycle dates, add to pastPredicted dates array. func refreshPastedDates() { if self.menstruationCycle.predictedCycleDates.isEmpty { return } menstruationCycle.predictedCycleDates = menstruationCycle.sortDates(self.menstruationCycle.predictedCycleDates) for cycleDates in self.menstruationCycle.predictedCycleDates { if cycleDates.date.isEarlierThan(self.currentDate) { self.menstruationCycle.pastCycleDates.append(cycleDates) if cycleDates.type == "menstruation" { self.menstruationCycle.pastMenstruationDates.append(cycleDates) } } } SavedDataManager.sharedInstance.savePastMenstruationDates(self.menstruationCycle.pastMenstruationDates) SavedDataManager.sharedInstance.savePastCycleDates(self.menstruationCycle.pastCycleDates) } }
mit
jose-camallonga/sample-base
SampleApp/Modules/ShowItem/Detail/DetailPresenter.swift
1
1433
// // DetailPresenter.swift // SampleApp // // Created by Jose Camallonga on 26/09/2017. // Copyright © 2017 Jose Camallonga. All rights reserved. // import Foundation protocol DetailPresenterProtocol: class { var view: DetailViewProtocol? { get set } weak var wireframe: DetailWireframeProtocol? { get set } var interactor: DetailInteractorProtocol? { get set } func showItem(_ item: ListItem) func viewDidLoad() func showVideoPressed() } class DetailPresenter: DetailPresenterProtocol { var view: DetailViewProtocol? var wireframe: DetailWireframeProtocol? var interactor: DetailInteractorProtocol? var currentItem: ListItem? var detailItem: DetailItem? func viewDidLoad() { view?.showListItem(name: currentItem?.names.international ?? "", logoURL: URL(string: currentItem?.assets.coverLarge?.uri ?? "")) interactor?.getDetailItem(listItem: currentItem!) } func showItem(_ item: ListItem) { currentItem = item } func showVideoPressed() { interactor?.showVideoUri(uri: detailItem?.videos.links[0].uri ?? "https://www.youtube.com/watch?v=KKjPMD0aHaY") } } extension DetailPresenter: DetailInteractorDelegate { func itemDetail(item: DetailItemData?) { detailItem = item?.data view?.showDetailItem(name: detailItem?.players[0].id, timeRun: detailItem?.times.realtime) } }
mit
adrfer/swift
test/ClangModules/cvars_parse.swift
18
465
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s import cvars func getPI() -> Float { return PI } func testPointers() { let cp = globalConstPointer cp.abcde() // expected-error {{value of type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>') has no member 'abcde'}} let mp = globalPointer mp.abcde() // expected-error {{value of type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>') has no member 'abcde'}} }
apache-2.0
google/JacquardSDKiOS
Example/JacquardSDK/TagManager/TagManagerViewController.swift
1
6309
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 Combine import JacquardSDK import MaterialComponents import UIKit class TagManagerViewController: UIViewController { struct TagCellModel: Hashable { var tag: JacquardTag static func == (lhs: TagCellModel, rhs: TagCellModel) -> Bool { return lhs.tag.identifier == rhs.tag.identifier } func hash(into hasher: inout Hasher) { tag.identifier.hash(into: &hasher) } } private var observations = [Cancellable]() @IBOutlet private weak var tagsTableView: UITableView! // Publishes a value every time the tag connects or disconnects. private var tagPublisher: AnyPublisher<ConnectedTag, Never>? /// Use to manage data and provide cells for a table view. private var tagsDiffableDataSource: UITableViewDiffableDataSource<Int, TagCellModel>? /// Datasource model. private var connectedTagModels = [TagCellModel]() init(tagPublisher: AnyPublisher<ConnectedTag, Never>?) { self.tagPublisher = tagPublisher super.init(nibName: "TagManagerViewController", bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let addBarButtonItem = UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(addNewTag) ) navigationItem.rightBarButtonItem = addBarButtonItem // Configure table view. let nib = UINib(nibName: String(describing: ConnectedTagTableViewCell.self), bundle: nil) tagsTableView.register( nib, forCellReuseIdentifier: ConnectedTagTableViewCell.reuseIdentifier ) tagsDiffableDataSource = UITableViewDiffableDataSource<Int, TagCellModel>( tableView: tagsTableView, cellProvider: { (tagsTableView, indexPath, connectedTagCellModel) -> UITableViewCell? in guard let cell = tagsTableView.dequeueReusableCell( withIdentifier: ConnectedTagTableViewCell.reuseIdentifier, for: indexPath ) as? ConnectedTagTableViewCell else { return UITableViewCell() } cell.configure(with: connectedTagCellModel) cell.checkboxTapped = { [weak self] in guard let self = self else { return } self.updateCurrentTag(connectedTagCellModel.tag) } return cell }) tagsTableView.dataSource = tagsDiffableDataSource } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureTableDataSource() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) observations.removeAll() } } // Extension contains only UI logic not related to Jacquard SDK API's extension TagManagerViewController { func configureTableDataSource() { // We need to track the currently connected tag so that the details screen can show more // info and disconnect if desired. The prepend(nil) is because we want the table to populate // even when there are no connected tags (would be better if tagPublisher propagated nil values) tagPublisher? .map { tag -> ConnectedTag? in tag } .prepend(nil) .sink(receiveValue: { [weak self] connectedTag in guard let self = self else { return } self.configureTableDataSource(currentConnectedTag: connectedTag) }).addTo(&observations) } private func configureTableDataSource(currentConnectedTag: ConnectedTag?) { tagsTableView.isHidden = Preferences.knownTags.isEmpty connectedTagModels = Preferences.knownTags .map { // Swap in the currently connected tag so that the details screen can show more // info and disconnect if desired. if let currentConnectedTag = currentConnectedTag, $0.identifier == currentConnectedTag.identifier { return TagCellModel(tag: currentConnectedTag) } else { return TagCellModel(tag: $0) } } var snapshot = NSDiffableDataSourceSnapshot<Int, TagCellModel>() snapshot.appendSections([0]) snapshot.appendItems(connectedTagModels, toSection: 0) tagsDiffableDataSource?.apply(snapshot, animatingDifferences: false) if Preferences.knownTags.count > 0 { let indexPath = IndexPath(row: 0, section: 0) tagsTableView.selectRow(at: indexPath, animated: true, scrollPosition: .top) } } /// Initiate scanning on add new tag. @objc func addNewTag() { let scanningVC = ScanningViewController() scanningVC.shouldShowCloseButton = true let navigationController = UINavigationController(rootViewController: scanningVC) navigationController.modalPresentationStyle = .fullScreen present(navigationController, animated: true) } private func updateCurrentTag(_ tag: JacquardTag) { // Set selected tag as first tag. guard let index = Preferences.knownTags.firstIndex(where: { $0.identifier == tag.identifier }) else { return } let tag = Preferences.knownTags[index] Preferences.knownTags.remove(at: index) Preferences.knownTags.insert(tag, at: 0) NotificationCenter.default.post(name: Notification.Name("setCurrentTag"), object: nil) navigationController?.popViewController(animated: true) } } /// Handle Tableview delegate methods. extension TagManagerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let model = tagsDiffableDataSource?.itemIdentifier(for: indexPath) else { return } let tagDetailsVC = TagDetailsViewController(tagPublisher: tagPublisher, tag: model.tag) navigationController?.pushViewController(tagDetailsVC, animated: true) } }
apache-2.0
bettkd/KenyaNews
Pods/Swift-YouTube-Player/YouTubePlayer/YouTubePlayer/VideoPlayerView.swift
1
9430
// // VideoPlayerView.swift // YouTubePlayer // // Created by Giles Van Gruisen on 12/21/14. // Copyright (c) 2014 Giles Van Gruisen. All rights reserved. // import UIKit public enum YouTubePlayerState: String { case Unstarted = "-1" case Ended = "0" case Playing = "1" case Paused = "2" case Buffering = "3" case Queued = "4" } public enum YouTubePlayerEvents: String { case YouTubeIframeAPIReady = "onYouTubeIframeAPIReady" case Ready = "onReady" case StateChange = "onStateChange" case PlaybackQualityChange = "onPlaybackQualityChange" } public enum YouTubePlaybackQuality: String { case Small = "small" case Medium = "medium" case Large = "large" case HD720 = "hd720" case HD1080 = "hd1080" case HighResolution = "highres" } public protocol YouTubePlayerDelegate { func playerReady(videoPlayer: YouTubePlayerView) func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) } private extension NSURL { func queryStringComponents() -> [String: AnyObject] { var dict = [String: AnyObject]() // Check for query string if let query = self.query { // Loop through pairings (separated by &) for pair in query.componentsSeparatedByString("&") { // Pull key, val from from pair parts (separated by =) and set dict[key] = value let components = pair.componentsSeparatedByString("=") dict[components[0]] = components[1] } } return dict } } public func videoIDFromYouTubeURL(videoURL: NSURL) -> String? { return videoURL.queryStringComponents()["v"] as! String? } /** Embed and control YouTube videos */ public class YouTubePlayerView: UIView, UIWebViewDelegate { public typealias YouTubePlayerParameters = [String: AnyObject] private var webView: UIWebView! /** The readiness of the player */ private(set) public var ready = false /** The current state of the video player */ private(set) public var playerState = YouTubePlayerState.Unstarted /** The current playback quality of the video player */ private(set) public var playbackQuality = YouTubePlaybackQuality.Small /** Used to configure the player */ public var playerVars = YouTubePlayerParameters() /** Used to respond to player events */ public var delegate: YouTubePlayerDelegate? // MARK: Various methods for initialization /* public init() { super.init() self.buildWebView(playerParameters()) } */ override public init(frame: CGRect) { super.init(frame: frame) buildWebView(playerParameters()) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) buildWebView(playerParameters()) } override public func layoutSubviews() { super.layoutSubviews() // Remove web view in case it's within view hierarchy, reset frame, add as subview webView.removeFromSuperview() webView.frame = bounds addSubview(webView) } // MARK: Web view initialization private func buildWebView(parameters: [String: AnyObject]) { webView = UIWebView() webView.allowsInlineMediaPlayback = true webView.mediaPlaybackRequiresUserAction = false webView.delegate = self } // MARK: Load player public func loadVideoURL(videoURL: NSURL) { if let videoID = videoIDFromYouTubeURL(videoURL) { loadVideoID(videoID) } } public func loadVideoID(videoID: String) { var playerParams = playerParameters() playerParams["videoId"] = videoID loadWebViewWithParameters(playerParams) } public func loadPlaylistID(playlistID: String) { // No videoId necessary when listType = playlist, list = [playlist Id] playerVars["listType"] = "playlist" playerVars["list"] = playlistID loadWebViewWithParameters(playerParameters()) } // MARK: Player controls public func play() { evaluatePlayerCommand("playVideo()") } public func pause() { evaluatePlayerCommand("pauseVideo()") } public func stop() { evaluatePlayerCommand("stopVideo()") } public func clear() { evaluatePlayerCommand("clearVideo()") } public func seekTo(seconds: Float, seekAhead: Bool) { evaluatePlayerCommand("seekTo(\(seconds), \(seekAhead))") } // MARK: Playlist controls public func previousVideo() { evaluatePlayerCommand("previousVideo()") } public func nextVideo() { evaluatePlayerCommand("nextVideo()") } private func evaluatePlayerCommand(command: String) { let fullCommand = "player." + command + ";" webView.stringByEvaluatingJavaScriptFromString(fullCommand) } // MARK: Player setup private func loadWebViewWithParameters(parameters: YouTubePlayerParameters) { // Get HTML from player file in bundle let rawHTMLString = htmlStringWithFilePath(playerHTMLPath())! // Get JSON serialized parameters string let jsonParameters = serializedJSON(parameters)! // Replace %@ in rawHTMLString with jsonParameters string let htmlString = rawHTMLString.stringByReplacingOccurrencesOfString("%@", withString: jsonParameters, options: [], range: nil) // Load HTML in web view webView.loadHTMLString(htmlString, baseURL: NSURL(string: "about:blank")) } private func playerHTMLPath() -> String { return NSBundle(forClass: self.classForCoder).pathForResource("YTPlayer", ofType: "html")! } private func htmlStringWithFilePath(path: String) -> String? { // Error optional for error handling var error: NSError? // Get HTML string from path let htmlString: NSString? do { htmlString = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 htmlString = nil } // Check for error if let _ = error { print("Lookup error: no HTML file found for path, \(path)") } return htmlString! as String } // MARK: Player parameters and defaults private func playerParameters() -> YouTubePlayerParameters { return [ "height": "100%", "width": "100%", "events": playerCallbacks(), "playerVars": playerVars ] } private func playerCallbacks() -> YouTubePlayerParameters { return [ "onReady": "onReady", "onStateChange": "onStateChange", "onPlaybackQualityChange": "onPlaybackQualityChange", "onError": "onPlayerError" ] } private func serializedJSON(object: AnyObject) -> String? { // Empty error var error: NSError? // Serialize json into NSData let jsonData: NSData? do { jsonData = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted) } catch let error1 as NSError { error = error1 jsonData = nil } // Check for error and return nil if let _ = error { print("Error parsing JSON") return nil } // Success, return JSON string return NSString(data: jsonData!, encoding: NSUTF8StringEncoding) as? String } // MARK: JS Event Handling private func handleJSEvent(eventURL: NSURL) { // Grab the last component of the queryString as string let data: String? = eventURL.queryStringComponents()["data"] as? String if let host = eventURL.host { if let event = YouTubePlayerEvents(rawValue: host) { // Check event type and handle accordingly switch event { case .YouTubeIframeAPIReady: ready = true break case .Ready: delegate?.playerReady(self) break case .StateChange: if let newState = YouTubePlayerState(rawValue: data!) { playerState = newState delegate?.playerStateChanged(self, playerState: newState) } break case .PlaybackQualityChange: if let newQuality = YouTubePlaybackQuality(rawValue: data!) { playbackQuality = newQuality delegate?.playerQualityChanged(self, playbackQuality: newQuality) } break } } } } // MARK: UIWebViewDelegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL // Check if ytplayer event and, if so, pass to handleJSEvent if url!.scheme == "ytplayer" { handleJSEvent(url!) } return true } }
apache-2.0
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Core/View/SelectBoxView.swift
1
5748
// // SelectBoxView.swift // HXPHPickerExample // // Created by Slience on 2020/12/29. // Copyright © 2020 Silence. All rights reserved. // import UIKit public final class SelectBoxView: UIControl { public enum Style: Int { /// 数字 case number /// 勾勾 case tick } public var text: String = "0" { didSet { if config.style == .number { textLayer.string = text } } } public override var isSelected: Bool { didSet { if !isSelected { text = "0" } updateLayers() } } var textSize: CGSize = CGSize.zero public lazy var config: SelectBoxConfiguration = .init() lazy var backgroundLayer: CAShapeLayer = { let backgroundLayer = CAShapeLayer.init() backgroundLayer.contentsScale = UIScreen.main.scale return backgroundLayer }() lazy var textLayer: CATextLayer = { let textLayer = CATextLayer.init() textLayer.contentsScale = UIScreen.main.scale textLayer.alignmentMode = .center textLayer.isWrapped = true return textLayer }() lazy var tickLayer: CAShapeLayer = { let tickLayer = CAShapeLayer.init() tickLayer.lineJoin = .round tickLayer.contentsScale = UIScreen.main.scale return tickLayer }() public override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(backgroundLayer) layer.addSublayer(textLayer) layer.addSublayer(tickLayer) } private func backgroundPath() -> CGPath { let strokePath = UIBezierPath( roundedRect: CGRect( x: 0, y: 0, width: width, height: height ), cornerRadius: height / 2 ) return strokePath.cgPath } private func drawBackgroundLayer() { backgroundLayer.path = backgroundPath() if isSelected { backgroundLayer.fillColor = PhotoManager.isDark ? config.selectedBackgroudDarkColor.cgColor : config.selectedBackgroundColor.cgColor backgroundLayer.lineWidth = 0 }else { backgroundLayer.lineWidth = config.borderWidth backgroundLayer.fillColor = PhotoManager.isDark ? config.darkBackgroundColor.cgColor : config.backgroundColor.cgColor backgroundLayer.strokeColor = PhotoManager.isDark ? config.borderDarkColor.cgColor : config.borderColor.cgColor } } private func drawTextLayer() { if config.style != .number { textLayer.isHidden = true return } if !isSelected { textLayer.string = nil } let font = UIFont.mediumPingFang(ofSize: config.titleFontSize) var textHeight: CGFloat var textWidth: CGFloat if textSize.equalTo(CGSize.zero) { textHeight = text.height(ofFont: font, maxWidth: CGFloat(MAXFLOAT)) textWidth = text.width(ofFont: font, maxHeight: textHeight) }else { textHeight = textSize.height textWidth = textSize.width } textLayer.frame = CGRect( x: (width - textWidth) * 0.5, y: (height - textHeight) * 0.5, width: textWidth, height: textHeight ) textLayer.font = CGFont(font.fontName as CFString) textLayer.fontSize = config.titleFontSize textLayer.foregroundColor = PhotoManager.isDark ? config.titleDarkColor.cgColor : config.titleColor.cgColor } private func tickPath() -> CGPath { let tickPath = UIBezierPath.init() tickPath.move(to: CGPoint(x: scale(8), y: height * 0.5 + scale(1))) tickPath.addLine(to: CGPoint(x: width * 0.5 - scale(2), y: height - scale(8))) tickPath.addLine(to: CGPoint(x: width - scale(7), y: scale(9))) return tickPath.cgPath } private func drawTickLayer() { if config.style != .tick { tickLayer.isHidden = true return } tickLayer.isHidden = !isSelected tickLayer.path = tickPath() tickLayer.lineWidth = config.tickWidth tickLayer.strokeColor = PhotoManager.isDark ? config.tickDarkColor.cgColor : config.tickColor.cgColor tickLayer.fillColor = UIColor.clear.cgColor } public func updateLayers() { backgroundLayer.frame = bounds if config.style == .tick { tickLayer.frame = bounds } drawBackgroundLayer() drawTextLayer() drawTickLayer() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func scale(_ numerator: CGFloat) -> CGFloat { return numerator / 30 * height } public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if isUserInteractionEnabled && CGRect(x: -15, y: -15, width: width + 30, height: height + 30).contains(point) { return self } return super.hitTest(point, with: event) } public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { drawBackgroundLayer() drawTextLayer() drawTickLayer() } } } }
mit
ip3r/Cart
Cart/Currencies/Protocols/Currencies.swift
1
1462
// // Currencies.swift // Cart // // Created by Jens Meder on 12.06.17. // Copyright © 2017 Jens Meder. All rights reserved. // import Foundation internal protocol Currencies: class { var count: Int {get} var current: Currency {get} subscript(_ index: Int) -> Currency {get} func currency(with code: String) -> [Currency] } internal final class FakeCurrencies: Currencies { private let currencies: [Currency] // MARK: - Init internal convenience init() { self.init( currencies: [ FakeCurrency(), FakeCurrency() ] ) } internal required init(currencies: [Currency]) { self.currencies = currencies } // MARK: - Currencies var current: Currency { return FakeCurrency() } var count: Int { return currencies.count } subscript(_ index: Int) -> Currency { return currencies[index] } func currency(with code: String) -> [Currency] { return [] } } internal class CurrenciesWrap: Currencies { private let origin: Currencies // MARK: - Init internal init(origin: Currencies) { self.origin = origin } // MARK: - Currencies var current: Currency { return origin.current } var count: Int { return origin.count } subscript(_ index: Int) -> Currency { return origin[index] } func currency(with code: String) -> [Currency] { return origin.currency(with:code) } }
mit
fousa/trackkit
Example/Pods/AEXML/Sources/Document.swift
1
3899
/** * https://github.com/tadija/AEXML * Copyright (c) Marko Tadić 2014-2018 * Licensed under the MIT license. See LICENSE file. */ import Foundation /** This class is inherited from `AEXMLElement` and has a few addons to represent **XML Document**. XML Parsing is also done with this object. */ open class AEXMLDocument: AEXMLElement { // MARK: - Properties /// Root (the first child element) element of XML Document **(Empty element with error if not exists)**. open var root: AEXMLElement { guard let rootElement = children.first else { let errorElement = AEXMLElement(name: "Error") errorElement.error = AEXMLError.rootElementMissing return errorElement } return rootElement } public let options: AEXMLOptions // MARK: - Lifecycle /** Designated initializer - Creates and returns new XML Document object. - parameter root: Root XML element for XML Document (defaults to `nil`). - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object. */ public init(root: AEXMLElement? = nil, options: AEXMLOptions = AEXMLOptions()) { self.options = options let documentName = String(describing: AEXMLDocument.self) super.init(name: documentName) // document has no parent element parent = nil // add root element to document (if any) if let rootElement = root { _ = addChild(rootElement) } } /** Convenience initializer - used for parsing XML data (by calling `loadXMLData:` internally). - parameter xmlData: XML data to parse. - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed. */ public convenience init(xml: Data, options: AEXMLOptions = AEXMLOptions()) throws { self.init(options: options) try loadXML(xml) } /** Convenience initializer - used for parsing XML string (by calling `init(xmlData:options:)` internally). - parameter xmlString: XML string to parse. - parameter encoding: String encoding for creating `Data` from `xmlString` (defaults to `String.Encoding.utf8`) - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed. */ public convenience init(xml: String, encoding: String.Encoding = String.Encoding.utf8, options: AEXMLOptions = AEXMLOptions()) throws { guard let data = xml.data(using: encoding) else { throw AEXMLError.parsingFailed } try self.init(xml: data, options: options) } // MARK: - Parse XML /** Creates instance of `AEXMLParser` (private class which is simple wrapper around `XMLParser`) and starts parsing the given XML data. Throws error if data could not be parsed. - parameter data: XML which should be parsed. */ open func loadXML(_ data: Data) throws { children.removeAll(keepingCapacity: false) let xmlParser = AEXMLParser(document: self, data: data) try xmlParser.parse() } // MARK: - Override /// Override of `xml` property of `AEXMLElement` - it just inserts XML Document header at the beginning. open override var xml: String { var xml = "\(options.documentHeader.xmlString)\n" xml += root.xml return xml } }
mit
Lebron1992/SlackTextViewController-Swift
SlackTextViewController-Swift/SlackTextViewController-Swift/Source/SLKTextInput.swift
1
4970
// // SLKTextInput.swift // SlackTextViewController-Swift // // Created by Lebron on 16/06/2017. // Copyright © 2017 hacknocraft. All rights reserved. // import Foundation import UIKit /// Searches for any matching string prefix at the text input's caret position. When nothing found, the completion block returns nil values. public protocol SLKTextInput: UITextInput { /// Searches for any matching string prefix at the text input's caret position. When nothing found, the completion block returns nil values /// - Parameters: /// - prefixes: A set of prefixes to search for /// - completion: A completion block called whenever the text processing finishes, successfuly or not. Required. func lookForPrefixes(_ prefixes: Set<String>, completion: (String?, String?, NSRange) -> Void) /// Finds the word close to the caret's position, if any /// - Parameters: /// - range: range Returns the range of the found word /// - Returns: /// The found word func wordAtCaretRange(_ range: inout NSRange) -> String? /// - Parameters: /// - range: range The range to be used for searching the word /// - rangeInText: rangePointer Returns the range of the found word. /// - Returns: /// The found word func wordAtRange(_ range: NSRange, rangeInText: inout NSRange) -> String? } extension SLKTextInput { // MARK: - Default implementations public func lookForPrefixes(_ prefixes: Set<String>, completion: (String?, String?, NSRange) -> Void) { var wordRange = NSRange(location: 0, length: 0) guard let word = wordAtCaretRange(&wordRange), prefixes.count > 0 else { return } if !word.isEmpty { for prefix in prefixes where word.hasPrefix(prefix) { completion(prefix, word, wordRange) } } else { completion(nil, nil, NSRange(location: 0, length: 0)) } } public func wordAtCaretRange(_ range: inout NSRange) -> String? { return wordAtRange(slk_caretRange, rangeInText: &range) } @discardableResult public func wordAtRange(_ range: NSRange, rangeInText: inout NSRange) -> String? { let location = range.location if location == NSNotFound { return nil } guard let text = slk_text else { return nil } // Aborts in case minimum requieres are not fufilled if text.isEmpty || location < 0 || (range.location + range.length) > text.length { rangeInText = NSRange(location: 0, length: 0) return nil } let leftPortion = text.substring(toIndex: location) let leftComponents = leftPortion.components(separatedBy: .whitespacesAndNewlines) let rightPortion = text.substring(from: location) let rightComponents = rightPortion.components(separatedBy: .whitespacesAndNewlines) guard let rightPart = rightComponents.first, let leftWordPart = leftComponents.last else { return nil } if location > 0 { let characterBeforeCursor = text.substring(with: Range(uncheckedBounds: (location - 1, location))) if let whitespaceRange = characterBeforeCursor.rangeOfCharacter(from: .whitespaces) { let distance = characterBeforeCursor.distance(from: whitespaceRange.lowerBound, to: whitespaceRange.upperBound) if distance == 1 { // At the start of a word, just use the word behind the cursor for the current word rangeInText = NSRange(location: location, length: rightPart.length) return rightPart } } } // In the middle of a word, so combine the part of the word before the cursor, and after the cursor to get the current word rangeInText = NSRange(location: location - leftWordPart.length, length: leftWordPart.length + rightPart.length) var word: String = leftWordPart.appending(rightPart) let linebreak = "\n" // If a break is detected, return the last component of the string if word.range(of: linebreak) != nil { rangeInText = text.nsRange(of: word) if let last = word.components(separatedBy: linebreak).last { word = last } } return word } // MARK: - Private methods private var slk_text: String? { if let range = textRange(from: beginningOfDocument, to: endOfDocument) { return text(in: range) } return nil } private var slk_caretRange: NSRange { if let selectedRange = selectedTextRange { let location = offset(from: beginningOfDocument, to: selectedRange.start) let length = offset(from: selectedRange.start, to: selectedRange.end) return NSRange(location: location, length: length) } return NSRange(location: 0, length: 0) } }
mit
paulsamuels/xcunique
spec/fixtures/TestProject/TestProjectUITests/TestProjectUITests.swift
1
1261
// // TestProjectUITests.swift // TestProjectUITests // // Created by Paul Samuels on 18/12/2015. // Copyright © 2015 Paul Samuels. All rights reserved. // import XCTest class TestProjectUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
tkremenek/swift
validation-test/compiler_crashers_2_fixed/0180-rdar45557325.swift
9
319
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -verify // REQUIRES: objc_interop import Foundation class MyClass: NSObject { func f() { let url = URL(url) // expected-error{{use of local variable 'url' before its declaration}} // expected-note@-1 {{'url' declared here}} } }
apache-2.0
xwu/swift
test/Constraints/bridging.swift
1
19299
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a type from another module. We only allow this for a // few specific types, like String. extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterSequence.Iterator { let result: LazyFilterSequence.Iterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { func hash(into hasher: inout Hasher) {} func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' expected to be an instance of a class or class-constrained type}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{34-34= as! [NotBridgedStruct]}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{35-37=as!}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // There is a note attached to a requirement `requirement from conditional conformance of 'Dictionary<Int, NotEquatable>' to 'Equatable'` return d == d // expected-error{{operator function '==' requires that 'NotEquatable' conform to 'Equatable'}} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 _ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}} var inferDouble2 = 1 / 3 / 3.0 let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'}} // expected-note@-2 {{did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error@-1 {{generic parameter 'K' could not be inferred}} // expected-error@-2 {{generic parameter 'V' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{7-7=(}} {{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{3-3=(}} {{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Int'}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note@-1{{overloads for '+'}} var v73 = true + [] // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Array<Bool>'}} var v75 = true + "str" // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'String'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{19-19=(}} {{50-50=) as String}} // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'NSString'}} {{50-50= as NSString}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{20-20=(}} {{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // Make sure more complicated cast has correct parenthesization func castMoreComplicated(anInt: Int?) { let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}} } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{value of type 'T' expected to be an instance of a class or class-constrained type in assignment}} z = b z = c // expected-error{{value of type 'Any' expected to be an instance of a class or class-constrained type in assignment}} expected-note {{cast 'Any' to 'AnyObject'}} {{8-8= as AnyObject}} z = d // expected-error{{value of type 'KnownUnbridged' expected to be an instance of a class or class-constrained type in assignment}} z = e z = f z = g z = h // expected-error{{value of type 'String' expected to be an instance of a class or class-constrained type in assignment}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y } // Array defaulting and bridging type checking error per rdar://problem/54274245 func rdar54274245(_ arr: [Any]?) { _ = (arr ?? []) as [NSObject] // expected-warning {{coercion from '[Any]' to '[NSObject]' may fail; use 'as?' or 'as!' instead}} } // rdar://problem/60501780 - failed to infer NSString as a value type of a dictionary func rdar60501780() { func foo(_: [String: NSObject]) {} func bar(_ v: String) { foo(["": "", "": v as NSString]) } } // SR-15161 func SR15161_as(e: Error?) { let _ = e as? NSError // Ok } func SR15161_is(e: Error?) { _ = e is NSError // expected-warning{{checking a value with optional type 'Error?' against dynamic type 'NSError' succeeds whenever the value is non-nil; did you mean to use '!= nil'?}} } func SR15161_as_1(e: Error?) { let _ = e as! NSError // expected-warning{{forced cast from 'Error?' to 'NSError' only unwraps and bridges; did you mean to use '!' with 'as'?}} }
apache-2.0
radex/swift-compiler-crashes
crashes/02257-swift-any-from-nsmutablearray.swift
11
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/mattdaw (Matt Daw) // http://www.openradar.me/19346816 (duplicate) import Foundation var a: NSMutableArray = [] var b: Any = a[0]
mit
Finb/V2ex-Swift
Model/API/TopicListApi.swift
1
1330
// // TopicListApi.swift // V2ex-Swift // // Created by huangfeng on 2018/9/17. // Copyright © 2018 Fin. All rights reserved. // import UIKit enum TopicListApi { //获取首页列表 case topicList(tab: String?, page: Int) //获取我的收藏帖子列表 case favoriteList(page: Int) //获取节点主题列表 case nodeTopicList(nodeName: String, page:Int) } extension TopicListApi: V2EXTargetType { var parameters: [String : Any]? { switch self { case let .topicList(tab, page): if tab == "all" && page > 0 { //只有全部分类能翻页 return ["p": page] } return ["tab": tab ?? "all"] case let .favoriteList(page): return ["p": page] case let .nodeTopicList(_, page): return ["p": page] // default: // return nil } } var path: String { switch self { case let .topicList(tab, page): if tab == "all" && page > 0 { return "/recent" } return "/" case .favoriteList: return "/my/topics" case let .nodeTopicList(nodeName, _): return "/go/\(nodeName)" // default: // return "" } } }
mit
radex/swift-compiler-crashes
crashes-duplicates/21002-no-stacktrace.swift
11
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { var d = { println( var { class case ,
mit
ViterbiDevelopment/PhotoWithSwift
PhotoKit/PhotoKit/ViewController.swift
1
6050
// // ViewController.swift // PhotoKit // // Created by 掌上先机 on 16/12/3. // Copyright © 2016年 wangchao. All rights reserved. // import UIKit import Photos class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView:UITableView! var SystemUserPhotoList:PHFetchResult<PHAssetCollection>! var UserPhotoList:PHFetchResult<PHCollection>! var allPhotoCollection:Array<PHAssetCollection>! var photoManager = PHCachingImageManager() var allPhotoFirstImage:Array<UIImage>! override func viewWillAppear(_ animated: Bool) { PHPhotoLibrary.shared().register(self) } override func viewDidLoad() { super.viewDidLoad() tableView = UITableView.init(frame: view.frame, style: .plain) tableView.tableFooterView = UIView.init() tableView.delegate = self tableView.dataSource = self tableView.register(thumbnailSizeCell.classForCoder(), forCellReuseIdentifier: "photoCell") view.addSubview(tableView) //这里是所有的智能相册 系统给创建的 SystemUserPhotoList = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) // 这里是所有自己创建的相册 UserPhotoList = PHCollectionList.fetchTopLevelUserCollections(with: nil) photoManager.allowsCachingHighQualityImages = false fetPhotoAndReloadTableView() } func fetPhotoAndReloadTableView() { if allPhotoCollection != nil { allPhotoCollection.removeAll() } else{ allPhotoCollection = [] } for i in 0..<SystemUserPhotoList.count{ let asset = SystemUserPhotoList.object(at: i) allPhotoCollection.append(asset) } for i in 0..<UserPhotoList.count{ let asset = UserPhotoList.object(at: i) as! PHAssetCollection allPhotoCollection.append(asset) } if allPhotoFirstImage != nil{ allPhotoFirstImage.removeAll() } else{ allPhotoFirstImage = [] } for i in 0..<allPhotoCollection.count{ let object = allPhotoCollection[i] let fetchResult = PHAsset.fetchAssets(in: object, options: nil) if fetchResult.count > 0{ // print("block j=======\(i)") //PHImageRequestOptions 设置同步执行 let options = PHImageRequestOptions() options.isSynchronous = true photoManager.requestImage(for: fetchResult.firstObject!, targetSize: CGSize(width: 44, height: 44), contentMode: .default, options: options, resultHandler: { (image, _) in self.allPhotoFirstImage.append(image!) // print("block i=======\(i)") }) }else{ let def = UIImage.init(named: "user_default") allPhotoFirstImage.append(def!) // print("i=======\(i)") } } tableView.reloadData() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "photoCell", for: indexPath) as! thumbnailSizeCell if allPhotoFirstImage.count>0 { let object = allPhotoCollection[indexPath.row] cell.imageName = object.localizedTitle cell.thumbnailSizeImage = allPhotoFirstImage[indexPath.row] } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let browPhoto = BrowsAllViewController() let object = allPhotoCollection[indexPath.row] browPhoto.fetchResult = PHAsset.fetchAssets(in: object, options: nil) browPhoto.PHManager = photoManager navigationController?.pushViewController(browPhoto, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allPhotoFirstImage.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } deinit{ PHPhotoLibrary.shared().unregisterChangeObserver(self) } } extension ViewController:PHPhotoLibraryChangeObserver{ func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.sync { if changeInstance.changeDetails(for: SystemUserPhotoList) != nil { let changes = changeInstance.changeDetails(for: SystemUserPhotoList) SystemUserPhotoList = changes?.fetchResultAfterChanges } if changeInstance.changeDetails(for: UserPhotoList) != nil{ let changes = changeInstance.changeDetails(for: UserPhotoList) UserPhotoList = changes?.fetchResultAfterChanges } fetPhotoAndReloadTableView() } } }
apache-2.0
glbuyer/GbKit
GbKit/Models/GBBuyersWithMap.swift
1
444
// // GBBuyersWithMap.swift // GbKit // // Created by Ye Gu on 1/9/17. // Copyright © 2017 glbuyer. All rights reserved. // import Foundation import ObjectMapper class GBBuyersWithMap:GBBaseModel { //买手信息 var buyers = [GBBuyer]() //地图信息 var mapInfo = GBMap() // Mappable override func mapping(map: Map) { super.mapping(map: map) } }
mit
pwoosam/Surf-Map
Surf Map/Helpers.swift
1
1391
import Foundation import UIKit extension UIImage { func resizedImage(newSize: CGSize) -> UIImage { // Created by samwize on 6/1/16. // http://samwize.com/2016/06/01/resize-uiimage-in-swift/ // Copyright © 2016 samwize. All rights reserved. guard self.size != newSize else { return self } UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0); self.draw(in: CGRect(origin: CGPoint.zero, size: newSize)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } } extension String { func image() -> UIImage { // Created by appzYourLife on 8/6/16. // http://stackoverflow.com/questions/38809425/convert-apple-emoji-string-to-uiimage // Copyright © 2016 appzYourLife. All rights reserved. let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.clear.set() let rect = CGRect(origin: CGPoint.zero, size: size) UIRectFill(CGRect(origin: CGPoint.zero, size: size)) (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
johnno1962e/swift-corelibs-foundation
Foundation/NSNotification.swift
2
7678
// 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 // open class NSNotification: NSObject, NSCopying, NSCoding { public struct Name : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(lhs: Name, rhs: Name) -> Bool { return lhs.rawValue == rhs.rawValue } } private(set) open var name: Name private(set) open var object: Any? private(set) open var userInfo: [AnyHashable : Any]? public convenience override init() { /* do not invoke; not a valid initializer for this class */ fatalError() } public init(name: Name, object: Any?, userInfo: [AnyHashable : Any]? = nil) { self.name = name self.object = object self.userInfo = userInfo } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let name = aDecoder.decodeObject(of: NSString.self, forKey:"NS.name") else { return nil } let object = aDecoder.decodeObject(forKey: "NS.object") // let userInfo = aDecoder.decodeObject(of: NSDictionary.self, forKey: "NS.userinfo") self.init(name: Name(rawValue: String._unconditionallyBridgeFromObjectiveC(name)), object: object as! NSObject, userInfo: nil) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.name.rawValue._bridgeToObjectiveC(), forKey:"NS.name") aCoder.encode(self.object, forKey:"NS.object") aCoder.encode(self.userInfo?._bridgeToObjectiveC(), forKey:"NS.userinfo") } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open override var description: String { var str = "\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque()) {" str += "name = \(self.name.rawValue)" if let object = self.object { str += "; object = \(object)" } if let userInfo = self.userInfo { str += "; userInfo = \(userInfo)" } str += "}" return str } } private class NSNotificationReceiver : NSObject { fileprivate weak var object: NSObject? fileprivate var name: Notification.Name? fileprivate var block: ((Notification) -> Void)? fileprivate var sender: AnyObject? fileprivate var queue: OperationQueue? } extension Sequence where Iterator.Element : NSNotificationReceiver { /// Returns collection of `NSNotificationReceiver`. /// /// Will return: /// - elements that property `object` is not equal to `observerToFilter` /// - elements that property `name` is not equal to parameter `name` if specified. /// - elements that property `sender` is not equal to parameter `object` if specified. /// fileprivate func filterOutObserver(_ observerToFilter: AnyObject, name:Notification.Name? = nil, object: Any? = nil) -> [Iterator.Element] { return self.filter { observer in let differentObserver = observer.object !== observerToFilter let nameSpecified = name != nil let differentName = observer.name != name let objectSpecified = object != nil let differentSender = observer.sender !== _SwiftValue.store(object) return differentObserver || (nameSpecified && differentName) || (objectSpecified && differentSender) } } /// Returns collection of `NSNotificationReceiver`. /// /// Will return: /// - elements that property `sender` is `nil` or equals specified parameter `sender`. /// - elements that property `name` is `nil` or equals specified parameter `name`. /// fileprivate func observersMatchingName(_ name:Notification.Name? = nil, sender: Any? = nil) -> [Iterator.Element] { return self.filter { observer in let emptyName = observer.name == nil let sameName = observer.name == name let emptySender = observer.sender == nil let sameSender = observer.sender === _SwiftValue.store(sender) return (emptySender || sameSender) && (emptyName || sameName) } } } private let _defaultCenter: NotificationCenter = NotificationCenter() open class NotificationCenter: NSObject { private var _observers: [NSNotificationReceiver] private let _observersLock = NSLock() public required override init() { _observers = [NSNotificationReceiver]() } open class var `default`: NotificationCenter { return _defaultCenter } open func post(_ notification: Notification) { let sendTo = _observersLock.synchronized({ return _observers.observersMatchingName(notification.name, sender: notification.object) }) for observer in sendTo { guard let block = observer.block else { continue } if let queue = observer.queue, queue != OperationQueue.current { queue.addOperation { block(notification) } queue.waitUntilAllOperationsAreFinished() } else { block(notification) } } } open func post(name aName: Notification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable : Any]? = nil) { let notification = Notification(name: aName, object: anObject, userInfo: aUserInfo) post(notification) } open func removeObserver(_ observer: Any) { removeObserver(observer, name: nil, object: nil) } open func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object: Any?) { guard let observer = observer as? NSObject else { return } _observersLock.synchronized({ self._observers = _observers.filterOutObserver(observer, name: aName, object: object) }) } @available(*,obsoleted:4.0,renamed:"addObserver(forName:object:queue:using:)") open func addObserver(forName name: Notification.Name?, object obj: Any?, queue: OperationQueue?, usingBlock block: @escaping (Notification) -> Void) -> NSObjectProtocol { return addObserver(forName: name, object: obj, queue: queue, using: block) } open func addObserver(forName name: Notification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) -> NSObjectProtocol { let object = NSObject() let newObserver = NSNotificationReceiver() newObserver.object = object newObserver.name = name newObserver.block = block newObserver.sender = _SwiftValue.store(obj) newObserver.queue = queue _observersLock.synchronized({ _observers.append(newObserver) }) return object } }
apache-2.0
CapsLock-Studio/CHCubicBezier
Tests/CHCubicBezierTests/CHCubicBezierTests.swift
1
2933
// // CHCubicBezierTests.swift // CHCubicBezierTests // // Created by Calvin on 6/23/16. // Copyright © 2016 CapsLock. All rights reserved. // import XCTest @testable import CHCubicBezier class CHCubicBezierTests: XCTestCase { func testCubicBezier() { let cubicBezier = CubicBezier(mX1: 0, mY1: 0, mX2: 1, mY2: 0.5) XCTAssertEqual(cubicBezier.easing(0.0), 0.0) XCTAssertEqual(cubicBezier.easing(0.5), 0.3125, "Value: \(cubicBezier.easing(0.5)) should equals to 0.3125") XCTAssertEqual(cubicBezier.easing(1.0), 1.0) } func testCubicBezierEasingEase() { let cubicBezierEasingEase = CubicBezier(easing: CubicBezier.Easing.ease) XCTAssertEqual(cubicBezierEasingEase.easing(0.0), 0.0) XCTAssertEqual(cubicBezierEasingEase.easing(0.5), 0.40542312526365115) XCTAssertEqual(cubicBezierEasingEase.easing(0.6), 0.52220528235001173) XCTAssertEqual(cubicBezierEasingEase.easing(0.7), 0.640774293957621) XCTAssertEqual(cubicBezierEasingEase.easing(1.0), 1.0) } func testCubicBezierEasingEaseIn() { let cubicBezierEasingEaseIn = CubicBezier(easing: CubicBezier.Easing.easeIn) XCTAssertEqual(cubicBezierEasingEaseIn.easing(0.0), 0.0) XCTAssertEqual(cubicBezierEasingEaseIn.easing(0.5), 0.3153567342653617) XCTAssertEqual(cubicBezierEasingEaseIn.easing(0.6), 0.42911907698767621) XCTAssertEqual(cubicBezierEasingEaseIn.easing(0.7), 0.554811856916553) XCTAssertEqual(cubicBezierEasingEaseIn.easing(1.0), 1.0) } func testCubicBezierEasingEaseOut() { let cubicBezierEasingEaseOut = CubicBezier(easing: CubicBezier.Easing.easeOut) XCTAssertEqual(cubicBezierEasingEaseOut.easing(0.0), 0.0) XCTAssertEqual(cubicBezierEasingEaseOut.easing(0.5), 0.68464326573463841) XCTAssertEqual(cubicBezierEasingEaseOut.easing(0.6), 0.78513906125636046) XCTAssertEqual(cubicBezierEasingEaseOut.easing(0.7), 0.870423239254529) XCTAssertEqual(cubicBezierEasingEaseOut.easing(1.0), 1.0) } func testCubicBezierEasingEaseInOut() { let cubicBezierEasingEaseInOut = CubicBezier(easing: CubicBezier.Easing.easeInOut) XCTAssertEqual(cubicBezierEasingEaseInOut.easing(0.0), 0.0) XCTAssertEqual(cubicBezierEasingEaseInOut.easing(0.5), 0.5) XCTAssertEqual(cubicBezierEasingEaseInOut.easing(0.6), 0.668116153265794) XCTAssertEqual(cubicBezierEasingEaseInOut.easing(0.7), 0.81260430454206756) XCTAssertEqual(cubicBezierEasingEaseInOut.easing(1.0), 1.0) } func testCubicBezierEasingEaseLinear() { let cubicBezierEasingLinear = CubicBezier(easing: CubicBezier.Easing.linear) XCTAssertEqual(cubicBezierEasingLinear.easing(0.0), 0.0) XCTAssertEqual(cubicBezierEasingLinear.easing(0.5), 0.5) XCTAssertEqual(cubicBezierEasingLinear.easing(1.0), 1.0) } }
mit
CodaFi/Algebra
Algebra/Monoid.swift
2
2649
// // Monoid.swift // Algebra // // Created by Robert Widmann on 11/22/14. // Copyright (c) 2014 TypeLift. All rights reserved. // /// Monoids are semigroups with some identity element. If we call that element 'e', the following /// holds for all 'a' and 'b' in the Monoid's set: /// /// e <> a == a <> e == a /// /// A monoid is said to be "Additive" if that identity is some zero (as in the case of addition over /// the integers). A monoid is said to be "Multiplicative" if that identity is some one (as in the /// case of multiplication over the integers). While either one makes sense when referring to /// Monoids, given the choice, we default to Additive in this library. /// Semigroups with a zero identity. public protocol Additive : Semigroup { static var zero : Self { get } } /// Semigroups with a one identity. public protocol Multiplicative : Semigroup { static var one : Self { get } } extension Bool : Additive { public static var zero : Bool { return false } } extension UInt : Additive { public static var zero : UInt { return 0 } } extension UInt8 : Additive { public static var zero : UInt8 { return 0 } } extension UInt16 : Additive { public static var zero : UInt16 { return 0 } } extension UInt32 : Additive { public static var zero : UInt32 { return 0 } } extension UInt64 : Additive { public static var zero : UInt64 { return 0 } } extension Int : Additive { public static var zero : Int { return 0 } } extension Int8 : Additive { public static var zero : Int8 { return 0 } } extension Int16 : Additive { public static var zero : Int16 { return 0 } } extension Int32 : Additive { public static var zero : Int32 { return 0 } } extension Int64 : Additive { public static var zero : Int64 { return 0 } } extension Bool : Multiplicative { public static var one : Bool { return true } } extension UInt : Multiplicative { public static var one : UInt { return 1 } } extension UInt8 : Multiplicative { public static var one : UInt8 { return 1 } } extension UInt16 : Multiplicative { public static var one : UInt16 { return 1 } } extension UInt32 : Multiplicative { public static var one : UInt32 { return 1 } } extension UInt64 : Multiplicative { public static var one : UInt64 { return 1 } } extension Int : Multiplicative { public static var one : Int { return 1 } } extension Int8 : Multiplicative { public static var one : Int8 { return 1 } } extension Int16 : Multiplicative { public static var one : Int16 { return 1 } } extension Int32 : Multiplicative { public static var one : Int32 { return 1 } } extension Int64 : Multiplicative { public static var one : Int64 { return 1 } }
mit
salonhelps/salon-customer-ios
Customer/ui/RegisterVerificationViewController.swift
1
263
// // RegisterVerificationViewController.swift // Customer // // Created by Thanh Truong on 2/10/17. // Copyright © 2017 SalonHelps. All rights reserved. // import Foundation import UIKit class RegisterVerificationViewController: UIViewController { }
mit
jimmyaat10/AATTools
AATTools/Tools/Extensions/String+Extra.swift
1
39017
// // String+Extra.swift // AATTools // // Created by Albert Arroyo on 18/11/16. // Copyright © 2016 AlbertArroyo. All rights reserved. // /** * This Extension has different MARK sections * Add/Modify accordingly to mantain 'some order' :) * If you add/modify some method/property, please add a Test. @see StringTest.swift */ import UIKit public extension String { // MARK: Computed properties /// Convenience property, Int for the number of characters of self public var length: Int { return self.characters.count } /// Convenience property, Array of the individual substrings composing self public var chars: [String] { return Array(self.characters).map({String($0)}) } /// Convenience property, Set<String> of the unique characters in self public var charSet: Set<String> { return Set(self.characters.map{String($0)}) } /// Convenience property, String with first character of self public var firstCharacter: String? { return self.chars.first } /// Convenience property, String with last character of self public var lastCharacter: String? { return self.chars.last } /// Convenience property, Bool to know if the string is empty (has characters) public var isEmpty: Bool { return self.chars.isEmpty } /// Convenience property, Bool to know if the field is empty (has characters) public var isEmptyField: Bool { if self.isEmpty { return true } return self.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty } /// Computed property that returns a new string made by replacing /// all HTML character entity references with the corresponding character var stringByDecodingHTMLEntities: String { let x = decodeHTMLEntities() return x.decodedString } /// Convenience property, String with base64 representation public var base64: String { let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue) let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } /// Convenience property, count of words public var countofWords: Int { let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options()) return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0 } /// Convenience property, count of paragraphs public var countofParagraphs: Int { let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options()) let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1 } /// Convenience property, extracts URLS from self and return [URL] public var extractURLs: [URL] { var urls: [URL] = [] let detector: NSDataDetector? do { detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } catch _ as NSError { detector = nil } let text = self if let detector = detector { detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let result = result, let url = result.url { urls.append(url) } }) } return urls } /// Convenience property, converts html to NSAttributedString var html2AttStr: NSAttributedString? { guard let data = data(using: .utf8) else { return nil } do { return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch let error as NSError { print(error.code) return nil } } /// Convenience property, returns localized string public var localized: String? { return self.localized() } /// Convenience property, returns pathExtension from string url public var pathExtension: String? { return NSURL(fileURLWithPath: self).pathExtension } /// Convenience property, returns lastPathComponent from string url public var lastPathComponent: String? { return NSURL(fileURLWithPath: self).lastPathComponent } /// Convenience property, converts self to NSString public var toNSString: NSString { get { return self as NSString } } } // MARK: String manipulation / util methods public extension String { /// Method to remove the first character of self /// - Returns: string with first character removed public func removedFirstChar() -> String { return self.substring(from: self.index(after: self.startIndex)) } /// Method to remove the last character of self /// - Returns: string with last character removed public func removedLastChar() -> String { return self.substring(to: self.index(before: self.endIndex)) } /// Method to remove whitespaces from the start and end of self /// - Returns: string with no whitespaces public func trimmed() -> String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Method to reverse self /// - Returns: string reversed public func reversed() -> String { return String(self.characters.reversed()) } /// Method to replace `t` parameter with string `s` parameter /// - Parameters: /// - target: The target to replace /// - withString: The string to replace /// - Returns: string replaced func replaced(target t: String, withString s: String) -> String { return self.replacingOccurrences(of: t, with: s, options: .literal, range: nil) } /// Method to split string using a separator string `s` parameter /// - Parameters: /// - separator: The separator string /// - Returns: [String] public func splitted(separator s: String) -> [String] { return self.components(separatedBy: s).filter { !$0.trimmed().isEmpty } } /// Method to split string using a separator set `characters` parameter with delimiters /// - Parameters: /// - separator: The separator CharacterSet /// - Returns: [String] public func splitted(separator characters: CharacterSet) -> [String] { return self.components(separatedBy: characters).filter { !$0.trimmed().isEmpty } } /// Method to count number of instances of the `substring` parameter inside self /// - Parameters: /// - substring: The substring to count /// - Returns: Int with number of ocurrences public func count(substring s: String) -> Int { return components(separatedBy: s).count - 1 } /// Method to uppercase the first letter /// - Returns: string with first letter capitalized func uppercasedFirstLetter() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).uppercased()) return result } /// Method to uppercases first 'count' characters of String /// - Parameters: /// - firstNumberCharacters: the first count characters /// - Returns: String modified public func uppercasedPrefix(firstNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) return result } /// Method to uppercases last 'count' characters of self /// - Parameters: /// - lastNumberCharacters: the last count characters /// - Returns: String modified public func uppercasedSuffix(lastNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) return result } /// Method to uppercases string in range 'range' /// - Parameters: /// - range: CountableRange<Int> to uppercase /// - Returns: String modified public func uppercased(range r: CountableRange<Int>) -> String { let from = max(r.lowerBound, 0), to = min(r.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased()) return result } /// Method to lowercase the first letter /// - Returns: string with first letter lowercased public func lowercasedFirstLetter() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) return result } /// Method to lowercase first 'count' characters of String /// - Parameters: /// - firstNumberCharacters: the first count characters /// - Returns: String modified public func lowercasedPrefix(firstNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased()) return result } /// Method to lowercase last 'count' characters of self /// - Parameters: /// - lastNumberCharacters: the last count characters /// - Returns: String modified public func lowercasedSuffix(lastNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) return result } /// Method to lowercase string in range 'range' /// - Parameters: /// - range: CountableRange<Int> to lowercase /// - Returns: String modified public func lowercased(range r: CountableRange<Int>) -> String { let from = max(r.lowerBound, 0), to = min(r.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased()) return result } /// Method to get the first index of the occurency of the character in self /// - Parameters: /// - character: Character to search /// - Returns: Int? with the position public func getIndexOf(character char: Character) -> Int? { for (index, c) in characters.enumerated() { if c == char { return index } } return nil } /// Method to get the height of rendered self /// - Parameters: /// - maxWidth: CGFloat /// - font: UIFont /// - lineBreakMode: NSLineBreakMode /// - Returns: CGFloat func height(maxWidth width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat { var attrib: [String: AnyObject] = [NSFontAttributeName: font] if lineBreakMode != nil { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode! attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName) } let size = CGSize(width: width, height: CGFloat(DBL_MAX)) return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height) } /// Method to copy string to pasteboard public func addToPasteboard() { let pasteboard = UIPasteboard.general pasteboard.string = self } } // MARK: String manipulation (mutating methods) // TODO: add some mutating functions public extension String { } // MARK: Wrapper for Index (String access) public extension String { /// Wrapper for index with startIndex offsetBy `from` parameter /// - Parameters: /// - from: Int /// - Returns: Index func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } /// Wrapper substring `from` parameter /// - Parameters: /// - from: Int /// - Returns: String func substring(from: Int) -> String { let fromIndex = index(from: from) return substring(from: fromIndex) } /// Wrapper substring `to` parameter /// - Parameters: /// - to: Int /// - Returns: String func substring(to: Int) -> String { let toIndex = index(from: to) return substring(to: toIndex) } /// Wrapper substring with range /// - Parameters: /// - with: Range<Int> /// - Returns: String func substring(with r: Range<Int>) -> String { let startIndex = index(from: r.lowerBound) let endIndex = index(from: r.upperBound) return substring(with: startIndex..<endIndex) } } // MARK: Subscript public extension String { /// Method to cut string from `integerIndex` parameter to the end /// - Parameters: /// - integerIndex: Int /// - Returns: Character public subscript(integerIndex: Int) -> Character { let index = characters.index(startIndex, offsetBy: integerIndex) return self[index] } /// Method to cut string from `integerRange` parameter /// - Parameters: /// - integerRange: Range<Int> /// - Returns: String public subscript(integerRange: Range<Int>) -> String { let start = characters.index(startIndex, offsetBy: integerRange.lowerBound) let end = characters.index(startIndex, offsetBy: integerRange.upperBound) return self[start..<end] } /// Method to cut string from `integerClosedRange` parameter /// - Parameters: /// - integerClosedRange: ClosedRange<Int> /// - Returns: String public subscript(integerClosedRange: ClosedRange<Int>) -> String { return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)] } } // MARK: Localization Methods public extension String { /// Method to localize self. /// Adding a bundle parameter with default value provide the possibility to test the method /// mocking the correct bundle /// - Parameters: /// - bundle: Bundle, by default Bundle.main /// - Returns: Localized string public func localized(bundle localizationBundle : Bundle = Bundle.main) -> String { return NSLocalizedString(self, bundle: localizationBundle, comment: "") } } // MARK: URL Methods public extension String { /// Method to encode the self string url /// - Returns: URL? with encoded URL public func encodeURL() -> URL? { if let originURL = URL(string: self) { return originURL } else { if let url = URL(string: self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!) { return url } else { return nil } } } /// Method to percent escapes values to be added to a URL query as specified in RFC 3986 /// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~". /// http://www.ietf.org/rfc/rfc3986.txt /// - Returns: String? with percent-escaped string func addedPercentToEncodedForUrl() -> String? { let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) } } // MARK: Range / NSRange public extension String { /// Method to return NSRange from `range` parameter /// - Parameters: /// - from: Range<String.Index> /// - Returns: NSRange func nsRange(from range: Range<String.Index>) -> NSRange { let from = range.lowerBound.samePosition(in: utf16) let to = range.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to)) } /// Method to return Range from `nsRange` parameter /// - Parameters: /// - from: NSRange /// - Returns: Range? func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } } // MARK: String satisfying certain conditions public extension String { /// Method to know if self is an email /// - Returns: Bool with condition public func isEmail() -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } /// Method to know if self is numeric /// - Returns: Bool with condition public func isNumber() -> Bool { let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) return (range == nil) } /// Method to know if self contains given sensitive `s` parameter /// - Parameters: /// - string: String to search /// - Returns: Bool with condition public func containsSensitive(string s: String) -> Bool { return self.range(of: s) != nil } /// Method to know if self contains given not sensitive `s` parameter /// - Parameters: /// - string: String to search /// - Returns: Bool with condition public func containsNotSensitive(string s: String) -> Bool { return self.lowercased().range(of: s) != nil } /// Method to find matches of regular expression in string /// - Parameters: /// - regex: String with regex /// - Returns: [String] with matches public func matchesForRegexInText(regex reg: String!) -> [String] { let regex = try? NSRegularExpression(pattern: reg, options: []) let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? [] return results.map { self.substring(with: self.range(from: $0.range)!) } } } // MARK: Tracting Numbers / Conversions / Utils for Banking Apps public extension String { /// More efficient not to create a number formatter every time if not modify properties static let numberFormatterInstance = NumberFormatter() /// Method to format a string to double /// - Returns: Double? public func toDouble() -> Double? { if let num = String.numberFormatterInstance.number(from: self) { return num.doubleValue } else { return nil } } /// Method to format a string to int /// - Returns: Int? public func toInt() -> Int? { if let num = String.numberFormatterInstance.number(from: self) { return num.intValue } else { return nil } } /// Method to format a string to float /// - Returns: Float? public func toFloat() -> Float? { if let num = String.numberFormatterInstance.number(from: self) { return num.floatValue } else { return nil } } /// Method to format a string to bool /// - Returns: Bool? public func toBool() -> Bool? { let trimmedString = trimmed().lowercased() if trimmedString == "true" || trimmedString == "false" { return (trimmedString as NSString).boolValue } return nil } /// Method to format a string to double with given `d` parameter /// - Parameters: /// - decimals: Int /// - Returns: String? public func formatNumber(decimals d: Int) -> String? { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.maximumFractionDigits = d guard let nDouble = self.toDouble() else { return nil } return numberFormatter.string(from: NSNumber(value: nDouble)) } /// Method to remove white spaces /// - Returns: String public func removedWitheSpaces() -> String { return self.replaced(target: " ", withString: "") } /// Method to format a string to an account number /// Verifications are not in this scope /// - Returns: String formatted func formattedAccountNumber() -> String { if self.length > 19 { let r1 : Range<Int> = 0..<4 let part1 = self.substring(with: r1) let r2 : Range<Int> = 4..<8 let part2 = self.substring(with: r2) let r3 : Range<Int> = 8..<10 let part3 = self.substring(with: r3) let r4 : Range<Int> = 10..<20 let part4 = self.substring(with: r4) return "\(part1)-\(part2)-\(part3)-\(part4)" } return self } /// Method to format a string to an iban number /// Verifications are not in this scope /// - Returns: String formatted func formattedIbanNumber() -> String { if self.length > 23 { let r1 : Range<Int> = 0..<4 let part1 = self.substring(with: r1) let r2 : Range<Int> = 4..<8 let part2 = self.substring(with: r2) let r3 : Range<Int> = 8..<12 let part3 = self.substring(with: r3) let r4 : Range<Int> = 12..<16 let part4 = self.substring(with: r4) let r5 : Range<Int> = 16..<20 let part5 = self.substring(with: r5) let r6 : Range<Int> = 20..<24 let part6 = self.substring(with: r6) return "\(part1) \(part2) \(part3) \(part4) \(part5) \(part6)" } return self } /// Method to remove trailing zeros to a given fraction digits `d` parameter /// Verifications are not in this scope /// - Parameters: /// - decimals: Int /// - Returns: String formatted func removedTrailingZeros(decimals d: Int) -> String { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = d numberFormatter.minimumFractionDigits = 0 guard let strRemovedTrailing = numberFormatter.string(from: NSNumber(value: self.toDouble()!)) else { return self } if self.hasPrefix("0") { return "0\(strRemovedTrailing)" } return strRemovedTrailing } } // MARK: NSAttributedString public extension String { /// Method to bold self /// - Returns: NSAttributedString public func bold() -> NSAttributedString { let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) return boldString } /// Method to underline self /// - Returns: NSAttributedString public func underline() -> NSAttributedString { let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) return underlineString } /// Method to italic self /// - Returns: NSAttributedString public func italic() -> NSAttributedString { let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) return italicString } /// Method to color self /// - Parameters: /// - _ : UIColor /// - Returns: NSAttributedString public func color(_ color: UIColor) -> NSAttributedString { let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) return colorString } /// Method to color substring of self /// - Parameters: /// - substring : String to apply the color in self /// - color : UIColor /// - Returns: NSAttributedString public func color(substring s: String, color: UIColor) -> NSMutableAttributedString { var start = 0 var ranges: [NSRange] = [] while true { let range = (self as NSString).range(of: s, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start)) if range.location == NSNotFound { break } else { ranges.append(range) start = range.location + range.length } } let attrText = NSMutableAttributedString(string: self) for range in ranges { attrText.addAttribute(NSForegroundColorAttributeName, value: color, range: range) } return attrText } } // MARK: Emoji public extension String { /// Method to check if String contains Emoji /// - Returns: Bool public func containsEmoji() -> Bool { for i in 0...length { let c: unichar = (self as NSString).character(at: i) if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) { return true } } return false } } // MARK: HTML //Source : https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555 private let characterEntities : [String: Character] = [ // XML predefined entities: "&quot;" : "\"", "&amp;" : "&", "&apos;" : "'", "&lt;" : "<", "&gt;" : ">", // HTML character entity references: "&nbsp;" : "\u{00A0}", "&iexcl;" : "\u{00A1}", "&cent;" : "\u{00A2}", "&pound;" : "\u{00A3}", "&curren;" : "\u{00A4}", "&yen;" : "\u{00A5}", "&brvbar;" : "\u{00A6}", "&sect;" : "\u{00A7}", "&uml;" : "\u{00A8}", "&copy;" : "\u{00A9}", "&ordf;" : "\u{00AA}", "&laquo;" : "\u{00AB}", "&not;" : "\u{00AC}", "&shy;" : "\u{00AD}", "&reg;" : "\u{00AE}", "&macr;" : "\u{00AF}", "&deg;" : "\u{00B0}", "&plusmn;" : "\u{00B1}", "&sup2;" : "\u{00B2}", "&sup3;" : "\u{00B3}", "&acute;" : "\u{00B4}", "&micro;" : "\u{00B5}", "&para;" : "\u{00B6}", "&middot;" : "\u{00B7}", "&cedil;" : "\u{00B8}", "&sup1;" : "\u{00B9}", "&ordm;" : "\u{00BA}", "&raquo;" : "\u{00BB}", "&frac14;" : "\u{00BC}", "&frac12;" : "\u{00BD}", "&frac34;" : "\u{00BE}", "&iquest;" : "\u{00BF}", "&Agrave;" : "\u{00C0}", "&Aacute;" : "\u{00C1}", "&Acirc;" : "\u{00C2}", "&Atilde;" : "\u{00C3}", "&Auml;" : "\u{00C4}", "&Aring;" : "\u{00C5}", "&AElig;" : "\u{00C6}", "&Ccedil;" : "\u{00C7}", "&Egrave;" : "\u{00C8}", "&Eacute;" : "\u{00C9}", "&Ecirc;" : "\u{00CA}", "&Euml;" : "\u{00CB}", "&Igrave;" : "\u{00CC}", "&Iacute;" : "\u{00CD}", "&Icirc;" : "\u{00CE}", "&Iuml;" : "\u{00CF}", "&ETH;" : "\u{00D0}", "&Ntilde;" : "\u{00D1}", "&Ograve;" : "\u{00D2}", "&Oacute;" : "\u{00D3}", "&Ocirc;" : "\u{00D4}", "&Otilde;" : "\u{00D5}", "&Ouml;" : "\u{00D6}", "&times;" : "\u{00D7}", "&Oslash;" : "\u{00D8}", "&Ugrave;" : "\u{00D9}", "&Uacute;" : "\u{00DA}", "&Ucirc;" : "\u{00DB}", "&Uuml;" : "\u{00DC}", "&Yacute;" : "\u{00DD}", "&THORN;" : "\u{00DE}", "&szlig;" : "\u{00DF}", "&agrave;" : "\u{00E0}", "&aacute;" : "\u{00E1}", "&acirc;" : "\u{00E2}", "&atilde;" : "\u{00E3}", "&auml;" : "\u{00E4}", "&aring;" : "\u{00E5}", "&aelig;" : "\u{00E6}", "&ccedil;" : "\u{00E7}", "&egrave;" : "\u{00E8}", "&eacute;" : "\u{00E9}", "&ecirc;" : "\u{00EA}", "&euml;" : "\u{00EB}", "&igrave;" : "\u{00EC}", "&iacute;" : "\u{00ED}", "&icirc;" : "\u{00EE}", "&iuml;" : "\u{00EF}", "&eth;" : "\u{00F0}", "&ntilde;" : "\u{00F1}", "&ograve;" : "\u{00F2}", "&oacute;" : "\u{00F3}", "&ocirc;" : "\u{00F4}", "&otilde;" : "\u{00F5}", "&ouml;" : "\u{00F6}", "&divide;" : "\u{00F7}", "&oslash;" : "\u{00F8}", "&ugrave;" : "\u{00F9}", "&uacute;" : "\u{00FA}", "&ucirc;" : "\u{00FB}", "&uuml;" : "\u{00FC}", "&yacute;" : "\u{00FD}", "&thorn;" : "\u{00FE}", "&yuml;" : "\u{00FF}", "&OElig;" : "\u{0152}", "&oelig;" : "\u{0153}", "&Scaron;" : "\u{0160}", "&scaron;" : "\u{0161}", "&Yuml;" : "\u{0178}", "&fnof;" : "\u{0192}", "&circ;" : "\u{02C6}", "&tilde;" : "\u{02DC}", "&Alpha;" : "\u{0391}", "&Beta;" : "\u{0392}", "&Gamma;" : "\u{0393}", "&Delta;" : "\u{0394}", "&Epsilon;" : "\u{0395}", "&Zeta;" : "\u{0396}", "&Eta;" : "\u{0397}", "&Theta;" : "\u{0398}", "&Iota;" : "\u{0399}", "&Kappa;" : "\u{039A}", "&Lambda;" : "\u{039B}", "&Mu;" : "\u{039C}", "&Nu;" : "\u{039D}", "&Xi;" : "\u{039E}", "&Omicron;" : "\u{039F}", "&Pi;" : "\u{03A0}", "&Rho;" : "\u{03A1}", "&Sigma;" : "\u{03A3}", "&Tau;" : "\u{03A4}", "&Upsilon;" : "\u{03A5}", "&Phi;" : "\u{03A6}", "&Chi;" : "\u{03A7}", "&Psi;" : "\u{03A8}", "&Omega;" : "\u{03A9}", "&alpha;" : "\u{03B1}", "&beta;" : "\u{03B2}", "&gamma;" : "\u{03B3}", "&delta;" : "\u{03B4}", "&epsilon;" : "\u{03B5}", "&zeta;" : "\u{03B6}", "&eta;" : "\u{03B7}", "&theta;" : "\u{03B8}", "&iota;" : "\u{03B9}", "&kappa;" : "\u{03BA}", "&lambda;" : "\u{03BB}", "&mu;" : "\u{03BC}", "&nu;" : "\u{03BD}", "&xi;" : "\u{03BE}", "&omicron;" : "\u{03BF}", "&pi;" : "\u{03C0}", "&rho;" : "\u{03C1}", "&sigmaf;" : "\u{03C2}", "&sigma;" : "\u{03C3}", "&tau;" : "\u{03C4}", "&upsilon;" : "\u{03C5}", "&phi;" : "\u{03C6}", "&chi;" : "\u{03C7}", "&psi;" : "\u{03C8}", "&omega;" : "\u{03C9}", "&thetasym;" : "\u{03D1}", "&upsih;" : "\u{03D2}", "&piv;" : "\u{03D6}", "&ensp;" : "\u{2002}", "&emsp;" : "\u{2003}", "&thinsp;" : "\u{2009}", "&zwnj;" : "\u{200C}", "&zwj;" : "\u{200D}", "&lrm;" : "\u{200E}", "&rlm;" : "\u{200F}", "&ndash;" : "\u{2013}", "&mdash;" : "\u{2014}", "&lsquo;" : "\u{2018}", "&rsquo;" : "\u{2019}", "&sbquo;" : "\u{201A}", "&ldquo;" : "\u{201C}", "&rdquo;" : "\u{201D}", "&bdquo;" : "\u{201E}", "&dagger;" : "\u{2020}", "&Dagger;" : "\u{2021}", "&bull;" : "\u{2022}", "&hellip;" : "\u{2026}", "&permil;" : "\u{2030}", "&prime;" : "\u{2032}", "&Prime;" : "\u{2033}", "&lsaquo;" : "\u{2039}", "&rsaquo;" : "\u{203A}", "&oline;" : "\u{203E}", "&frasl;" : "\u{2044}", "&euro;" : "\u{20AC}", "&image;" : "\u{2111}", "&weierp;" : "\u{2118}", "&real;" : "\u{211C}", "&trade;" : "\u{2122}", "&alefsym;" : "\u{2135}", "&larr;" : "\u{2190}", "&uarr;" : "\u{2191}", "&rarr;" : "\u{2192}", "&darr;" : "\u{2193}", "&harr;" : "\u{2194}", "&crarr;" : "\u{21B5}", "&lArr;" : "\u{21D0}", "&uArr;" : "\u{21D1}", "&rArr;" : "\u{21D2}", "&dArr;" : "\u{21D3}", "&hArr;" : "\u{21D4}", "&forall;" : "\u{2200}", "&part;" : "\u{2202}", "&exist;" : "\u{2203}", "&empty;" : "\u{2205}", "&nabla;" : "\u{2207}", "&isin;" : "\u{2208}", "&notin;" : "\u{2209}", "&ni;" : "\u{220B}", "&prod;" : "\u{220F}", "&sum;" : "\u{2211}", "&minus;" : "\u{2212}", "&lowast;" : "\u{2217}", "&radic;" : "\u{221A}", "&prop;" : "\u{221D}", "&infin;" : "\u{221E}", "&ang;" : "\u{2220}", "&and;" : "\u{2227}", "&or;" : "\u{2228}", "&cap;" : "\u{2229}", "&cup;" : "\u{222A}", "&int;" : "\u{222B}", "&there4;" : "\u{2234}", "&sim;" : "\u{223C}", "&cong;" : "\u{2245}", "&asymp;" : "\u{2248}", "&ne;" : "\u{2260}", "&equiv;" : "\u{2261}", "&le;" : "\u{2264}", "&ge;" : "\u{2265}", "&sub;" : "\u{2282}", "&sup;" : "\u{2283}", "&nsub;" : "\u{2284}", "&sube;" : "\u{2286}", "&supe;" : "\u{2287}", "&oplus;" : "\u{2295}", "&otimes;" : "\u{2297}", "&perp;" : "\u{22A5}", "&sdot;" : "\u{22C5}", "&lceil;" : "\u{2308}", "&rceil;" : "\u{2309}", "&lfloor;" : "\u{230A}", "&rfloor;" : "\u{230B}", "&lang;" : "\u{2329}", "&rang;" : "\u{232A}", "&loz;" : "\u{25CA}", "&spades;" : "\u{2660}", "&clubs;" : "\u{2663}", "&hearts;" : "\u{2665}", "&diams;" : "\u{2666}", ] public extension String { /// Method that returns a tuple containing the string made by replacing in the /// `String` all HTML character entity references with the corresponding /// character. Also returned is an array of offset information describing /// the location and length offsets for each replacement. This allows /// for the correct adjust any attributes that may be associated with /// with substrings within the `String` func decodeHTMLEntities() -> (decodedString: String, replacementOffsets: [Range<String.Index>]) { // ===== Utility functions ===== // Record the index offsets of each replacement // This allows anyone to correctly adjust any attributes that may be // associated with substrings within the string var replacementOffsets: [Range<String.Index>] = [] // Convert the number in the string to the corresponding // Unicode character, e.g. // decodeNumeric("64", 10) --> "@" // decodeNumeric("20ac", 16) --> "€" func decodeNumeric(string : String, base : Int32) -> Character? { let code = UInt32(strtoul(string, nil, base)) return Character(UnicodeScalar(code)!) } // Decode the HTML character entity to the corresponding // Unicode character, return `nil` for invalid input. // decode("&#64;") --> "@" // decode("&#x20ac;") --> "€" // decode("&lt;") --> "<" // decode("&foo;") --> nil func decode(entity : String) -> Character? { if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){ return decodeNumeric(string: entity.substring(from: entity.index(entity.startIndex, offsetBy: 3)), base: 16) } else if entity.hasPrefix("&#") { return decodeNumeric(string: entity.substring(from: entity.index(entity.startIndex, offsetBy: 2)), base: 10) } else { return characterEntities[entity] } } // ===== Method starts here ===== var result = "" var position = startIndex // Find the next '&' and copy the characters preceding it to `result`: while let ampRange = self.range(of:"&", range: position ..< endIndex) { result += self[position ..< ampRange.lowerBound] position = ampRange.lowerBound // Find the next ';' and copy everything from '&' to ';' into `entity` if let semiRange = self.range(of:";", range: position ..< endIndex) { let entity = self[position ..< semiRange.upperBound] if let decoded = decode(entity: entity) { // Replace by decoded character: result.append(decoded) replacementOffsets.append(Range(position ..< semiRange.upperBound)) } else { // Invalid entity, copy verbatim: result += entity } position = semiRange.upperBound } else { // No matching ';'. break } } // Copy remaining characters to `result`: result += self[position ..< endIndex] // Return results return (decodedString: result, replacementOffsets: replacementOffsets) } }
mit
Kaffys/AppleWatchFitness
Testing TablesTests/Testing_TablesTests.swift
1
990
// // Testing_TablesTests.swift // Testing TablesTests // // Created by Apple on 9/5/15. // Copyright © 2015 Kaffys. All rights reserved. // import XCTest @testable import Testing_Tables class Testing_TablesTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
AimobierCocoaPods/OddityUI
Classes/NewFeedListViewController/NewFeedListDataSource.swift
1
12508
// // NewFeedListDataSource.swift // OddityUI // // Created by Mister on 16/8/29. // Copyright © 2016年 aimobier. All rights reserved. // import UIKit import PINCache // ///// 属性字符串 缓存器 //class TableViewHeightCached { // // // private static var __once: () = { () -> Void in // backTaskLeton.instance = TableViewHeightCached() // }() // // lazy var cache = PINMemoryCache() // // class var sharedHeightCached:TableViewHeightCached!{ // get{ // struct backTaskLeton{ // static var predicate:Int = 0 // static var instance:TableViewHeightCached? = nil // } // _ = TableViewHeightCached.__once // return backTaskLeton.instance // } // } // // func cacheHeight(_ nid : Int,height:CGFloat){ // // self.cache.setObject(height, forKey: "\(nid)") // } // // /** // 根据提供的 title 字符串 (title 针对于频道时唯一的,可以当作唯一标识来使用)在缓存中获取UIViewController // // - parameter string: 原本 字符串 // - parameter font: 字体 对象 默认为 系统2号字体 // // - returns: 返回属性字符串 // */ // func heightForNewNID(_ nid : Int ) -> CGFloat { // //// if let channelViewController = self.cache.objectForKey(nid) as? CG { return channelViewController } //// //// let channelViewController = getDisplayViewController(channel.cname) //// //// channelViewController.channel = channel //// //// if channel.id == 1{ //// //// channelViewController.newsResults = New.allArray().filter("ishotnew = 1 AND isdelete = 0") //// }else{ //// //// channelViewController.newsResults = New.allArray().filter("(ANY channelList.channel = %@ AND isdelete = 0 ) OR ( channel = %@ AND isidentification = 1 )",channel.id,channel.id) //// } //// //// self.cache.setObject(channelViewController, forKey: channel.cname) // // return self.cache.object(forKey: "\(nid)") as? CGFloat ?? -1 // } //} extension NewFeedListViewController:UITableViewDataSource{ fileprivate func getTableViewCell(_ indexPath : IndexPath) -> UITableViewCell{ let new = newsResults[(indexPath as NSIndexPath).row] if new.rtype == 4 { let cell = tableView.dequeueReusableCell(withIdentifier: "SpecialTableViewCell") as! SpecialTableViewCell cell.setNewObject(new) return cell } var cell :NewBaseTableViewCell! if new.isidentification == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "refreshcell")! as UITableViewCell return cell } if new.style == 0 { cell = tableView.dequeueReusableCell(withIdentifier: "NewNormalTableViewCell") as! NewNormalTableViewCell cell.setNewObject(new) }else if new.style == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "NewOneTableViewCell") as! NewOneTableViewCell cell.setNewObject(new) }else if new.style == 2 { cell = tableView.dequeueReusableCell(withIdentifier: "NewTwoTableViewCell") as! NewTwoTableViewCell cell.setNewObject(new) }else if new.style == 3 { cell = tableView.dequeueReusableCell(withIdentifier: "NewThreeTableViewCell") as! NewThreeTableViewCell cell.setNewObject(new) }else{ cell = tableView.dequeueReusableCell(withIdentifier: "NewTwoTableViewCell") as! NewTwoTableViewCell switch new.style { case 5: cell.setNewObject(new,bigImg: 0) case 11: cell.setNewObject(new,bigImg: 0) case 12: cell.setNewObject(new,bigImg: 1) default: cell.setNewObject(new,bigImg: 2) } } cell.noLikeButton.removeActions(events: UIControlEvents.touchUpInside) cell.noLikeButton.addAction(events: UIControlEvents.touchUpInside) { (_) in self.handleActionMethod(cell, indexPath: indexPath) } // if self.channel?.id == 1 { cell.setPPPLabel(new) // } return cell } /** 设置新闻的个数 判断当前视图没有newResults对象,如果没有 默认返回0 有则正常返回其数目 - parameter tableView: 表格对象 - parameter section: section index - returns: 新闻的个数 */ public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsResults.count } /** 返回每一个新闻的展示 其中当遇到 这个新闻的 `isidentification` 的标示为 1 的时候,说明这条新闻是用来显示一个刷新视图的。 其它的新闻会根据起 style 参数进行 没有图 一张图 两张图 三张图的 新闻展示形式进行不同形式的展示 - parameter tableView: 表格对象 - parameter indexPath: 当前新闻展示的位置 - returns: 返回新闻的具体战士杨视图 */ public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return self.getTableViewCell(indexPath) } /** 处理用户的点击新闻视图中的 不喜欢按钮处理方法 首先获取当前cell基于注视图的point。用于传递给上层视图进行 cell 新闻的展示 计算cell所在的位置,之后预估起全部展开的位置大小,是否会被遮挡,如果被遮挡 ,就先进性cel的移动,使其不会被遮挡 之后将这个cell和所在的point传递给上层视图 使用的传递工具为 delegate 之后上层视图处理完成之后,返回是否删除动作,当前tableview进行删除或者刷新cell - parameter cell: 返回被点击的cell - parameter indexPath: 被点击的位置 */ fileprivate func handleActionMethod(_ cell :NewBaseTableViewCell,indexPath:IndexPath){ var delayInSeconds = 0.0 let porint = cell.convert(cell.bounds, to: self.view).origin if porint.y < 0 { delayInSeconds = 0.5 self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true) } let needHeight = porint.y+cell.frame.height+128 if needHeight > self.tableView.frame.height { delayInSeconds = 0.5 let result = needHeight-self.tableView.frame.height let toPoint = CGPoint(x: 0, y: self.tableView.contentOffset.y+result) self.tableView.setContentOffset(toPoint, animated: true) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // 2 self.predelegate.ClickNoLikeButtonOfUITableViewCell?(cell, finish: { (cancel) in if !cancel { self.newsResults[(indexPath as NSIndexPath).row].suicide() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // 2 self.showNoInterest() self.tableView.reloadData() } }else{ self.tableView.reloadData() } }) } } } extension NewFeedListViewController:UITableViewDelegate{ /** 点击cell 之后处理的方法 如果是刷新的cell就进行当前新闻的刷新 如果是新闻cell就进行 - parameter tableView: tableview 对象 - parameter indexPath: 点击的indexPath */ public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let new = newsResults[(indexPath as NSIndexPath).row] if new.isidentification == 1 { return self.tableView.mj_header.beginRefreshing() } if new.rtype == 4, let view = OddityViewControllerManager.shareManager.storyBoard.instantiateViewController(withIdentifier: "SpecialViewController") as? SpecialViewController { view.tid = new.nid view.odditySetting = self.odditySetting view.oddityDelegate = self.oddityDelegate return self.present(view, animated: true, completion: nil) } if new.rtype == 3, let view = OddityViewControllerManager.shareManager.storyBoard.instantiateViewController(withIdentifier: "AdsWebViewController") as? AdsWebViewController { view.adsUrlString = new.purl return self.present(view, animated: true, completion: nil) } let viewController = OddityViewControllerManager.shareManager.getDetailAndCommitViewController(new) viewController.odditySetting = self.odditySetting viewController.oddityDelegate = self.oddityDelegate self.show(viewController, sender: nil) if new.isread == 0 { new.isRead() // 设置为已读 } } } open class AdsWebViewController : UIViewController,UIViewControllerTransitioningDelegate { var adsUrlString = "" var waitView:WaitView! @IBOutlet var dissButton: UIButton! // 左上角更多按钮 @IBOutlet var webView:UIWebView! let DismissedAnimation = CustomViewControllerDismissedAnimation() let PresentdAnimation = CustomViewControllerPresentdAnimation() // 切换全屏活着完成反悔上一个界面 @IBAction func touchViewController(_ sender: AnyObject) { return self.dismiss(animated: true, completion: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.transitioningDelegate = self self.modalPresentationCapturesStatusBarAppearance = false // self.modalPresentationStyle = UIModalPresentationStyle.Custom } open override func viewDidLoad() { super.viewDidLoad() self.webView.delegate = self guard let encodedStr = adsUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),let url = URL(string: encodedStr) else { return } self.webView.loadRequest(URLRequest(url: url)) } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PresentdAnimation } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DismissedAnimation } } extension AdsWebViewController:UIWebViewDelegate,WaitLoadProtcol { public func webViewDidStartLoad(_ webView: UIWebView) { self.showWaitLoadView() } public func webViewDidFinishLoad(_ webView: UIWebView) { self.hiddenWaitLoadView() } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.waitView.setNoNetWork { guard let encodedStr = self.adsUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),let url = URL(string: encodedStr) else { return } self.webView.loadRequest(URLRequest(url: url)) } } }
mit
WeltN24/Carlos
Example/Example/MemoryWarningSampleViewController.swift
1
1049
import Carlos import Combine import Foundation import UIKit class MemoryWarningSampleViewController: BaseCacheViewController { private var cache: BasicCache<URL, NSData>! private var token: NSObjectProtocol? var cancellable: AnyCancellable? override func fetchRequested() { super.fetchRequested() cancellable = cache.get(URL(string: urlKeyField?.text ?? "")!) .sink(receiveCompletion: { _ in }, receiveValue: { _ in }) } override func titleForScreen() -> String { "Memory warnings" } override func setupCache() { super.setupCache() cache = simpleCache() } @IBAction func memoryWarningSwitchValueChanged(_ sender: UISwitch) { if sender.isOn, token == nil { token = cache.listenToMemoryWarnings() } else if let token = token, !sender.isOn { unsubscribeToMemoryWarnings(token) self.token = nil } } @IBAction func simulateMemoryWarning(_: AnyObject) { NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil) } }
mit
mindvalley/Mobile_iOS_Library_MVMedia
MVMedia/Classes/Cells/MVMediaMarkerTableViewCell.swift
1
650
// // MediaMarkerTableViewCell.swift // Micro Learning App // // Created by Evandro Harrison Hoffmann on 19/09/2016. // Copyright © 2016 Mindvalley. All rights reserved. // import UIKit open class MVMediaMarkerTableViewCell: UITableViewCell { @IBOutlet open weak var timeLabel: UILabel! @IBOutlet open weak var titleLabel: UILabel! override open func awakeFromNib() { super.awakeFromNib() // Initialization code } override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
scarlettwu93/test
Example/Pods/SwiftSVG/SwiftSVG/String+Subscript.swift
1
2371
// // String+Subscript.swift // Breakfast // // This file is from a dynamic framework I created called Breakfast. I included the // files here so you didn't have to install another Cocoapod to use and test out // this library. As such, this file may not be maintained as well, so use it at // your own risk. // // SwiftSVG is one of the many great tools that are a part of Breakfast. If you're // looking for a great start to your next Swift project, check out Breakfast. // It contains classes and helper functions that will get you started off right. // https://github.com/mchoe/Breakfast // // // Copyright (c) 2015 Michael Choe // http://www.straussmade.com/ // http://www.twitter.com/_mchoe // http://www.github.com/mchoe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif public extension String { subscript(index: Int) -> Character { get { let index = self.startIndex.advancedBy(index) return self[index] } } subscript(integerRange: Range<Int>) -> String { let start = self.startIndex.advancedBy(integerRange.startIndex) let end = self.startIndex.advancedBy(integerRange.endIndex) let range = start..<end return self[range] } }
mit
simeonpp/home-hunt
ios-client/Pods/Swinject/Sources/UnavailableItems.swift
9
692
// // UnavailableItems.swift // Swinject // // Created by Yoichi Tagaya on 11/30/16. // Copyright © 2016 Swinject Contributors. All rights reserved. // // MARK: For auto migration from Swinject v1 to v2. extension ObjectScope { @available(*, unavailable, renamed: "transient") public static let none = transient @available(*, unavailable, renamed: "container") public static let hierarchy = container } @available(*, unavailable, renamed: "Resolver") public protocol ResolverType { } @available(*, unavailable, renamed: "Assembly") public protocol AssemblyType { } @available(*, unavailable, renamed: "ServiceKeyOption") public protocol ServiceKeyOptionType { }
mit
LaudyLaw/LSPlayPauseButton
Example/Example/AppDelegate.swift
1
2173
// // AppDelegate.swift // Example // // Created by Pisen_LuoSong on 2017/9/8. // Copyright © 2017年 LuoSong. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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:. } }
mit
GYLibrary/GYNetWorking
GYNetWorkingUITests/GYNetWorkingUITests.swift
1
1258
// // GYNetWorkINGUITests.swift // GYNetWorkINGUITests // // Created by zhuguangyang on 16/10/26. // Copyright © 2016年 Giant. All rights reserved. // import XCTest class GYNetWorkINGUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
rdlester/simply-giphy
Pods/ReactiveCocoa/ReactiveCocoa/NSObject+Intercepting.swift
1
16280
import Foundation import ReactiveSwift import enum Result.NoError /// Whether the runtime subclass has already been prepared for method /// interception. fileprivate let interceptedKey = AssociationKey(default: false) /// Holds the method signature cache of the runtime subclass. fileprivate let signatureCacheKey = AssociationKey<SignatureCache>() /// Holds the method selector cache of the runtime subclass. fileprivate let selectorCacheKey = AssociationKey<SelectorCache>() extension Reactive where Base: NSObject { /// Create a signal which sends a `next` event at the end of every /// invocation of `selector` on the object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A trigger signal. public func trigger(for selector: Selector) -> Signal<(), NoError> { return base.intercept(selector).map { _ in } } /// Create a signal which sends a `next` event, containing an array of /// bridged arguments, at the end of every invocation of `selector` on the /// object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A signal that sends an array of bridged arguments. public func signal(for selector: Selector) -> Signal<[Any?], NoError> { return base.intercept(selector).map(unpackInvocation) } } extension NSObject { /// Setup the method interception. /// /// - parameters: /// - object: The object to be intercepted. /// - selector: The selector of the method to be intercepted. /// /// - returns: A signal that sends the corresponding `NSInvocation` after /// every invocation of the method. @nonobjc fileprivate func intercept(_ selector: Selector) -> Signal<AnyObject, NoError> { guard let method = class_getInstanceMethod(objcClass, selector) else { fatalError("Selector `\(selector)` does not exist in class `\(String(describing: objcClass))`.") } let typeEncoding = method_getTypeEncoding(method)! assert(checkTypeEncoding(typeEncoding)) return synchronized { let alias = selector.alias let stateKey = AssociationKey<InterceptingState?>(alias) let interopAlias = selector.interopAlias if let state = associations.value(forKey: stateKey) { return state.signal } let subclass: AnyClass = swizzleClass(self) let subclassAssociations = Associations(subclass as AnyObject) // FIXME: Compiler asks to handle a mysterious throw. try! ReactiveCocoa.synchronized(subclass) { let isSwizzled = subclassAssociations.value(forKey: interceptedKey) let signatureCache: SignatureCache let selectorCache: SelectorCache if isSwizzled { signatureCache = subclassAssociations.value(forKey: signatureCacheKey) selectorCache = subclassAssociations.value(forKey: selectorCacheKey) } else { signatureCache = SignatureCache() selectorCache = SelectorCache() subclassAssociations.setValue(signatureCache, forKey: signatureCacheKey) subclassAssociations.setValue(selectorCache, forKey: selectorCacheKey) subclassAssociations.setValue(true, forKey: interceptedKey) enableMessageForwarding(subclass, selectorCache) setupMethodSignatureCaching(subclass, signatureCache) } selectorCache.cache(selector) if signatureCache[selector] == nil { let signature = NSMethodSignature.signature(withObjCTypes: typeEncoding) signatureCache[selector] = signature } // If an immediate implementation of the selector is found in the // runtime subclass the first time the selector is intercepted, // preserve the implementation. // // Example: KVO setters if the instance is swizzled by KVO before RAC // does. if !class_respondsToSelector(subclass, interopAlias) { let immediateImpl = class_getImmediateMethod(subclass, selector) .flatMap(method_getImplementation) .flatMap { $0 != _rac_objc_msgForward ? $0 : nil } if let impl = immediateImpl { let succeeds = class_addMethod(subclass, interopAlias, impl, typeEncoding) precondition(succeeds, "RAC attempts to swizzle a selector that has message forwarding enabled with a runtime injected implementation. This is unsupported in the current version.") } } } let state = InterceptingState(lifetime: reactive.lifetime) associations.setValue(state, forKey: stateKey) // Start forwarding the messages of the selector. _ = class_replaceMethod(subclass, selector, _rac_objc_msgForward, typeEncoding) return state.signal } } } /// Swizzle `realClass` to enable message forwarding for method interception. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. private func enableMessageForwarding(_ realClass: AnyClass, _ selectorCache: SelectorCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass) typealias ForwardInvocationImpl = @convention(block) (Unmanaged<NSObject>, AnyObject) -> Void let newForwardInvocation: ForwardInvocationImpl = { objectRef, invocation in let selector = invocation.selector! let alias = selectorCache.alias(for: selector) let interopAlias = selectorCache.interopAlias(for: selector) defer { let stateKey = AssociationKey<InterceptingState?>(alias) if let state = objectRef.takeUnretainedValue().associations.value(forKey: stateKey) { state.observer.send(value: invocation) } } let method = class_getInstanceMethod(perceivedClass, selector)! let typeEncoding = method_getTypeEncoding(method) if class_respondsToSelector(realClass, interopAlias) { // RAC has preserved an immediate implementation found in the runtime // subclass that was supplied by an external party. // // As the KVO setter relies on the selector to work, it has to be invoked // by swapping in the preserved implementation and restore to the message // forwarder afterwards. // // However, the IMP cache would be thrashed due to the swapping. let topLevelClass: AnyClass = object_getClass(objectRef.takeUnretainedValue()) // The locking below prevents RAC swizzling attempts from intervening the // invocation. // // Given the implementation of `swizzleClass`, `topLevelClass` can only be: // (1) the same as `realClass`; or (2) a subclass of `realClass`. In other // words, this would deadlock only if the locking order is not followed in // other nested locking scenarios of these metaclasses at compile time. synchronized(topLevelClass) { func swizzle() { let interopImpl = class_getMethodImplementation(topLevelClass, interopAlias) let previousImpl = class_replaceMethod(topLevelClass, selector, interopImpl, typeEncoding) invocation.invoke() _ = class_replaceMethod(topLevelClass, selector, previousImpl, typeEncoding) } if topLevelClass != realClass { synchronized(realClass) { // In addition to swapping in the implementation, the message // forwarding needs to be temporarily disabled to prevent circular // invocation. _ = class_replaceMethod(realClass, selector, nil, typeEncoding) swizzle() _ = class_replaceMethod(realClass, selector, _rac_objc_msgForward, typeEncoding) } } else { swizzle() } } return } if let impl = method_getImplementation(method), impl != _rac_objc_msgForward { // The perceived class, or its ancestors, responds to the selector. // // The implementation is invoked through the selector alias, which // reflects the latest implementation of the selector in the perceived // class. if class_getMethodImplementation(realClass, alias) != impl { // Update the alias if and only if the implementation has changed, so as // to avoid thrashing the IMP cache. _ = class_replaceMethod(realClass, alias, impl, typeEncoding) } invocation.setSelector(alias) invocation.invoke() return } // Forward the invocation to the closest `forwardInvocation(_:)` in the // inheritance hierarchy, or the default handler returned by the runtime // if it finds no implementation. typealias SuperForwardInvocation = @convention(c) (Unmanaged<NSObject>, Selector, AnyObject) -> Void let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.forwardInvocation) let forwardInvocation = unsafeBitCast(impl, to: SuperForwardInvocation.self) forwardInvocation(objectRef, ObjCSelector.forwardInvocation, invocation) } _ = class_replaceMethod(realClass, ObjCSelector.forwardInvocation, imp_implementationWithBlock(newForwardInvocation as Any), ObjCMethodEncoding.forwardInvocation) } /// Swizzle `realClass` to accelerate the method signature retrieval, using a /// signature cache that covers all known intercepted selectors of `realClass`. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. /// - signatureCache: The method signature cache. private func setupMethodSignatureCaching(_ realClass: AnyClass, _ signatureCache: SignatureCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass) let newMethodSignatureForSelector: @convention(block) (Unmanaged<NSObject>, Selector) -> AnyObject? = { objectRef, selector in if let signature = signatureCache[selector] { return signature } typealias SuperMethodSignatureForSelector = @convention(c) (Unmanaged<NSObject>, Selector, Selector) -> AnyObject? let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.methodSignatureForSelector) let methodSignatureForSelector = unsafeBitCast(impl, to: SuperMethodSignatureForSelector.self) return methodSignatureForSelector(objectRef, ObjCSelector.methodSignatureForSelector, selector) } _ = class_replaceMethod(realClass, ObjCSelector.methodSignatureForSelector, imp_implementationWithBlock(newMethodSignatureForSelector as Any), ObjCMethodEncoding.methodSignatureForSelector) } /// The state of an intercepted method specific to an instance. private final class InterceptingState { let (signal, observer) = Signal<AnyObject, NoError>.pipe() /// Initialize a state specific to an instance. /// /// - parameters: /// - lifetime: The lifetime of the instance. init(lifetime: Lifetime) { lifetime.ended.observeCompleted(observer.sendCompleted) } } private final class SelectorCache { private var map: [Selector: (main: Selector, interop: Selector)] = [:] init() {} /// Cache the aliases of the specified selector in the cache. /// /// - warning: Any invocation of this method must be synchronized against the /// runtime subclass. @discardableResult func cache(_ selector: Selector) -> (main: Selector, interop: Selector) { if let pair = map[selector] { return pair } let aliases = (selector.alias, selector.interopAlias) map[selector] = aliases return aliases } /// Get the alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func alias(for selector: Selector) -> Selector { if let (main, _) = map[selector] { return main } return selector.alias } /// Get the secondary alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func interopAlias(for selector: Selector) -> Selector { if let (_, interop) = map[selector] { return interop } return selector.interopAlias } } // The signature cache for classes that have been swizzled for method // interception. // // Read-copy-update is used here, since the cache has multiple readers but only // one writer. private final class SignatureCache { // `Dictionary` takes 8 bytes for the reference to its storage and does CoW. // So it should not encounter any corrupted, partially updated state. private var map: [Selector: AnyObject] = [:] init() {} /// Get or set the signature for the specified selector. /// /// - warning: Any invocation of the setter must be synchronized against the /// runtime subclass. /// /// - parameters: /// - selector: The method signature. subscript(selector: Selector) -> AnyObject? { get { return map[selector] } set { if map[selector] == nil { map[selector] = newValue } } } } /// Assert that the method does not contain types that cannot be intercepted. /// /// - parameters: /// - types: The type encoding C string of the method. /// /// - returns: `true`. private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool { // Some types, including vector types, are not encoded. In these cases the // signature starts with the size of the argument frame. assert(types.pointee < Int8(UInt8(ascii: "1")) || types.pointee > Int8(UInt8(ascii: "9")), "unknown method return type not supported in type encoding: \(String(cString: types))") assert(types.pointee != Int8(UInt8(ascii: "(")), "union method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "{")), "struct method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "[")), "array method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "j")), "complex method return type not supported") return true } /// Extract the arguments of an `NSInvocation` as an array of objects. /// /// - parameters: /// - invocation: The `NSInvocation` to unpack. /// /// - returns: An array of objects. private func unpackInvocation(_ invocation: AnyObject) -> [Any?] { let invocation = invocation as AnyObject let methodSignature = invocation.objcMethodSignature! let count = UInt(methodSignature.numberOfArguments!) var bridged = [Any?]() bridged.reserveCapacity(Int(count - 2)) // Ignore `self` and `_cmd` at index 0 and 1. for position in 2 ..< count { let rawEncoding = methodSignature.argumentType(at: position) let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined func extract<U>(_ type: U.Type) -> U { let pointer = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) defer { pointer.deallocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) } invocation.copy(to: pointer, forArgumentAt: Int(position)) return pointer.assumingMemoryBound(to: type).pointee } let value: Any? switch encoding { case .char: value = NSNumber(value: extract(CChar.self)) case .int: value = NSNumber(value: extract(CInt.self)) case .short: value = NSNumber(value: extract(CShort.self)) case .long: value = NSNumber(value: extract(CLong.self)) case .longLong: value = NSNumber(value: extract(CLongLong.self)) case .unsignedChar: value = NSNumber(value: extract(CUnsignedChar.self)) case .unsignedInt: value = NSNumber(value: extract(CUnsignedInt.self)) case .unsignedShort: value = NSNumber(value: extract(CUnsignedShort.self)) case .unsignedLong: value = NSNumber(value: extract(CUnsignedLong.self)) case .unsignedLongLong: value = NSNumber(value: extract(CUnsignedLongLong.self)) case .float: value = NSNumber(value: extract(CFloat.self)) case .double: value = NSNumber(value: extract(CDouble.self)) case .bool: value = NSNumber(value: extract(CBool.self)) case .object: value = extract((AnyObject?).self) case .type: value = extract((AnyClass?).self) case .selector: value = extract((Selector?).self) case .undefined: var size = 0, alignment = 0 NSGetSizeAndAlignment(rawEncoding, &size, &alignment) let buffer = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment) defer { buffer.deallocate(bytes: size, alignedTo: alignment) } invocation.copy(to: buffer, forArgumentAt: Int(position)) value = NSValue(bytes: buffer, objCType: rawEncoding) } bridged.append(value) } return bridged }
apache-2.0
narner/AudioKit
AudioKit/Common/Internals/AudioUnit Host/AKAudioUnitInstrument.swift
1
1868
// // AKAudioUnitInstrument.swift // AudioKit // // Created by Ryan Francesconi, revision history on Github. // Copyright © 2017 AudioKit. All rights reserved. // /// Wrapper for audio units that accept MIDI (ie. instruments) open class AKAudioUnitInstrument: AKMIDIInstrument { /// Initialize the audio unit instrument /// /// - parameter audioUnit: AVAudioUnitMIDIInstrument to wrap /// public init?(audioUnit: AVAudioUnitMIDIInstrument) { super.init() self.midiInstrument = audioUnit AudioKit.engine.attach(audioUnit) // assign the output to the mixer self.avAudioNode = audioUnit self.name = audioUnit.name } /// Send MIDI Note On information to the audio unit /// /// - Parameters /// - noteNumber: MIDI note number to play /// - velocity: MIDI velocity to play the note at /// - channel: MIDI channel to play the note on /// open func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity = 64, channel: MIDIChannel = 0) { guard self.midiInstrument != nil else { AKLog("no midiInstrument exists") return } self.midiInstrument!.startNote(noteNumber, withVelocity: velocity, onChannel: channel) } /// Send MIDI Note Off information to the audio unit /// /// - Parameters /// - noteNumber: MIDI note number to stop /// - channel: MIDI channel to stop the note on /// override open func stop(noteNumber: MIDINoteNumber) { stop(noteNumber: noteNumber, channel: 0) } override open func stop(noteNumber: MIDINoteNumber, channel: MIDIChannel) { guard self.midiInstrument != nil else { AKLog("no midiInstrument exists") return } self.midiInstrument!.stopNote(noteNumber, onChannel: channel) } }
mit
wanghdnku/Whisper
Whisper/CustomizableImageView.swift
1
375
// // CustomizableImageView.swift // Swift Academy // // Created by Frezy Stone Mboumba on 7/8/16. // Copyright © 2016 Frezy Stone Mboumba. All rights reserved. // import UIKit @IBDesignable class CustomizableImageView: UIImageView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } }
mit
congncif/SiFUtilities
Foundation/Codable/JSONCodable.swift
1
896
// // JSONCodable.swift // // // Created by NGUYEN CHI CONG on 12/18/20. // import Foundation public protocol JSONDecodable { init(from jsonData: Data) throws init(from jsonString: String) throws } public protocol JSONEncodable { func encodeData() throws -> Data } public extension JSONDecodable where Self: Decodable { init(from jsonData: Data) throws { self = try JSONDecoder().decode(Self.self, from: jsonData) } init(from jsonString: String) throws { guard let data = jsonString.data() else { throw NSError(domain: "JSONDecodable.jsonString.invalid", code: 0, userInfo: [NSLocalizedDescriptionKey: "Cannot convert json string to data"]) } try self.init(from: data) } } public extension JSONEncodable where Self: Encodable { func encodeData() throws -> Data { try JSONEncoder().encode(self) } }
mit
cforlando/orlando-walking-tours-ios
Orlando Walking Tours/Models/HistoricLocation+CoreDataClass.swift
1
267
// // HistoricLocation+CoreDataClass.swift // Orlando Walking Tours // // Created by Keli'i Martin on 9/23/16. // Copyright © 2016 Code for Orlando. All rights reserved. // import Foundation import CoreData public class HistoricLocation: NSManagedObject { }
mit
Sadmansamee/quran-ios
Quran/Container.swift
1
7937
// // Container.swift // Quran // // Created by Mohamed Afifi on 4/20/16. // Copyright © 2016 Quran.com. All rights reserved. // import UIKit class Container { fileprivate static let DownloadsBackgroundIdentifier = "com.quran.ios.downloading.audio" fileprivate let imagesCache: Cache<Int, UIImage> = { let cache = Cache<Int, UIImage>() cache.countLimit = 5 return cache }() fileprivate var downloadManager: DownloadManager! = nil init() { let configuration = URLSessionConfiguration.background(withIdentifier: "DownloadsBackgroundIdentifier") downloadManager = URLSessionDownloadManager(configuration: configuration, persistence: createSimplePersistence()) } func createRootViewController() -> UIViewController { let controller = MainTabBarController() controller.viewControllers = [createSurasNavigationController(), createJuzsNavigationController(), createBookmarksController()] return controller } func createSurasNavigationController() -> UIViewController { return SurasNavigationController(rootViewController: createSurasViewController()) } func createJuzsNavigationController() -> UIViewController { return JuzsNavigationController(rootViewController: createJuzsViewController()) } func createSurasViewController() -> UIViewController { return SurasViewController(dataRetriever: createSurasRetriever(), quranControllerCreator: createCreator(createQuranController)) } func createJuzsViewController() -> UIViewController { return JuzsViewController(dataRetriever: createQuartersRetriever(), quranControllerCreator: createCreator(createQuranController)) } func createSearchController() -> UIViewController { return SearchNavigationController(rootViewController: SearchViewController()) } func createSettingsController() -> UIViewController { return SettingsNavigationController(rootViewController: SettingsViewController()) } func createBookmarksController() -> UIViewController { return BookmarksNavigationController(rootViewController: createBookmarksViewController()) } func createBookmarksViewController() -> UIViewController { return BookmarksTableViewController( quranControllerCreator: createCreator(createQuranController), simplePersistence: createSimplePersistence(), lastPagesPersistence: createLastPagesPersistence(), bookmarksPersistence: createBookmarksPersistence(), ayahPersistence: createAyahTextStorage()) } func createQariTableViewController() -> QariTableViewController { return QariTableViewController(style: .plain) } func createSurasRetriever() -> AnyDataRetriever<[(Juz, [Sura])]> { return SurasDataRetriever().erasedType() } func createQuartersRetriever() -> AnyDataRetriever<[(Juz, [Quarter])]> { return QuartersDataRetriever().erasedType() } func createQuranPagesRetriever() -> AnyDataRetriever<[QuranPage]> { return QuranPagesDataRetriever().erasedType() } func createQarisDataRetriever() -> AnyDataRetriever<[Qari]> { return QariDataRetriever().erasedType() } func createAyahInfoPersistence() -> AyahInfoPersistence { return SQLiteAyahInfoPersistence() } func createAyahTextStorage() -> AyahTextPersistence { return SQLiteAyahTextPersistence() } func createAyahInfoRetriever() -> AyahInfoRetriever { return DefaultAyahInfoRetriever(persistence: createAyahInfoPersistence()) } func createQuranController(page: Int, lastPage: LastPage?) -> QuranViewController { return QuranViewController( imageService : createQuranImageService(), dataRetriever : createQuranPagesRetriever(), ayahInfoRetriever : createAyahInfoRetriever(), audioViewPresenter : createAudioBannerViewPresenter(), qarisControllerCreator : createCreator(createQariTableViewController), bookmarksPersistence : createBookmarksPersistence(), lastPagesPersistence : createLastPagesPersistence(), page : page, lastPage : lastPage ) } func createCreator<CreatedObject, Parameters>( _ creationClosure: @escaping (Parameters) -> CreatedObject) -> AnyCreator<CreatedObject, Parameters> { return AnyCreator(createClosure: creationClosure).erasedType() } func createQuranImageService() -> QuranImageService { return DefaultQuranImageService(imagesCache: createImagesCache()) } func createImagesCache() -> Cache<Int, UIImage> { return imagesCache } func createAudioBannerViewPresenter() -> AudioBannerViewPresenter { return DefaultAudioBannerViewPresenter(persistence: createSimplePersistence(), qariRetreiver: createQarisDataRetriever(), gaplessAudioPlayer: createGaplessAudioPlayerInteractor(), gappedAudioPlayer: createGappedAudioPlayerInteractor()) } func createUserDefaults() -> UserDefaults { return UserDefaults.standard } func createSimplePersistence() -> SimplePersistence { return UserDefaultsSimplePersistence(userDefaults: createUserDefaults()) } func createSuraLastAyahFinder() -> LastAyahFinder { return SuraBasedLastAyahFinder() } func createPageLastAyahFinder() -> LastAyahFinder { return PageBasedLastAyahFinder() } func createJuzLastAyahFinder() -> LastAyahFinder { return JuzBasedLastAyahFinder() } func createDownloadManager() -> DownloadManager { return downloadManager } func createGappedAudioDownloader() -> AudioFilesDownloader { return GappedAudioFilesDownloader(downloader: createDownloadManager()) } func createGaplessAudioDownloader() -> AudioFilesDownloader { return GaplessAudioFilesDownloader(downloader: createDownloadManager()) } func createGappedAudioPlayer() -> AudioPlayer { return GappedAudioPlayer() } func createGaplessAudioPlayer() -> AudioPlayer { return GaplessAudioPlayer(timingRetriever: createQariTimingRetriever()) } func createGaplessAudioPlayerInteractor() -> AudioPlayerInteractor { return GaplessAudioPlayerInteractor(downloader: createGaplessAudioDownloader(), lastAyahFinder: createJuzLastAyahFinder(), player: createGaplessAudioPlayer()) } func createGappedAudioPlayerInteractor() -> AudioPlayerInteractor { return GappedAudioPlayerInteractor(downloader: createGappedAudioDownloader(), lastAyahFinder: createJuzLastAyahFinder(), player: createGappedAudioPlayer()) } func createQariTimingRetriever() -> QariTimingRetriever { return SQLiteQariTimingRetriever(persistence: createQariAyahTimingPersistence()) } func createQariAyahTimingPersistence() -> QariAyahTimingPersistence { return SQLiteAyahTimingPersistence() } func createBookmarksPersistence() -> BookmarksPersistence { return SQLiteBookmarksPersistence() } func createLastPagesPersistence() -> LastPagesPersistence { return SQLiteLastPagesPersistence(simplePersistence: createSimplePersistence()) } }
mit
milseman/swift
test/IRGen/rdar15304329.swift
8
449
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s // REQUIRES: objc_interop // CHECK-NOT: @_TWvi{{.*}} // CHECK: _T012rdar153043293BarC3fooAA3FooVySiGvWvd // CHECK-NOT: @_TWvi{{.*}} import Foundation struct Foo<T> { var x: T } class Bar : NSObject { var foo: Foo<Int> init(foo: Foo<Int>) { self.foo = foo super.init() } }
apache-2.0
moonrailgun/OpenCode
OpenCode/Classes/RepositoryDetail/View/RepoDetailHeaderView.swift
1
5698
// // RepoDetailHeaderView.swift // OpenCode // // Created by 陈亮 on 16/5/14. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit class RepoDetailHeaderView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ var headerImgView:UIImageView? var repoNameLabel:UILabel? var repoDescLabel:UILabel? var infoBlock1:RepoInfoView? var infoBlock2:RepoInfoView? var infoBlock3:RepoInfoView? var repoDesc1:RepoDescView?//isPrivate var repoDesc2:RepoDescView?//language var repoDesc3:RepoDescView?//issues num var repoDesc4:RepoDescView?//branch num var repoDesc5:RepoDescView?//create data var repoDesc6:RepoDescView?//size override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func initView(){ let headerView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 200)) headerView.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1) headerImgView = UIImageView(frame: CGRect(x: headerView.frame.width / 2 - 50, y: 25, width: 100, height: 100)) //headerImgView!.backgroundColor = UIColor(white: 1, alpha: 1) headerView.addSubview(headerImgView!) self.repoNameLabel = UILabel(frame: CGRect(x: 0, y: 130, width: self.frame.width, height: 40)) repoNameLabel!.text = "" repoNameLabel!.textColor = UIColor(white: 1, alpha: 1) repoNameLabel!.font = UIFont(descriptor: UIFontDescriptor(), size: 20) repoNameLabel!.textAlignment = NSTextAlignment.Center headerView.addSubview(repoNameLabel!) self.repoDescLabel = UILabel(frame: CGRect(x: 0, y: 160, width: self.frame.width, height: 40)) repoDescLabel!.text = "" repoDescLabel!.numberOfLines = 2 repoDescLabel!.textColor = UIColor(white: 1, alpha: 1) repoDescLabel!.font = UIFont(descriptor: UIFontDescriptor(), size: 14) repoDescLabel!.textAlignment = NSTextAlignment.Center headerView.addSubview(repoDescLabel!) //信息部分 let infoBlockWidth = floor(frame.width / 3) let infoBlockSpace = (frame.width - infoBlockWidth * 3)/2 self.infoBlock1 = RepoInfoView(frame: CGRectMake(0, 200, infoBlockWidth, 40), name: "Stargazers", value: 1) self.infoBlock2 = RepoInfoView(frame: CGRectMake(infoBlockWidth * 1 + infoBlockSpace * 1, 200, infoBlockWidth, 40), name: "Watchers", value: 3) self.infoBlock3 = RepoInfoView(frame: CGRectMake(infoBlockWidth * 2 + infoBlockSpace * 2, 200, infoBlockWidth, 40), name: "Forks", value: 5) self.addSubview(infoBlock1!) self.addSubview(infoBlock2!) self.addSubview(infoBlock3!) //描述部分 let descStartY:CGFloat = 250 let descWidth = floor(frame.width / 2) let descHeight:CGFloat = 40 self.repoDesc1 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*0, descWidth, 40), icon: UIImage(named: "watch")!, desc: "") repoDesc1!.backgroundColor = UIColor.whiteColor() self.repoDesc2 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*0, descWidth, 40), icon: UIImage(named: "code")!, desc: "") repoDesc2!.backgroundColor = UIColor.whiteColor() self.repoDesc3 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*1, descWidth, 40), icon: UIImage(named: "comment")!, desc: "") repoDesc3!.backgroundColor = UIColor.whiteColor() self.repoDesc4 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*1, descWidth, 40), icon: UIImage(named: "fork")!, desc: "") repoDesc4!.backgroundColor = UIColor.whiteColor() self.repoDesc5 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*2, descWidth, 40), icon: UIImage(named: "tag")!, desc: "") repoDesc5!.backgroundColor = UIColor.whiteColor() self.repoDesc6 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*2, descWidth, 40), icon: UIImage(named: "repo")!, desc: "") repoDesc6!.backgroundColor = UIColor.whiteColor() self.addSubview(repoDesc1!) self.addSubview(repoDesc2!) self.addSubview(repoDesc3!) self.addSubview(repoDesc4!) self.addSubview(repoDesc5!) self.addSubview(repoDesc6!) self.addSubview(headerView) } func setData(icon:UIImage?, repoName:String?, repoDesc:String?, blockValue1:Int?, blockValue2:Int?, blockValue3:Int?){ self.headerImgView?.image = icon self.repoNameLabel?.text = repoName self.repoDescLabel?.text = repoDesc self.infoBlock1?.setValue(blockValue1!) self.infoBlock2?.setValue(blockValue2!) self.infoBlock3?.setValue(blockValue3!) } func setDescData(isPrivate:Bool, language:String, issuesNum:Int, defaultBranch:String, createdDate:String, size:Int){ self.repoDesc1?.descLabel.text = isPrivate ? "Private" : "Public" self.repoDesc2?.descLabel.text = language self.repoDesc3?.descLabel.text = "\(issuesNum) Issues" self.repoDesc4?.descLabel.text = defaultBranch self.repoDesc5?.descLabel.text = GithubTime(dateStr: createdDate).onlyDay() self.repoDesc6?.descLabel.text = size > 1024 ? "\(String(format: "%.2f", Float(size) / 1024))MB":"\(size)KB" } }
gpl-2.0
crxiaoluo/DouYuZhiBo
DYZB/DYZB/Class/Tools/Swift+Extension/Foundation/String+Extension.swift
1
2952
// // String-Extension.swift // date // // Created by Apple on 16/9/9. // Copyright © 2016年 Apple. All rights reserved. // import UIKit extension String { /** 根据日期字符串生成对应的日期格式化字符串 */ func CreateDateString () -> String { let fmt = DateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" // fmt.locale = NSLocale(localeIdentifier: "en") fmt.locale = Locale.current guard let creatDate = fmt.date(from: self) else { return "" } //获取当前时间 let nowDate = Date() //比较两个时间 let intervalDoble = (nowDate.timeIntervalSince1970 - creatDate.timeIntervalSince1970) let interval = quad_t (intervalDoble) //创建日历对象 let calender = Calendar.current let comps = (calender as NSCalendar).components(.year, from: creatDate, to: nowDate, options: []) if comps.year! < 1 { //昨天 if calender.isDateInYesterday(creatDate) { //ios 8 fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.string(from: creatDate) return timeStr }else if calender.isDateInToday(creatDate) { if interval >= 60 * 60 { //1天内 return "\(interval/(60 * 60))小时前" } if interval > 60 { //1小时内 return "\(interval / 60)分钟前" } else{ //1分钟内 return "刚刚" } }else { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.string(from: creatDate) return timeStr } }else { //超出一年 fmt.dateFormat = "yyyy-MM-dd" let timeStr = fmt.string(from: creatDate) return timeStr } } } extension String { func setSize(_ font: CGFloat , width: CGFloat , height: CGFloat) -> CGSize { let size = CGSize(width: width, height: height) let rect = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: font) ], context:nil) return rect.size } func setSize(_ font : CGFloat , width: CGFloat) -> CGSize { return setSize(font, width: width, height: CGFloat.greatestFiniteMagnitude) } func setSize(_ font : CGFloat) -> CGSize { return setSize(font, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) } }
mit
sarukun99/CoreStore
CoreStore/Convenience Helpers/NSProgress+Convenience.swift
1
4058
// // NSProgress+Convenience.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - NSProgress public extension NSProgress { // MARK: Public /** Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO. - parameter closure: the closure to execute on progress change */ public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) { self.progressObserver.progressHandler = closure } // MARK: Private private struct PropertyKeys { static var progressObserver: Void? } private var progressObserver: ProgressObserver { get { let object: ProgressObserver? = getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self) if let observer = object { return observer } let observer = ProgressObserver(self) setAssociatedRetainedObject( observer, forKey: &PropertyKeys.progressObserver, inObject: self ) return observer } } } @objc private final class ProgressObserver: NSObject { private unowned let progress: NSProgress private var progressHandler: ((progress: NSProgress) -> Void)? { didSet { let progressHandler = self.progressHandler if (progressHandler == nil) == (oldValue == nil) { return } if let _ = progressHandler { self.progress.addObserver( self, forKeyPath: "fractionCompleted", options: [.Initial, .New], context: nil ) } else { self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } } private init(_ progress: NSProgress) { self.progress = progress super.init() } deinit { if let _ = self.progressHandler { self.progressHandler = nil self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else { return } GCDQueue.Main.async { [weak self] () -> Void in self?.progressHandler?(progress: progress) } } }
mit
iOS-Swift-Developers/Swift
基础语法/枚举/main.swift
1
3993
// // main.swift // 枚举 // // Created by 韩俊强 on 2017/6/12. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* Swift枚举: Swift中的枚举比OC中的枚举强大, 因为Swift中的枚举是一等类型, 它可以像类和结构体一样增加属性和方法 格式: enum Method{ case 枚举值 } */ enum Method { case Add case Sub case Mul case Div //可以连在一起写 // case Add, Sub, Mul, Div } // 可以使用枚举类型变量或者常量接收枚举值 var m:Method = .Add print(m) // 注意: 如果变量或者常量没有指定类型, 那么前面必须加上该值属于哪个枚举类型 var m1 = Method.Add print(m1) // 利用Switch匹配 // 注意: 如果case中包含了所有的值, 可以不写default; 如果case没有包含枚举中所有的值, 必须写default switch (Method.Add){ case Method.Add: print("加法") case Method.Sub: print("减法") case Method.Mul: print("除法") case Method.Div: print("乘法") //default: // print("都不是") } /* 原始值: OC中枚举的本质就是整数,所以OC中的枚举是有原始值的,默认是从0开始 而Swift中的枚举默认是没有原始值的, 但是可以在定义时告诉系统让枚举有原始值 enum Method: 枚举值原始值类型{ case 枚举值 } */ enum Method2: Int { case Add, Sub, Mul, Div } // 和OC中的枚举一样, 也可以指定原始值, 后面的值默认 +1 enum Method3: Int { case Add = 5, Sub, Mul, Div } // Swift中的枚举除了可以指定整型以外还可以指定其他类型, 但是如果指定其他类型, 必须给所有枚举值赋值, 因为不能自动递增 enum Method4: Double { case Add = 5.0, Sub = 6.0, Mul = 7.0, Div = 8.0 } // rawValue代表将枚举值转换为原始值, 注意老版本中转换为原始值的方法名叫toRaw // 最新的Swift版本不再支持toRaw和fromRaw了,只有rawValue属性和hashValue属性了! print(Method4.Sub.rawValue) // hashValue来访问成员值所对应的哈希值,这个哈希值是不能改变的,由编译器自动生成,之后不可改变,Swift在背后实际上使用哈希值来识别枚举符号的(即成员) print(Method4.Mul.hashValue) // 原始值转换为枚举值 enum Method5: String { case Add = "add", Sub = "sub", Mul = "mul", Div = "div" } // 通过原始值创建枚举值 /* 注意: 1.原始值区分大小写 2.返回的是一个可选值,因为原始值对应的枚举值不一定存在 3.老版本中为fromRaw("add") */ let m2:Method5 = Method5(rawValue: "add")! print(m2) //func chooseMethod(op:Method2) func chooseMethod5(rawString: String) { // 由于返回值是可选类型, 所以有可能为nil, 最好使用可选绑定 if let opE = Method5(rawValue: rawString) { switch (opE) { case .Add: print("加法") case .Sub: print("减法") case .Mul: print("除法") case .Div: print("乘法") } } } print(chooseMethod5(rawString: "add")) /* 枚举相关值: 可以让枚举值对应的原始值不是唯一的, 而是一个变量. 每一个枚举可以是在某种模式下的一些特定值 */ enum lineSegmentDescriptor { case StartAndEndPattern(start: Double, end: Double) case StartAndLengthPattern(start: Double, length: Double) } var lsd = lineSegmentDescriptor.StartAndLengthPattern(start: 0.0, length: 100.0) lsd = lineSegmentDescriptor.StartAndEndPattern(start: 0.0, end: 50.0) print(lsd) // 利用switch提取枚举关联值 /* switch lsd { case .StartAndEndPattern(let s, let e): print("start = \(s) end = \(e)") case .StartAndLengthPattern(let s, let l): print("start = \(s) lenght = \(l)") } */ // 提取关联值优化写法 switch lsd { case let .StartAndEndPattern(s, e): print("start = \(s) end = \(e)") case .StartAndLengthPattern(let s, let l): print("start = \(s) l = \(l)") }
mit
StevenUpForever/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/CLIBootstrapper.swift
2
3926
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl @objc open class CLIBootstrapper : NSObject { open static func bootstrap() -> Int32 { let arguments = Array(CommandLine.arguments.dropFirst(1)) let environment = ProcessInfo.processInfo.environment let (cli, writer, reporter, _) = CLI.fromArguments(arguments, environment: environment).bootstrap() return CLIRunner(cli: cli, writer: writer, reporter: reporter).runForStatus() } } struct CLIRunner : Runner { let cli: CLI let writer: Writer let reporter: EventReporter func run() -> CommandResult { switch self.cli { case .run(let command): return BaseCommandRunner(reporter: self.reporter, command: command).run() case .show(let help): return HelpRunner(reporter: self.reporter, help: help).run() case .print(let action): return PrintRunner(action: action, writer: self.writer).run() } } func runForStatus() -> Int32 { // Start the runner let result = self.run() // Now we're done. Terminate any remaining asynchronous work for handle in result.handles { handle.terminate() } switch result.outcome { case .failure(let message): self.reporter.reportError(message) return 1 case .success(.some(let subject)): self.reporter.report(subject) fallthrough default: return 0 } } } struct PrintRunner : Runner { let action: Action let writer: Writer func run() -> CommandResult { switch self.action { case .core(let action): let output = action.printable() self.writer.write(output) return .success(nil) default: break } return .failure("Action \(self.action) not printable") } } extension CLI { struct CLIError : Error, CustomStringConvertible { let description: String } public static func fromArguments(_ arguments: [String], environment: [String : String]) -> CLI { do { let (_, cli) = try CLI.parser.parse(arguments) return cli.appendEnvironment(environment) } catch let error as (CustomStringConvertible & Error) { let help = Help(outputOptions: OutputOptions(), error: error, command: nil) return CLI.show(help) } catch { let error = CLIError(description: "An Unknown Error Occurred") let help = Help(outputOptions: OutputOptions(), error: error, command: nil) return CLI.show(help) } } public func bootstrap() -> (CLI, Writer, EventReporter, FBControlCoreLoggerProtocol) { let writer = self.createWriter() let reporter = self.createReporter(writer) if case .run(let command) = self { let configuration = command.configuration let debugEnabled = configuration.outputOptions.contains(OutputOptions.DebugLogging) let bridge = ControlCoreLoggerBridge(reporter: reporter) let logger = LogReporter(bridge: bridge, debug: debugEnabled) FBControlCoreGlobalConfiguration.defaultLogger = logger return (self, writer, reporter, logger) } let logger = FBControlCoreGlobalConfiguration.defaultLogger return (self, writer, reporter, logger) } private func createWriter() -> Writer { switch self { case .show: return FileHandleWriter.stdErrWriter case .print: return FileHandleWriter.stdOutWriter case .run(let command): return command.createWriter() } } } extension Command { func createWriter() -> Writer { for action in self.actions { if case .stream = action { return FileHandleWriter.stdErrWriter } } return FileHandleWriter.stdOutWriter } }
bsd-3-clause
beobyte/UpdateLocStrings
UpdateLocStringsTests/StringsFileParserTests.swift
1
1105
// // StringsFileParserTests.swift // UpdateLocStrings // // Created by Anton Grachev on 08/07/2017. // Copyright © 2017 Anton Grachev. All rights reserved. // import XCTest class StringsFileParserTests: XCTestCase { func testParse() { let path = TestDataSource.pathForTestDataResource(TestDataSource.stringsResource, ofType: TestDataSource.stringsType) guard let stringsFilePath = path else { XCTFail() return } let localizedStrings: [LocalizedString] do { localizedStrings = try StringsFileParser.parse(contentOf: stringsFilePath) } catch { localizedStrings = [] XCTFail() } XCTAssertTrue(localizedStrings.count > 0) let firstString = localizedStrings.first! XCTAssertTrue(firstString.comment == "Comment for first string") XCTAssertTrue(firstString.key == "testString.1") XCTAssertTrue(firstString.value == "first string") } }
mit
SlackKit/SKServer
Sources/SKServer/Model/WebhookRequest.swift
3
2253
// // WebhookRequest.swift // // Copyright © 2017 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct WebhookRequest { public let token: String? public let teamID: String? public let teamDomain: String? public let channelID: String? public let channelName: String? public let ts: String? public let userID: String? public let userName: String? public let command: String? public let text: String? public let triggerWord: String? public let responseURL: String? internal init(request: [String: Any]?) { token = request?["token"] as? String teamID = request?["team_id"] as? String teamDomain = request?["team_domain"] as? String channelID = request?["channel_id"] as? String channelName = request?["channel_name"] as? String ts = request?["timestamp"] as? String userID = request?["user_id"] as? String userName = request?["user_name"] as? String command = request?["command"] as? String text = request?["text"] as? String triggerWord = request?["trigger_word"] as? String responseURL = request?["response_url"] as? String } }
mit
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Entities/UserEntity.swift
2
4784
// // UserEntity.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 18/10/2016. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kUserUserIdKey: String = "userId" let kUserTokenKey: String = "token" let kUserSalutationKey: String = "salutation" let kUserFirstNameKey: String = "firstName" let kUserLastNameKey: String = "lastName" let kUserAddressKey: String = "address" let kUserAddressOptionalKey: String = "addressOptional" let kUserZipCodeKey: String = "zipCode" let kUserCountryCodeKey: String = "countryCode" let kUserStateCodeKey: String = "stateCode" let kUserCityKey: String = "city" let kUserEmailKey: String = "email" let kUserPhoneKey: String = "phone" let kUserPasswordKey: String = "password" protocol UserEntityProtocol: ParsableEntityProtocol { var userId: String! {get set} var token: String? {get set} var salutation: String! {get set} var firstName: String! {get set} var lastName: String! {get set} var address: String! {get set} var addressOptional: String? {get set} var zipCode: String! {get set} var countryCode: String! {get set} var stateCode: String! {get set} var city: String! {get set} var phone: String! {get set} var email: String! {get set} var password: String? {get set} } class UserEntity: UserEntityProtocol { // MARK: UserEntityProtocol var userId: String! var token: String? var salutation: String! var firstName: String! var lastName: String! var address: String! var addressOptional: String? var zipCode: String! var countryCode: String! var stateCode: String! var city: String! var phone: String! var email: String! var password: String? required init (){ // ... } required init(dict: Dictionary <String, Any>) { self.userId = dict[kUserUserIdKey] as! String! self.salutation = dict[kUserSalutationKey] as! String! self.firstName = dict[kUserFirstNameKey] as! String! self.lastName = dict[kUserLastNameKey] as! String! self.address = dict[kUserAddressKey] as! String! if let addr = dict[kUserAddressOptionalKey] as? String { self.addressOptional = addr } self.zipCode = dict[kUserZipCodeKey] as! String! self.city = dict[kUserCityKey] as! String! self.countryCode = dict[kUserCountryCodeKey] as! String! self.stateCode = dict[kUserStateCodeKey] as! String! self.phone = dict[kUserPhoneKey] as! String! self.email = dict[kUserEmailKey] as! String! self.token = dict[kUserTokenKey] as! String? } func serializedDict()-> Dictionary <String, Any>? { var dict:Dictionary <String, Any>? = Dictionary() // dict? unwraps dictionary into value, and then ? (Optional chaining) makes sure setValue on dictionary is called when dict is not nill only. dict?[kUserUserIdKey] = userId dict?[kUserSalutationKey] = salutation dict?[kUserFirstNameKey] = firstName dict?[kUserLastNameKey] = lastName dict?[kUserAddressKey] = address dict?[kUserAddressOptionalKey] = addressOptional dict?[kUserZipCodeKey] = zipCode dict?[kUserCityKey] = city dict?[kUserCountryCodeKey] = countryCode dict?[kUserStateCodeKey] = stateCode dict?[kUserPhoneKey] = phone dict?[kUserEmailKey] = email dict?[kUserPasswordKey] = password return dict //return ["test":"test"] } }
mit
HabitRPG/habitrpg-ios
HabiticaTests/UI/Challenges/ChallengeDetailsSpecs.swift
1
3798
// // ChallengeDetailsSpecs.swift // HabiticaTests // // Created by Elliot Schrock on 10/28/17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import Foundation import Quick import Nimble @testable import Habitica import Habitica_Models class ChallengeDetailsViewModelSpec: QuickSpec { var challenge: ChallengeProtocol? override func spec() { describe("challenge details view model") { /*beforeEach { self.challenge = NSEntityDescription.insertNewObject(forEntityName: "Challenge", into: HRPGManager.shared().getManagedObjectContext()) as! Challenge } context("button cell") { it("allows joining") { let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.joinLeaveStyleProvider.buttonStateSignal.observeValues({ (state) in expect(state).to(equal(ChallengeButtonState.join)) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } it("allows leaving") { self.challenge.user = NSEntityDescription.insertNewObject(forEntityName: "User", into: HRPGManager.shared().getManagedObjectContext()) as! User let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.joinLeaveStyleProvider.buttonStateSignal.observeValues({ (state) in expect(state).to(equal(ChallengeButtonState.leave)) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) }*/ //TODO: Re enable once creator mode is in /* context("when has tasks") { it("allows publishing") { self.challenge.dailies = [ NSEntityDescription.insertNewObject(forEntityName: "ChallengeTask", into: HRPGManager.shared().getManagedObjectContext()) as! ChallengeTask] let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.publishStyleProvider.enabledSignal.observeValues({ (isEnabled) in expect(isEnabled).to(beTrue()) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } } context("when no tasks") { it("doesn't allow publishing") { let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.publishStyleProvider.enabledSignal.observeValues({ (isEnabled) in expect(isEnabled).to(beFalse()) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } } }*/ context("creator cell") { } } } }
gpl-3.0
apple/swift-syntax
Sources/SwiftParser/Expressions.swift
1
90746
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension TokenConsumer { func atStartOfExpression() -> Bool { switch self.at(anyIn: ExpressionStart.self) { case (.awaitTryMove, let handle)?: var backtrack = self.lookahead() backtrack.eat(handle) if backtrack.atStartOfDeclaration() || backtrack.atStartOfStatement() { // If after the 'try' we are at a declaration or statement, it can't be a valid expression. // Decide how we want to consume the 'try': // If the declaration or statement starts at a new line, the user probably just forgot to write the expression after 'try' -> parse it as a TryExpr // If the declaration or statement starts at the same line, the user maybe tried to use 'try' as a modifier -> parse it as unexpected text in front of that decl or stmt. return backtrack.currentToken.isAtStartOfLine } else { return true } case (_, _)?: return true case nil: break } if self.at(.atSign) || self.at(.inoutKeyword) { var backtrack = self.lookahead() if backtrack.canParseType() { return true } } return false } } extension Parser { public enum ExprFlavor { case basic case trailingClosure } public enum PatternContext { /// There is no ambient pattern context. case none /// We're parsing a matching pattern that is not introduced via `let` or `var`. /// /// In this context, identifiers are references to the enclosing scopes, not a variable binding. /// /// ``` /// case x.y <- 'x' must refer to some 'x' defined in another scope, it cannot be e.g. an enum type. /// ``` case matching /// We're parsing a matching pattern that is introduced via `let` or `var`. /// /// ``` /// case let x.y <- 'x' must refer to the base of some member access, y must refer to some pattern-compatible identfier /// ``` case letOrVar var admitsBinding: Bool { switch self { case .letOrVar: return true case .none, .matching: return false } } } /// Parse an expression. /// /// Grammar /// ======= /// /// expression → try-operator? await-operator? prefix-expression infix-expressions? /// expression-list → expression | expression ',' expression-list @_spi(RawSyntax) public mutating func parseExpression(_ flavor: ExprFlavor = .trailingClosure, pattern: PatternContext = .none) -> RawExprSyntax { // If we are parsing a refutable pattern, check to see if this is the start // of a let/var/is pattern. If so, parse it as an UnresolvedPatternExpr and // let pattern type checking determine its final form. // // Only do this if we're parsing a pattern, to improve QoI on malformed // expressions followed by (e.g.) let/var decls. if pattern != .none, self.at(anyIn: MatchingPatternStart.self) != nil { let pattern = self.parseMatchingPattern(context: .matching) return RawExprSyntax(RawUnresolvedPatternExprSyntax(pattern: pattern, arena: self.arena)) } return RawExprSyntax(self.parseSequenceExpression(flavor, pattern: pattern)) } } extension Parser { /// Parse a sequence of expressions. /// /// Grammar /// ======= /// /// infix-expression → infix-operator prefix-expression /// infix-expression → assignment-operator try-operator? prefix-expression /// infix-expression → conditional-operator try-operator? prefix-expression /// infix-expression → type-casting-operator /// infix-expressions → infix-expression infix-expressions? @_spi(RawSyntax) public mutating func parseSequenceExpression( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { if forDirective && self.currentToken.isAtStartOfLine { return RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } // Parsed sequence elements except 'lastElement'. var elements = [RawExprSyntax]() // The last element parsed. we don't eagarly append to 'elements' because we // don't want to populate the 'Array' unless the expression is actually // sequenced. var lastElement: RawExprSyntax lastElement = self.parseSequenceExpressionElement(flavor, forDirective: forDirective, pattern: pattern) var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { guard !lastElement.is(RawMissingExprSyntax.self), !(forDirective && self.currentToken.isAtStartOfLine) else { break } // Parse the operator. guard let (operatorExpr, rhsExpr) = self.parseSequenceExpressionOperator(flavor, pattern: pattern) else { // Not an operator. We're done. break } elements.append(lastElement) elements.append(operatorExpr) if let rhsExpr = rhsExpr { // Operator parsing returned the RHS. lastElement = rhsExpr } else if forDirective && self.currentToken.isAtStartOfLine { // Don't allow RHS at a newline for `#if` conditions. lastElement = RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) break } else { lastElement = self.parseSequenceExpressionElement(flavor, forDirective: forDirective, pattern: pattern) } } // There was no operators. Return the only element we parsed. if elements.isEmpty { return lastElement } assert(elements.count.isMultiple(of: 2), "elements must have a even number of elements") elements.append(lastElement) return RawExprSyntax(RawSequenceExprSyntax( elements: RawExprListSyntax(elements: elements, arena: self.arena), arena: self.arena)) } /// Parse an expression sequence operators. /// /// Returns `nil` if the current token is not at an operator. /// Returns a tuple of an operator expression and a optional right operand /// expression. The right operand is only returned if it is not a common /// sequence element. /// /// Grammar /// ======= /// /// infix-operator → operator /// assignment-operator → '=' /// conditional-operator → '?' expression ':' /// type-casting-operator → 'is' type /// type-casting-operator → 'as' type /// type-casting-operator → 'as' '?' type /// type-casting-operator → 'as' '!' type /// arrow-operator -> 'async' '->' /// arrow-operator -> 'throws' '->' /// arrow-operator -> 'async' 'throws' '->' mutating func parseSequenceExpressionOperator( _ flavor: ExprFlavor, pattern: PatternContext ) -> (operator: RawExprSyntax, rhs: RawExprSyntax?)? { enum ExpectedTokenKind: RawTokenKindSubset { case spacedBinaryOperator case unspacedBinaryOperator case infixQuestionMark case equal case isKeyword case asKeyword case async case arrow case throwsKeyword init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .spacedBinaryOperator: self = .spacedBinaryOperator case .unspacedBinaryOperator: self = .unspacedBinaryOperator case .infixQuestionMark: self = .infixQuestionMark case .equal: self = .equal case .isKeyword: self = .isKeyword case .asKeyword: self = .asKeyword case .identifier where lexeme.tokenText == "async": self = .async case .arrow: self = .arrow case .throwsKeyword: self = .throwsKeyword default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .spacedBinaryOperator: return .spacedBinaryOperator case .unspacedBinaryOperator: return .unspacedBinaryOperator case .infixQuestionMark: return .infixQuestionMark case .equal: return .equal case .isKeyword: return .isKeyword case .asKeyword: return .asKeyword case .async: return .identifier case .arrow: return .arrow case .throwsKeyword: return .throwsKeyword } } var contextualKeyword: SyntaxText? { switch self { case .async: return "async" default: return nil } } } switch self.at(anyIn: ExpectedTokenKind.self) { case (.spacedBinaryOperator, let handle)?, (.unspacedBinaryOperator, let handle)?: // Parse the operator. let operatorToken = self.eat(handle) let op = RawBinaryOperatorExprSyntax(operatorToken: operatorToken, arena: arena) return (RawExprSyntax(op), nil) case (.infixQuestionMark, let handle)?: // Save the '?'. let question = self.eat(handle) let firstChoice = self.parseSequenceExpression(flavor, pattern: pattern) // Make sure there's a matching ':' after the middle expr. let (unexpectedBeforeColon, colon) = self.expect(.colon) let op = RawUnresolvedTernaryExprSyntax( questionMark: question, firstChoice: firstChoice, unexpectedBeforeColon, colonMark: colon, arena: self.arena) let rhs: RawExprSyntax? if colon.isMissing { // If the colon is missing there's not much more structure we can // expect out of this expression sequence. Emit a missing expression // to end the parsing here. rhs = RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } else { rhs = nil } return (RawExprSyntax(op), rhs) case (.equal, let handle)?: switch pattern { case .matching, .letOrVar: return nil case .none: let eq = self.eat(handle) let op = RawAssignmentExprSyntax( assignToken: eq, arena: self.arena ) return (RawExprSyntax(op), nil) } case (.isKeyword, let handle)?: let isKeyword = self.eat(handle) let op = RawUnresolvedIsExprSyntax( isTok: isKeyword, arena: self.arena ) // Parse the right type expression operand as part of the 'is' production. let type = self.parseType() let rhs = RawTypeExprSyntax(type: type, arena: self.arena) return (RawExprSyntax(op), RawExprSyntax(rhs)) case (.asKeyword, let handle)?: let asKeyword = self.eat(handle) let failable = self.consume(ifAny: [.postfixQuestionMark, .exclamationMark]) let op = RawUnresolvedAsExprSyntax( asTok: asKeyword, questionOrExclamationMark: failable, arena: self.arena ) // Parse the right type expression operand as part of the 'as' production. let type = self.parseType() let rhs = RawTypeExprSyntax(type: type, arena: self.arena) return (RawExprSyntax(op), RawExprSyntax(rhs)) case (.async, _)?: if self.peek().tokenKind == .arrow || self.peek().tokenKind == .throwsKeyword { fallthrough } else { return nil } case (.arrow, _)?, (.throwsKeyword, _)?: var asyncKeyword = self.consumeIfContextualKeyword("async") var throwsKeyword = self.consume(if: .throwsKeyword) let (unexpectedBeforeArrow, arrow) = self.expect(.arrow) // Recover if effect modifiers are specified after '->' by eating them into // unexpectedAfterArrow and inserting the corresponding effects modifier as // missing into the ArrowExprSyntax. This reflect the semantics the user // originally intended. var effectModifiersAfterArrow: [RawTokenSyntax] = [] if let asyncAfterArrow = self.consumeIfContextualKeyword("async") { effectModifiersAfterArrow.append(asyncAfterArrow) if asyncKeyword == nil { asyncKeyword = missingToken(.contextualKeyword, text: "async") } } if let throwsAfterArrow = self.consume(if: .throwsKeyword) { effectModifiersAfterArrow.append(throwsAfterArrow) if throwsKeyword == nil { throwsKeyword = missingToken(.throwsKeyword, text: nil) } } let unexpectedAfterArrow = effectModifiersAfterArrow.isEmpty ? nil : RawUnexpectedNodesSyntax( elements: effectModifiersAfterArrow.map { RawSyntax($0) }, arena: self.arena ) let op = RawArrowExprSyntax( asyncKeyword: asyncKeyword, throwsToken: throwsKeyword, unexpectedBeforeArrow, arrowToken: arrow, unexpectedAfterArrow, arena: self.arena ) return (RawExprSyntax(op), nil) case nil: // Not an operator. return nil } } /// Parse an expression sequence element. /// /// Grammar /// ======= /// /// expression → try-operator? await-operator? prefix-expression infix-expressions? /// expression-list → expression | expression ',' expression-list @_spi(RawSyntax) public mutating func parseSequenceExpressionElement( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { // Try to parse '@' sign or 'inout' as a attributed typerepr. if self.at(any: [.atSign, .inoutKeyword]) { var backtrack = self.lookahead() if backtrack.canParseType() { let type = self.parseType() return RawExprSyntax(RawTypeExprSyntax(type: type, arena: self.arena)) } } switch self.at(anyIn: AwaitTryMove.self) { case (.awaitContextualKeyword, let handle)?: let awaitTok = self.eat(handle) let sub = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawAwaitExprSyntax( awaitKeyword: awaitTok, expression: sub, arena: self.arena )) case (.tryKeyword, let handle)?: let tryKeyword = self.eat(handle) let mark = self.consume(ifAny: [.exclamationMark, .postfixQuestionMark]) let expression = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawTryExprSyntax( tryKeyword: tryKeyword, questionOrExclamationMark: mark, expression: expression, arena: self.arena )) case (._moveContextualKeyword, let handle)?: let moveTok = self.eat(handle) let sub = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawMoveExprSyntax( moveKeyword: moveTok, expression: sub, arena: self.arena)) case nil: return self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) } } /// Parse an optional prefix operator followed by an expression. /// /// Grammar /// ======= /// /// prefix-expression → prefix-operator? postfix-expression /// prefix-expression → in-out-expression /// /// in-out-expression → '&' identifier @_spi(RawSyntax) public mutating func parseUnaryExpression( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { // First check to see if we have the start of a regex literal `/.../`. // tryLexRegexLiteral(/*forUnappliedOperator*/ false) switch self.at(anyIn: ExpressionPrefixOperator.self) { case (.prefixAmpersand, let handle)?: let amp = self.eat(handle) let expr = self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawInOutExprSyntax( ampersand: amp, expression: RawExprSyntax(expr), arena: self.arena )) case (.backslash, _)?: return RawExprSyntax(self.parseKeyPathExpression(forDirective: forDirective, pattern: pattern)) case (.prefixOperator, let handle)?: let op = self.eat(handle) let postfix = self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawPrefixOperatorExprSyntax( operatorToken: op, postfixExpression: postfix, arena: self.arena )) default: // If the next token is not an operator, just parse this as expr-postfix. return self.parsePostfixExpression( flavor, forDirective: forDirective, pattern: pattern) } } /// Parse a postfix expression applied to another expression. /// /// Grammar /// ======= /// /// postfix-expression → primary-expression /// postfix-expression → postfix-expression postfix-operator /// postfix-expression → function-call-expression /// postfix-expression → initializer-expression /// postfix-expression → explicit-member-expression /// postfix-expression → postfix-self-expression /// postfix-expression → subscript-expression /// postfix-expression → forced-value-expression /// postfix-expression → optional-chaining-expression @_spi(RawSyntax) public mutating func parsePostfixExpression( _ flavor: ExprFlavor, forDirective: Bool, pattern: PatternContext ) -> RawExprSyntax { let head = self.parsePrimaryExpression(pattern: pattern, flavor: flavor) guard !head.is(RawMissingExprSyntax.self) else { return head } return self.parsePostfixExpressionSuffix( head, flavor, forDirective: forDirective, pattern: pattern) } @_spi(RawSyntax) public mutating func parseDottedExpressionSuffix() -> ( period: RawTokenSyntax, name: RawTokenSyntax, declNameArgs: RawDeclNameArgumentsSyntax?, generics: RawGenericArgumentClauseSyntax? ) { assert(self.at(any: [.period, .prefixPeriod])) let period = self.consumeAnyToken(remapping: .period) // Parse the name portion. let name: RawTokenSyntax let declNameArgs: RawDeclNameArgumentsSyntax? if let index = self.consume(if: .integerLiteral) { // Handle "x.42" - a tuple index. name = index declNameArgs = nil } else if let selfKeyword = self.consume(if: .selfKeyword) { // Handle "x.self" expr. name = selfKeyword declNameArgs = nil } else { // Handle an arbitrary declararion name. (name, declNameArgs) = self.parseDeclNameRef([.keywords, .compoundNames]) } // Parse the generic arguments, if any. let generics: RawGenericArgumentClauseSyntax? if self.lookahead().canParseAsGenericArgumentList() { generics = self.parseGenericArguments() } else { generics = nil } return (period, name, declNameArgs, generics) } @_spi(RawSyntax) public mutating func parseDottedExpressionSuffix(_ start: RawExprSyntax?) -> RawExprSyntax { let (period, name, declNameArgs, generics) = parseDottedExpressionSuffix() let memberAccess = RawMemberAccessExprSyntax( base: start, dot: period, name: name, declNameArguments: declNameArgs, arena: self.arena) guard let generics = generics else { return RawExprSyntax(memberAccess) } return RawExprSyntax(RawSpecializeExprSyntax( expression: RawExprSyntax(memberAccess), genericArgumentClause: generics, arena: self.arena)) } @_spi(RawSyntax) public mutating func parseIfConfigExpressionSuffix( _ start: RawExprSyntax?, _ flavor: ExprFlavor, forDirective: Bool ) -> RawExprSyntax { assert(self.at(.poundIfKeyword)) let config = self.parsePoundIfDirective { parser -> RawExprSyntax? in let head: RawExprSyntax if parser.at(any: [.period, .prefixPeriod]) { head = parser.parseDottedExpressionSuffix(nil) } else if parser.at(.poundIfKeyword) { head = parser.parseIfConfigExpressionSuffix(nil, flavor, forDirective: forDirective) } else { // TODO: diagnose and skip. return nil } let result = parser.parsePostfixExpressionSuffix( head, flavor, forDirective: forDirective, pattern: .none ) // TODO: diagnose and skip the remaining token in the current clause. return result } syntax: { (parser, elements) -> RawIfConfigClauseSyntax.Elements? in switch elements.count { case 0: return nil case 1: return .postfixExpression(elements.first!) default: fatalError("Postfix #if should only have one element") } } return RawExprSyntax(RawPostfixIfConfigExprSyntax( base: start, config: config, arena: self.arena)) } /// Parse the suffix of a postfix expression. /// /// Grammar /// ======= /// /// postfix-expression → postfix-expression postfix-operator /// postfix-expression → function-call-expression /// postfix-expression → initializer-expression /// postfix-expression → explicit-member-expression /// postfix-expression → postfix-self-expression /// postfix-expression → subscript-expression /// postfix-expression → forced-value-expression /// postfix-expression → optional-chaining-expression @_spi(RawSyntax) public mutating func parsePostfixExpressionSuffix( _ start: RawExprSyntax, _ flavor: ExprFlavor, forDirective: Bool, pattern: PatternContext ) -> RawExprSyntax { // Handle suffix expressions. var leadingExpr = start var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { if forDirective && self.currentToken.isAtStartOfLine { return leadingExpr } // Check for a .foo suffix. if self.at(any: [.period, .prefixPeriod]) { leadingExpr = self.parseDottedExpressionSuffix(leadingExpr) continue } // If there is an expr-call-suffix, parse it and form a call. if let lparen = self.consume(if: .leftParen, where: { !$0.isAtStartOfLine }) { let args = self.parseArgumentListElements(pattern: pattern) let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } leadingExpr = RawExprSyntax(RawFunctionCallExprSyntax( calledExpression: leadingExpr, leftParen: lparen, argumentList: RawTupleExprElementListSyntax(elements: args, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena)) continue } // Check for a [expr] suffix. // Note that this cannot be the start of a new line. if let lsquare = self.consume(if: .leftSquareBracket, where: { !$0.isAtStartOfLine }) { let args: [RawTupleExprElementSyntax] if self.at(.rightSquareBracket) { args = [] } else { args = self.parseArgumentListElements(pattern: pattern) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } leadingExpr = RawExprSyntax(RawSubscriptExprSyntax( calledExpression: leadingExpr, leftBracket: lsquare, argumentList: RawTupleExprElementListSyntax(elements: args, arena: self.arena), unexpectedBeforeRSquare, rightBracket: rsquare, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena)) continue } // Check for a trailing closure, if allowed. if self.at(.leftBrace) && self.lookahead().isValidTrailingClosure(flavor) { // FIXME: if Result has a trailing closure, break out. // Add dummy blank argument list to the call expression syntax. let list = RawTupleExprElementListSyntax(elements: [], arena: self.arena) let (first, rest) = self.parseTrailingClosures(flavor) leadingExpr = RawExprSyntax(RawFunctionCallExprSyntax( calledExpression: leadingExpr, leftParen: nil, argumentList: list, rightParen: nil, trailingClosure: first, additionalTrailingClosures: rest, arena: self.arena)) // We only allow a single trailing closure on a call. This could be // generalized in the future, but needs further design. if self.at(.leftBrace) { break } continue } // Check for a ? suffix. if let question = self.consume(if: .postfixQuestionMark) { leadingExpr = RawExprSyntax(RawOptionalChainingExprSyntax( expression: leadingExpr, questionMark: question, arena: self.arena)) continue } // Check for a ! suffix. if let exlaim = self.consume(if: .exclamationMark) { leadingExpr = RawExprSyntax(RawForcedValueExprSyntax( expression: leadingExpr, exclamationMark: exlaim, arena: self.arena)) continue } // Check for a postfix-operator suffix. if let op = self.consume(if: .postfixOperator) { leadingExpr = RawExprSyntax(RawPostfixUnaryExprSyntax( expression: leadingExpr, operatorToken: op, arena: self.arena )) continue } if self.at(.poundIfKeyword) { // Check if the first '#if' body starts with '.' <identifier>, and parse // it as a "postfix ifconfig expression". do { var backtrack = self.lookahead() // Skip to the first body. We may need to skip multiple '#if' directives // since we support nested '#if's. e.g. // baseExpr // #if CONDITION_1 // #if CONDITION_2 // .someMember var loopProgress = LoopProgressCondition() repeat { backtrack.eat(.poundIfKeyword) while !backtrack.at(.eof) && !backtrack.currentToken.isAtStartOfLine { backtrack.skipSingle() } } while backtrack.at(.poundIfKeyword) && loopProgress.evaluate(backtrack.currentToken) guard backtrack.isAtStartOfPostfixExprSuffix() else { break } } leadingExpr = self.parseIfConfigExpressionSuffix( leadingExpr, flavor, forDirective: forDirective) continue } // Otherwise, we don't know what this token is, it must end the expression. break } return leadingExpr } } extension Parser { /// Determine if this is a key path postfix operator like ".?!?". private func getNumOptionalKeyPathPostfixComponents( _ tokenText: SyntaxText ) -> Int? { // Make sure every character is ".", "!", or "?", without two "."s in a row. var numComponents = 0 var lastWasDot = false for byte in tokenText { if byte == UInt8(ascii: ".") { if lastWasDot { return nil } lastWasDot = true continue } if byte == UInt8(ascii: "!") || byte == UInt8(ascii: "?") { lastWasDot = false numComponents += 1 continue } return nil } return numComponents } /// Consume the optional key path postfix ino a set of key path components. private mutating func consumeOptionalKeyPathPostfix( numComponents: Int ) -> [RawKeyPathComponentSyntax] { var components: [RawKeyPathComponentSyntax] = [] for _ in 0..<numComponents { // Consume a period, if there is one. let period: RawTokenSyntax? if self.currentToken.starts(with: ".") { period = self.consumePrefix(".", as: .period) } else { period = nil } // Consume the '!' or '?'. let questionOrExclaim: RawTokenSyntax if self.currentToken.starts(with: "!") { questionOrExclaim = self.consumePrefix("!", as: .exclamationMark) } else { assert(self.currentToken.starts(with: "?")) questionOrExclaim = self.consumePrefix("?", as: .postfixQuestionMark) } components.append(RawKeyPathComponentSyntax( period: period, component: .optional(RawKeyPathOptionalComponentSyntax( questionOrExclamationMark: questionOrExclaim, arena: self.arena)), arena: self.arena)) } return components } /// Parse a keypath expression. /// /// Grammar /// ======= /// /// key-path-expression → '\' type? '.' key-path-components /// /// key-path-components → key-path-component | key-path-component '.' key-path-components /// key-path-component → identifier key-path-postfixes? | key-path-postfixes /// /// key-path-postfixes → key-path-postfix key-path-postfixes? /// key-path-postfix → '?' | '!' | 'self' | '[' function-call-argument-list ']' @_spi(RawSyntax) public mutating func parseKeyPathExpression(forDirective: Bool, pattern: PatternContext) -> RawKeyPathExprSyntax { // Consume '\'. let (unexpectedBeforeBackslash, backslash) = self.expect(.backslash) // For uniformity, \.foo is parsed as if it were MAGIC.foo, so we need to // make sure the . is there, but parsing the ? in \.? as .? doesn't make // sense. This is all made more complicated by .?. being considered an // operator token. Since keypath allows '.!' '.?' and '.[', consume '.' // the token is a operator starts with '.', or the following token is '['. let rootType: RawTypeSyntax? if !self.currentToken.starts(with: ".") { rootType = self.parseSimpleType(stopAtFirstPeriod: true) } else { rootType = nil } var components: [RawKeyPathComponentSyntax] = [] var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { // Check for a [] or .[] suffix. The latter is only permitted when there // are no components. if self.at(.leftSquareBracket, where: { !$0.isAtStartOfLine }) || (components.isEmpty && self.at(any: [.period, .prefixPeriod]) && self.peek().tokenKind == .leftSquareBracket) { // Consume the '.', if it's allowed here. let period: RawTokenSyntax? if !self.at(.leftSquareBracket) { period = self.consumeAnyToken(remapping: .period) } else { period = nil } assert(self.at(.leftSquareBracket)) let lsquare = self.consumeAnyToken() let args: [RawTupleExprElementSyntax] if self.at(.rightSquareBracket) { args = [] } else { args = self.parseArgumentListElements(pattern: pattern) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) components.append(RawKeyPathComponentSyntax( period: period, component: .subscript(RawKeyPathSubscriptComponentSyntax( leftBracket: lsquare, argumentList: RawTupleExprElementListSyntax( elements: args, arena: self.arena), unexpectedBeforeRSquare, rightBracket: rsquare, arena: self.arena)), arena: self.arena)) continue } // Check for an operator starting with '.' that contains only // periods, '?'s, and '!'s. Expand that into key path components. if self.at(any: [ .postfixOperator, .postfixQuestionMark, .exclamationMark, .prefixOperator, .unspacedBinaryOperator ]), let numComponents = getNumOptionalKeyPathPostfixComponents( self.currentToken.tokenText) { components.append( contentsOf: self.consumeOptionalKeyPathPostfix( numComponents: numComponents)) continue } // Check for a .name or .1 suffix. if self.at(any: [.period, .prefixPeriod]) { let (period, name, declNameArgs, generics) = parseDottedExpressionSuffix() components.append(RawKeyPathComponentSyntax( period: period, component: .property(RawKeyPathPropertyComponentSyntax( identifier: name, declNameArguments: declNameArgs, genericArgumentClause: generics, arena: self.arena)), arena: self.arena)) continue } // No more postfix expressions. break } return RawKeyPathExprSyntax( unexpectedBeforeBackslash, backslash: backslash, root: rootType, components: RawKeyPathComponentListSyntax( elements: components, arena: self.arena), arena: self.arena) } } extension Parser { /// Parse a "primary expression" - these are the most basic leaves of the /// Swift expression grammar. /// /// Grammar /// ======= /// /// primary-expression → identifier generic-argument-clause? /// primary-expression → literal-expression /// primary-expression → self-expression /// primary-expression → superclass-expression /// primary-expression → closure-expression /// primary-expression → parenthesized-expression /// primary-expression → tuple-expression /// primary-expression → implicit-member-expression /// primary-expression → wildcard-expression /// primary-expression → key-path-expression /// primary-expression → selector-expression /// primary-expression → key-path-string-expression /// primary-expression → macro-expansion-expression @_spi(RawSyntax) public mutating func parsePrimaryExpression( pattern: PatternContext, flavor: ExprFlavor ) -> RawExprSyntax { switch self.at(anyIn: PrimaryExpressionStart.self) { case (.integerLiteral, let handle)?: let digits = self.eat(handle) return RawExprSyntax(RawIntegerLiteralExprSyntax( digits: digits, arena: self.arena )) case (.floatingLiteral, let handle)?: let digits = self.eat(handle) return RawExprSyntax(RawFloatLiteralExprSyntax( floatingDigits: digits, arena: self.arena )) case (.stringLiteral, _)?: return RawExprSyntax(self.parseStringLiteral()) case (.regexLiteral, _)?: return RawExprSyntax(self.parseRegexLiteral()) case (.nilKeyword, let handle)?: let nilKeyword = self.eat(handle) return RawExprSyntax(RawNilLiteralExprSyntax( nilKeyword: nilKeyword, arena: self.arena )) case (.trueKeyword, let handle)?, (.falseKeyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawBooleanLiteralExprSyntax( booleanLiteral: tok, arena: self.arena )) case (.__file__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundFileExprSyntax( poundFile: tok, arena: self.arena )) case (.__function__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundFunctionExprSyntax( poundFunction: tok, arena: self.arena )) case (.__line__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundLineExprSyntax( poundLine: tok, arena: self.arena )) case (.__column__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundColumnExprSyntax( poundColumn: tok, arena: self.arena )) case (.__dso_handle__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundDsohandleExprSyntax( poundDsohandle: tok, arena: self.arena )) case (.identifier, let handle)?, (.selfKeyword, let handle)?, (.initKeyword, let handle)?: // If we have "case let x." or "case let x(", we parse x as a normal // name, not a binding, because it is the start of an enum pattern or // call pattern. if pattern.admitsBinding && !self.lookahead().isNextTokenCallPattern() { let identifier = self.eat(handle) let pattern = RawPatternSyntax(RawIdentifierPatternSyntax( identifier: identifier, arena: self.arena)) return RawExprSyntax(RawUnresolvedPatternExprSyntax(pattern: pattern, arena: self.arena)) } // 'any' followed by another identifier is an existential type. if self.atContextualKeyword("any"), self.peek().tokenKind == .identifier, !self.peek().isAtStartOfLine { let ty = self.parseType() return RawExprSyntax(RawTypeExprSyntax(type: ty, arena: self.arena)) } return RawExprSyntax(self.parseIdentifierExpression()) case (.capitalSelfKeyword, _)?: // Self return RawExprSyntax(self.parseIdentifierExpression()) case (.anyKeyword, _)?: // Any let anyType = RawTypeSyntax(self.parseAnyType()) return RawExprSyntax(RawTypeExprSyntax(type: anyType, arena: self.arena)) case (.dollarIdentifier, _)?: return RawExprSyntax(self.parseAnonymousClosureArgument()) case (.wildcardKeyword, let handle)?: // _ let wild = self.eat(handle) return RawExprSyntax(RawDiscardAssignmentExprSyntax( wildcard: wild, arena: self.arena )) case (.pound, _)?: return RawExprSyntax( self.parseMacroExpansionExpr(pattern: pattern, flavor: flavor) ) case (.poundSelectorKeyword, _)?: return RawExprSyntax(self.parseObjectiveCSelectorLiteral()) case (.poundKeyPathKeyword, _)?: return RawExprSyntax(self.parseObjectiveCKeyPathExpression()) case (.leftBrace, _)?: // expr-closure return RawExprSyntax(self.parseClosureExpression()) case (.period, let handle)?, //=.foo (.prefixPeriod, let handle)?: // .foo let dot = self.eat(handle) let (name, args) = self.parseDeclNameRef([ .keywords, .compoundNames ]) return RawExprSyntax(RawMemberAccessExprSyntax( base: nil, dot: dot, name: name, declNameArguments: args, arena: self.arena)) case (.superKeyword, _)?: // 'super' return RawExprSyntax(self.parseSuperExpression()) case (.leftParen, _)?: // Build a tuple expression syntax node. // AST differentiates paren and tuple expression where the former allows // only one element without label. However, libSyntax tree doesn't have this // differentiation. A tuple expression node in libSyntax can have a single // element without label. return RawExprSyntax(self.parseTupleExpression(pattern: pattern)) case (.leftSquareBracket, _)?: return self.parseCollectionLiteral() case nil: return RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } } } extension Parser { /// Parse an identifier as an expression. /// /// Grammar /// ======= /// /// primary-expression → identifier @_spi(RawSyntax) public mutating func parseIdentifierExpression() -> RawExprSyntax { let (name, args) = self.parseDeclNameRef(.compoundNames) guard self.lookahead().canParseAsGenericArgumentList() else { if name.tokenText.isEditorPlaceholder && args == nil { return RawExprSyntax( RawEditorPlaceholderExprSyntax( identifier: name, arena: self.arena)) } return RawExprSyntax(RawIdentifierExprSyntax( identifier: name, declNameArguments: args, arena: self.arena)) } let identifier = RawIdentifierExprSyntax( identifier: name, declNameArguments: args, arena: self.arena) let generics = self.parseGenericArguments() return RawExprSyntax(RawSpecializeExprSyntax( expression: RawExprSyntax(identifier), genericArgumentClause: generics, arena: self.arena)) } } extension Parser { /// Parse a macro expansion as an expression. /// /// /// Grammar /// ======= /// /// macro-expansion-expression → '#' identifier expr-call-suffix? @_spi(RawSyntax) public mutating func parseMacroExpansionExpr( pattern: PatternContext, flavor: ExprFlavor ) -> RawMacroExpansionExprSyntax { let poundKeyword = self.consumeAnyToken() let (unexpectedBeforeMacro, macro) = self.expectIdentifier() // Parse the optional generic argument list. let generics: RawGenericArgumentClauseSyntax? if self.lookahead().canParseAsGenericArgumentList() { generics = self.parseGenericArguments() } else { generics = nil } // Parse the optional parenthesized argument list. let leftParen = self.consume(if: .leftParen, where: { !$0.isAtStartOfLine }) let args: [RawTupleExprElementSyntax] let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax? let rightParen: RawTokenSyntax? if leftParen != nil { args = parseArgumentListElements(pattern: pattern) (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) } else { args = [] unexpectedBeforeRightParen = nil rightParen = nil } // Parse the optional trailing closures. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } return RawMacroExpansionExprSyntax( poundToken: poundKeyword, unexpectedBeforeMacro, macro: macro, genericArguments: generics, leftParen: leftParen, argumentList: RawTupleExprElementListSyntax( elements: args, arena: self.arena ), unexpectedBeforeRightParen, rightParen: rightParen, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena) } } extension Parser { /// Parse a string literal expression. /// /// Grammar /// ======= /// /// string-literal → static-string-literal | interpolated-string-literal /// /// string-literal-opening-delimiter → extended-string-literal-delimiter? '"' /// string-literal-closing-delimiter → '"' extended-string-literal-delimiter? /// /// static-string-literal → string-literal-opening-delimiter quoted-text? string-literal-closing-delimiter /// static-string-literal → multiline-string-literal-opening-delimiter multiline-quoted-text? multiline-string-literal-closing-delimiter /// /// multiline-string-literal-opening-delimiter → extended-string-literal-delimiter? '"""' /// multiline-string-literal-closing-delimiter → '"""' extended-string-literal-delimiter? /// extended-string-literal-delimiter → '#' extended-string-literal-delimiter? /// /// quoted-text → quoted-text-item quoted-text? /// quoted-text-item → escaped-character /// quoted-text-item → `Any Unicode scalar value except ", \, U+000A, or U+000D` /// /// multiline-quoted-text → multiline-quoted-text-item multiline-quoted-text? /// multiline-quoted-text-item → escaped-character /// multiline-quoted-text-item → `Any Unicode scalar value except \` /// multiline-quoted-text-item → escaped-newline /// /// interpolated-string-literal → string-literal-opening-delimiter interpolated-text? string-literal-closing-delimiter /// interpolated-string-literal → multiline-string-literal-opening-delimiter multiline-interpolated-text? multiline-string-literal-closing-delimiter /// interpolated-text → interpolated-text-item interpolated-text? /// interpolated-text-item → '\(' expression ')' | quoted-text-item /// /// multiline-interpolated-text → multiline-interpolated-text-item multiline-interpolated-text? /// multiline-interpolated-text-item → '\(' expression ')' | multiline-quoted-text-item /// escape-sequence → \ extended-string-literal-delimiter /// escaped-character → escape-sequence '0' | escape-sequence '\' | escape-sequence 't' | escape-sequence 'n' | escape-sequence 'r' | escape-sequence '"' | escape-sequence ''' /// /// escaped-character → escape-sequence 'u' '{' unicode-scalar-digits '}' /// unicode-scalar-digits → Between one and eight hexadecimal digits /// /// escaped-newline → escape-sequence inline-spaces? line-break @_spi(RawSyntax) public mutating func parseStringLiteral() -> RawStringLiteralExprSyntax { var text = self.currentToken.wholeText[self.currentToken.textRange] /// Parse opening raw string delimiter if exist. let openDelimiter = self.parseStringLiteralDelimiter(at: .leading, text: text) if let openDelimiter = openDelimiter { text = text.dropFirst(openDelimiter.tokenText.count) } /// Parse open quote. let openQuote = self.parseStringLiteralQuote( at: openDelimiter != nil ? .leadingRaw : .leading, text: text, wantsMultiline: self.currentToken.isMultilineStringLiteral ) ?? RawTokenSyntax(missing: .stringQuote, arena: arena) if !openQuote.isMissing { text = text.dropFirst(openQuote.tokenText.count) } /// Parse segments. let (segments, closeStart) = self.parseStringLiteralSegments( text, openQuote, openDelimiter?.tokenText ?? "") text = text[closeStart...] /// Parse close quote. let closeQuote = self.parseStringLiteralQuote( at: openDelimiter != nil ? .trailingRaw : .trailing, text: text, wantsMultiline: self.currentToken.isMultilineStringLiteral ) ?? RawTokenSyntax(missing: openQuote.tokenKind, arena: arena) if !closeQuote.isMissing { text = text.dropFirst(closeQuote.tokenText.count) } /// Parse closing raw string delimiter if exist. let closeDelimiter: RawTokenSyntax? if let delimiter = self.parseStringLiteralDelimiter( at: .trailing, text: text ) { closeDelimiter = delimiter } else if let openDelimiter = openDelimiter { closeDelimiter = RawTokenSyntax( missing: .rawStringDelimiter, text: openDelimiter.tokenText, arena: arena ) } else { closeDelimiter = nil } assert((openDelimiter == nil) == (closeDelimiter == nil), "existence of open/close delimiter should match") if let closeDelimiter = closeDelimiter, !closeDelimiter.isMissing { text = text.dropFirst(closeDelimiter.byteLength) } assert(text.isEmpty, "string literal parsing should consume all the literal text") /// Discard the raw string literal token and create the structed string /// literal expression. /// FIXME: We should not instantiate `RawTokenSyntax` and discard it here. _ = self.consumeAnyToken() /// Construct the literal expression. return RawStringLiteralExprSyntax( openDelimiter: openDelimiter, openQuote: openQuote, segments: segments, closeQuote: closeQuote, closeDelimiter: closeDelimiter, arena: self.arena) } // Enumerates the positions that a quote can appear in a string literal. enum QuotePosition { /// The quote appears in leading position. /// /// ```swift /// "Hello World" /// ^ /// ##"Hello World"## /// ^ /// ``` case leading /// The quote appears in trailing position. /// /// ```swift /// "Hello World" /// ^ /// ##"Hello World"## /// ^ /// ``` case trailing /// The quote appears in at the start of a raw string literal. /// /// ```swift /// ##"Hello World"## /// ^ /// ``` case leadingRaw /// The quote appears in at the end of a raw string literal. /// /// ```swift /// ##"Hello World"## /// ^ /// ``` case trailingRaw } /// Create string literal delimiter/quote token syntax for `position`. /// /// `text` will the token text of the token. The `text.base` must be the whole /// text of the original `.stringLiteral` token including trivia. private func makeStringLiteralQuoteToken( _ kind: RawTokenKind, text: Slice<SyntaxText>, at position: QuotePosition ) -> RawTokenSyntax { let wholeText: SyntaxText let textRange: Range<SyntaxText.Index> switch position { case .leadingRaw, .trailingRaw: wholeText = SyntaxText(rebasing: text) textRange = wholeText.startIndex ..< wholeText.endIndex case .leading: wholeText = SyntaxText(rebasing: text.base[..<text.endIndex]) textRange = text.startIndex ..< text.endIndex case .trailing: wholeText = SyntaxText(rebasing: text.base[text.startIndex...]) textRange = wholeText.startIndex ..< wholeText.startIndex + text.count } return RawTokenSyntax( kind: kind, wholeText: wholeText, textRange: textRange, presence: .present, hasLexerError: false, arena: self.arena ) } mutating func parseStringLiteralDelimiter( at position: QuotePosition, text: Slice<SyntaxText> ) -> RawTokenSyntax? { assert(position != .leadingRaw && position != .trailingRaw) var index = text.startIndex while index < text.endIndex && text[index] == UInt8(ascii: "#") { index = text.index(after: index) } guard index > text.startIndex else { return nil } return makeStringLiteralQuoteToken( .rawStringDelimiter, text: text[..<index], at: position) } mutating func parseStringLiteralQuote( at position: QuotePosition, text: Slice<SyntaxText>, wantsMultiline: Bool ) -> RawTokenSyntax? { // Single quote. We only support single line literal. if let first = text.first, first == UInt8(ascii: "'") { let index = text.index(after: text.startIndex) return makeStringLiteralQuoteToken( .singleQuote, text: text[..<index], at: position) } var index = text.startIndex var quoteCount = 0 while index < text.endIndex && text[index] == UInt8(ascii: "\"") { quoteCount += 1 index = text.index(after: index) guard wantsMultiline else { break } } // Empty single line string. Return only the first quote. switch quoteCount { case 0, 1: break case 2: quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) case 3: // position == .leadingRaw implies that we saw a `#` before the quote. // A multiline string literal must always start its contents on a new line. // Thus we are parsing something like #"""#, which is not a multiline string literal but a raw literal containing a single quote. if position == .leadingRaw, index < text.endIndex, text[index] == UInt8(ascii: "#") { quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) } default: // Similar two the above, we are parsing something like #"""""#, which is not a multiline string literal but a raw literal containing three quote. if position == .leadingRaw { quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) } else if position == .leading { quoteCount = 3 index = text.index(text.startIndex, offsetBy: quoteCount) } } // Single line string literal. if quoteCount == 1 { return makeStringLiteralQuoteToken( .stringQuote, text: text[..<index], at: position) } // Multi line string literal. if quoteCount == 3 { return makeStringLiteralQuoteToken( .multilineStringQuote, text: text[..<index], at: position) } // Otherwise, this is not a literal quote. return nil } /// Foo. /// /// Parameters: /// - text: slice from after the quote to the end of the literal. /// - closer: opening quote token. /// - delimiter: opening custom string delimiter or empty string. mutating func parseStringLiteralSegments( _ text: Slice<SyntaxText>, _ closer: RawTokenSyntax, _ delimiter: SyntaxText ) -> (RawStringLiteralSegmentsSyntax, SyntaxText.Index) { let allowsMultiline = closer.tokenKind == .multilineStringQuote var segments = [RawStringLiteralSegmentsSyntax.Element]() var segment = text var stringLiteralSegmentStart = segment.startIndex while let slashIndex = segment.firstIndex(of: UInt8(ascii: "\\")), stringLiteralSegmentStart < segment.endIndex { let delimiterStart = text.index(after: slashIndex) guard delimiterStart < segment.endIndex && SyntaxText(rebasing: text[delimiterStart...]).hasPrefix(delimiter) else { // If `\` is not followed by the custom delimiter, it's not a segment delimiter. // Restart after the `\`. if delimiterStart == segment.endIndex { segment = text[segment.endIndex...] break } else { segment = text[text.index(after: delimiterStart)...] continue } } let contentStart = text.index(delimiterStart, offsetBy: delimiter.count) guard contentStart < segment.endIndex && text[contentStart] == UInt8(ascii: "(") else { if contentStart == segment.endIndex { segment = text[segment.endIndex...] break } else { // If `\` (or `\#`) is not followed by `(`, it's not a segment delimiter. // Restart after the `(`. segment = text[text.index(after: contentStart)...] continue } } // Collect ".stringSegment" before `\`. let segmentToken = RawTokenSyntax( kind: .stringSegment, text: SyntaxText(rebasing: text[stringLiteralSegmentStart..<slashIndex]), presence: .present, arena: self.arena) segments.append(.stringSegment(RawStringSegmentSyntax(content: segmentToken, arena: self.arena))) let content = SyntaxText(rebasing: text[contentStart...]) let contentSize = content.withBuffer { buf in Lexer.lexToEndOfInterpolatedExpression(buf, allowsMultiline) } let contentEnd = text.index(contentStart, offsetBy: contentSize) do { // `\` let slashToken = RawTokenSyntax( kind: .backslash, text: SyntaxText(rebasing: text[slashIndex..<text.index(after: slashIndex)]), presence: .present, arena: self.arena) // `###` let delim: RawTokenSyntax? if !delimiter.isEmpty { delim = RawTokenSyntax( kind: .rawStringDelimiter, text: SyntaxText(rebasing: text[delimiterStart..<contentStart]), presence: .present, arena: self.arena) } else { delim = nil } // `(...)`. let expressionContent = SyntaxText(rebasing: text[contentStart...contentEnd]) expressionContent.withBuffer { buf in var subparser = Parser(buf, arena: self.arena) let (lunexpected, lparen) = subparser.expect(.leftParen) let args = subparser.parseArgumentListElements(pattern: .none) // If we stopped parsing the expression before the expression segment is // over, eat the remaining tokens into a token list. var runexpectedTokens = [RawSyntax]() let runexpected: RawUnexpectedNodesSyntax? var loopProgress = LoopProgressCondition() while !subparser.at(any: [.eof, .rightParen]) && loopProgress.evaluate(subparser.currentToken) { runexpectedTokens.append(RawSyntax(subparser.consumeAnyToken())) } if !runexpectedTokens.isEmpty { runexpected = RawUnexpectedNodesSyntax(elements: runexpectedTokens, arena: self.arena) } else { runexpected = nil } let rparen = subparser.expectWithoutRecovery(.rightParen) assert(subparser.currentToken.tokenKind == .eof) let trailing: RawUnexpectedNodesSyntax? if subparser.currentToken.byteLength == 0 { trailing = nil } else { trailing = RawUnexpectedNodesSyntax([ subparser.consumeAnyToken() ], arena: self.arena) } segments.append(.expressionSegment(RawExpressionSegmentSyntax( backslash: slashToken, delimiter: delim, lunexpected, leftParen: lparen, expressions: RawTupleExprElementListSyntax(elements: args, arena: self.arena), runexpected, rightParen: rparen, trailing, arena: self.arena))) } } segment = text[text.index(after: contentEnd)...] stringLiteralSegmentStart = segment.startIndex } /// We still have the last "literal" segment. /// Trim the end delimiter. i.e. `"##`. segment = text[stringLiteralSegmentStart...] if (SyntaxText(rebasing: segment).hasSuffix(delimiter)) { // trim `##`. segment = text[stringLiteralSegmentStart..<text.index(segment.endIndex, offsetBy: -delimiter.count)] if (SyntaxText(rebasing: segment).hasSuffix(closer.tokenText)) { // trim `"`. segment = text[stringLiteralSegmentStart..<text.index(segment.endIndex, offsetBy: -closer.tokenText.count)] } else { // If `"` is not found, eat the rest. segment = text[stringLiteralSegmentStart...] } } assert(segments.count % 2 == 0) assert(segments.isEmpty || segments.last!.is(RawExpressionSegmentSyntax.self)) let segmentToken = RawTokenSyntax( kind: .stringSegment, text: SyntaxText(rebasing: segment), presence: .present, arena: self.arena) segments.append(.stringSegment(RawStringSegmentSyntax(content: segmentToken, arena: self.arena))) return (RawStringLiteralSegmentsSyntax(elements: segments, arena: arena), segment.endIndex) } } extension Parser { /// Parse a regular expression literal. /// /// The broad structure of the regular expression is validated by the lexer. /// /// Grammar /// ======= /// /// regular-expression-literal → '\' `Any valid regular expression characters` '\' @_spi(RawSyntax) public mutating func parseRegexLiteral() -> RawRegexLiteralExprSyntax { let (unexpectedBeforeLiteral, literal) = self.expect(.regexLiteral) return RawRegexLiteralExprSyntax( unexpectedBeforeLiteral, regex: literal, arena: self.arena ) } } extension Parser { /// Parse an Objective-C #keypath literal. /// /// Grammar /// ======= /// /// key-path-string-expression → '#keyPath' '(' expression ')' @_spi(RawSyntax) public mutating func parseObjectiveCKeyPathExpression() -> RawObjcKeyPathExprSyntax { let (unexpectedBeforeKeyword, keyword) = self.expect(.poundKeyPathKeyword) // Parse the leading '('. let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) // Parse the sequence of unqualified-names. var elements = [RawObjcNamePieceSyntax]() do { var flags: DeclNameOptions = [] var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { // Parse the next name. let (name, args) = self.parseDeclNameRef(flags) assert(args == nil, "Found arguments but did not pass argument flag?") // After the first component, we can start parsing keywords. flags.formUnion(.keywords) // Parse the next period to continue the path. keepGoing = self.consume(if: .period) elements.append(RawObjcNamePieceSyntax( name: name, dot: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } // Parse the closing ')'. let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawObjcKeyPathExprSyntax( unexpectedBeforeKeyword, keyPath: keyword, unexpectedBeforeLParen, leftParen: lparen, name: RawObjcNameSyntax(elements: elements, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { /// Parse a 'super' reference to the superclass instance of a class. /// /// Grammar /// ======= /// /// primary-expression → 'super' @_spi(RawSyntax) public mutating func parseSuperExpression() -> RawSuperRefExprSyntax { // Parse the 'super' reference. let (unexpectedBeforeSuperKeyword, superKeyword) = self.expect(.superKeyword) return RawSuperRefExprSyntax( unexpectedBeforeSuperKeyword, superKeyword: superKeyword, arena: self.arena ) } } extension Parser { /// Parse a tuple expression. /// /// Grammar /// ======= /// /// tuple-expression → '(' ')' | '(' tuple-element ',' tuple-element-list ')' /// tuple-element-list → tuple-element | tuple-element ',' tuple-element-list @_spi(RawSyntax) public mutating func parseTupleExpression(pattern: PatternContext) -> RawTupleExprSyntax { let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) let elements = self.parseArgumentListElements(pattern: pattern) let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawTupleExprSyntax( unexpectedBeforeLParen, leftParen: lparen, elementList: RawTupleExprElementListSyntax(elements: elements, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { enum CollectionKind { case dictionary(key: RawExprSyntax, unexpectedBeforeColon: RawUnexpectedNodesSyntax?, colon: RawTokenSyntax, value: RawExprSyntax) case array(RawExprSyntax) } /// Parse an element of an array or dictionary literal. /// /// Grammar /// ======= /// /// array-literal-item → expression /// /// dictionary-literal-item → expression ':' expression mutating func parseCollectionElement(_ existing: CollectionKind?) -> CollectionKind { let key = self.parseExpression() switch existing { case .array(_): return .array(key) case nil: guard self.at(.colon) else { return .array(key) } fallthrough case .dictionary: let (unexpectedBeforeColon, colon) = self.expect(.colon) let value = self.parseExpression() return .dictionary(key: key, unexpectedBeforeColon: unexpectedBeforeColon, colon: colon, value: value) } } /// Parse an array or dictionary literal. /// /// Grammar /// ======= /// /// array-literal → '[' array-literal-items? ']' /// array-literal-items → array-literal-item ','? | array-literal-item ',' array-literal-items /// /// dictionary-literal → '[' dictionary-literal-items ']' | '[' ':' ']' /// dictionary-literal-items → dictionary-literal-item ','? | dictionary-literal-item ',' dictionary-literal-items @_spi(RawSyntax) public mutating func parseCollectionLiteral() -> RawExprSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawExprSyntax(RawArrayExprSyntax( remainingTokens, leftSquare: missingToken(.leftSquareBracket), elements: RawArrayElementListSyntax(elements: [], arena: self.arena), rightSquare: missingToken(.rightSquareBracket), arena: self.arena )) } let (unexpectedBeforeLSquare, lsquare) = self.expect(.leftSquareBracket) if let rsquare = self.consume(if: .rightSquareBracket) { return RawExprSyntax(RawArrayExprSyntax( unexpectedBeforeLSquare, leftSquare: lsquare, elements: RawArrayElementListSyntax(elements: [], arena: self.arena), rightSquare: rsquare, arena: self.arena)) } if let (colon, rsquare) = self.consume(if: .colon, followedBy: .rightSquareBracket) { // FIXME: We probably want a separate node for the empty case. return RawExprSyntax(RawDictionaryExprSyntax( unexpectedBeforeLSquare, leftSquare: lsquare, content: .colon(colon), rightSquare: rsquare, arena: self.arena )) } var elementKind: CollectionKind? = nil var elements = [RawSyntax]() do { var collectionLoopCondition = LoopProgressCondition() COLLECTION_LOOP: while collectionLoopCondition.evaluate(currentToken) { elementKind = self.parseCollectionElement(elementKind) // Parse the ',' if exists. let comma = self.consume(if: .comma) switch elementKind! { case .array(let el): let element = RawArrayElementSyntax( expression: el, trailingComma: comma, arena: self.arena ) if element.isEmpty { break COLLECTION_LOOP } else { elements.append(RawSyntax(element)) } case .dictionary(let key, let unexpectedBeforeColon, let colon, let value): let element = RawDictionaryElementSyntax( keyExpression: key, unexpectedBeforeColon, colon: colon, valueExpression: value, trailingComma: comma, arena: self.arena ) if element.isEmpty { break COLLECTION_LOOP } else { elements.append(RawSyntax(element)) } } // If we saw a comma, that's a strong indicator we have more elements // to process. If that's not the case, we have to do some legwork to // determine if we should bail out. guard comma == nil || self.at(any: [.rightSquareBracket, .eof]) else { continue } // If we found EOF or the closing square bracket, bailout. if self.at(any: [.rightSquareBracket, .eof]) { break } // If The next token is at the beginning of a new line and can never start // an element, break. if self.currentToken.isAtStartOfLine && (self.at(any: [.rightBrace, .poundEndifKeyword]) || self.atStartOfDeclaration() || self.atStartOfStatement()) { break } } } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) switch elementKind! { case .dictionary: return RawExprSyntax(RawDictionaryExprSyntax( leftSquare: lsquare, content: .elements(RawDictionaryElementListSyntax(elements: elements.map { $0.as(RawDictionaryElementSyntax.self)! }, arena: self.arena)), unexpectedBeforeRSquare, rightSquare: rsquare, arena: self.arena)) case .array: return RawExprSyntax(RawArrayExprSyntax( leftSquare: lsquare, elements: RawArrayElementListSyntax(elements: elements.map { $0.as(RawArrayElementSyntax.self)! }, arena: self.arena), unexpectedBeforeRSquare, rightSquare: rsquare, arena: self.arena)) } } } extension Parser { @_spi(RawSyntax) public mutating func parseDefaultArgument() -> RawInitializerClauseSyntax { let (unexpectedBeforeEq, eq) = self.expect(.equal) let expr = self.parseExpression() return RawInitializerClauseSyntax( unexpectedBeforeEq, equal: eq, value: expr, arena: self.arena ) } } extension Parser { @_spi(RawSyntax) public mutating func parseAnonymousClosureArgument() -> RawIdentifierExprSyntax { let (unexpectedBeforeIdent, ident) = self.expect(.dollarIdentifier) return RawIdentifierExprSyntax( unexpectedBeforeIdent, identifier: ident, declNameArguments: nil, arena: self.arena ) } } extension Parser { /// Parse a #selector expression. /// /// Grammar /// ======= /// /// selector-expression → '#selector' '(' expression ) /// selector-expression → '#selector' '(' 'getter' ':' expression ')' /// selector-expression → '#selector' '(' 'setter' ':' expression ')' @_spi(RawSyntax) public mutating func parseObjectiveCSelectorLiteral() -> RawObjcSelectorExprSyntax { // Consume '#selector'. let (unexpectedBeforeSelector, selector) = self.expect(.poundSelectorKeyword) // Parse the leading '('. let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) // Parse possible 'getter:' or 'setter:' modifiers, and determine // the kind of selector we're working with. let kindAndColon = self.consume( if: { $0.isContextualKeyword(["getter", "setter"])}, followedBy: { $0.tokenKind == .colon } ) let (kind, colon) = (kindAndColon?.0, kindAndColon?.1) // Parse the subexpression. let subexpr = self.parseExpression() // Parse the closing ')'. let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawObjcSelectorExprSyntax( unexpectedBeforeSelector, poundSelector: selector, unexpectedBeforeLParen, leftParen: lparen, kind: kind, colon: colon, name: subexpr, unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { /// Parse a closure expression. /// /// Grammar /// ======= /// /// closure-expression → '{' attributes? closure-signature? statements? '}' @_spi(RawSyntax) public mutating func parseClosureExpression() -> RawClosureExprSyntax { // Parse the opening left brace. let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace) // Parse the closure-signature, if present. let signature = self.parseClosureSignatureIfPresent() // Parse the body. var elements = [RawCodeBlockItemSyntax]() do { var loopProgress = LoopProgressCondition() while !self.at(.rightBrace), let newItem = self.parseCodeBlockItem(), loopProgress.evaluate(currentToken) { elements.append(newItem) } } // Parse the closing '}'. let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace) return RawClosureExprSyntax( unexpectedBeforeLBrace, leftBrace: lbrace, signature: signature, statements: RawCodeBlockItemListSyntax(elements: elements, arena: arena), unexpectedBeforeRBrace, rightBrace: rbrace, arena: self.arena) } } extension Parser { /// Parse the signature of a closure, if one is present. /// /// Grammar /// ======= /// /// closure-signature → capture-list? closure-parameter-clause 'async'? 'throws'? function-result? 'in' /// closure-signature → capture-list 'in' /// /// closure-parameter-clause → '(' ')' | '(' closure-parameter-list ')' | identifier-list /// /// closure-parameter-list → closure-parameter | closure-parameter , closure-parameter-list /// closure-parameter → closure-parameter-name type-annotation? /// closure-parameter → closure-parameter-name type-annotation '...' /// closure-parameter-name → identifier /// /// capture-list → '[' capture-list-items ']' /// capture-list-items → capture-list-item | capture-list-item , capture-list-items /// capture-list-item → capture-specifier? identifier /// capture-list-item → capture-specifier? identifier '=' expression /// capture-list-item → capture-specifier? self-expression /// /// capture-specifier → 'weak' | 'unowned' | 'unowned(safe)' | 'unowned(unsafe)' @_spi(RawSyntax) public mutating func parseClosureSignatureIfPresent() -> RawClosureSignatureSyntax? { // If we have a leading token that may be part of the closure signature, do a // speculative parse to validate it and look for 'in'. guard self.at(any: [.atSign, .leftParen, .leftSquareBracket, .wildcardKeyword]) || self.at(.identifier) else { // No closure signature. return nil } guard self.lookahead().canParseClosureSignature() else { return nil } let attrs = self.parseAttributeList() let captures: RawClosureCaptureSignatureSyntax? if let lsquare = self.consume(if: .leftSquareBracket) { // At this point, we know we have a closure signature. Parse the capture list // and parameters. var elements = [RawClosureCaptureItemSyntax]() if !self.at(.rightSquareBracket) { var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { // Parse any specifiers on the capture like `weak` or `unowned` let specifier = self.parseClosureCaptureSpecifiers() // The thing being capture specified is an identifier, or as an identifier // followed by an expression. let unexpectedBeforeName: RawUnexpectedNodesSyntax? let name: RawTokenSyntax? let unexpectedBeforeAssignToken: RawUnexpectedNodesSyntax? let assignToken: RawTokenSyntax? let expression: RawExprSyntax if self.peek().tokenKind == .equal { // The name is a new declaration. (unexpectedBeforeName, name) = self.expectIdentifier() (unexpectedBeforeAssignToken, assignToken) = self.expect(.equal) expression = self.parseExpression() } else { // This is the simple case - the identifier is both the name and // the expression to capture. unexpectedBeforeName = nil name = nil unexpectedBeforeAssignToken = nil assignToken = nil expression = RawExprSyntax(self.parseIdentifierExpression()) } keepGoing = self.consume(if: .comma) elements.append(RawClosureCaptureItemSyntax( specifier: specifier, unexpectedBeforeName, name: name, unexpectedBeforeAssignToken, assignToken: assignToken, expression: expression, trailingComma: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } // We were promised a right square bracket, so we're going to get it. var unexpectedNodes = [RawSyntax]() while !self.at(.eof) && !self.at(.rightSquareBracket) && !self.at(.inKeyword) { unexpectedNodes.append(RawSyntax(self.consumeAnyToken())) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) unexpectedNodes.append(contentsOf: unexpectedBeforeRSquare?.elements ?? []) captures = RawClosureCaptureSignatureSyntax( leftSquare: lsquare, items: elements.isEmpty ? nil : RawClosureCaptureItemListSyntax(elements: elements, arena: self.arena), RawUnexpectedNodesSyntax(unexpectedNodes, arena: self.arena), rightSquare: rsquare, arena: self.arena) } else { captures = nil } var input: RawClosureSignatureSyntax.Input? var asyncKeyword: RawTokenSyntax? = nil var throwsTok: RawTokenSyntax? = nil var output: RawReturnClauseSyntax? = nil if !self.at(.inKeyword) { if self.at(.leftParen) { // Parse the closure arguments. input = .input(self.parseParameterClause(for: .closure)) } else { var params = [RawClosureParamSyntax]() var loopProgress = LoopProgressCondition() do { // Parse identifier (',' identifier)* var keepGoing: RawTokenSyntax? = nil repeat { let unexpected: RawUnexpectedNodesSyntax? let name: RawTokenSyntax if let identifier = self.consume(if: .identifier) { unexpected = nil name = identifier } else { (unexpected, name) = self.expect(.wildcardKeyword) } keepGoing = consume(if: .comma) params.append(RawClosureParamSyntax( unexpected, name: name, trailingComma: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } input = .simpleInput(RawClosureParamListSyntax(elements: params, arena: self.arena)) } asyncKeyword = self.parseEffectsSpecifier() throwsTok = self.parseEffectsSpecifier() // Parse the optional explicit return type. if let arrow = self.consume(if: .arrow) { // Parse the type. let returnTy = self.parseType() output = RawReturnClauseSyntax( arrow: arrow, returnType: returnTy, arena: self.arena ) } } // Parse the 'in'. let (unexpectedBeforeInTok, inTok) = self.expect(.inKeyword) return RawClosureSignatureSyntax( attributes: attrs, capture: captures, input: input, asyncKeyword: asyncKeyword, throwsTok: throwsTok, output: output, unexpectedBeforeInTok, inTok: inTok, arena: self.arena) } @_spi(RawSyntax) public mutating func parseClosureCaptureSpecifiers() -> RawTokenListSyntax? { var specifiers = [RawTokenSyntax]() do { // Check for the strength specifier: "weak", "unowned", or // "unowned(safe/unsafe)". if let weakContextualKeyword = self.consumeIfContextualKeyword("weak") { specifiers.append(weakContextualKeyword) } else if let unownedContextualKeyword = self.consumeIfContextualKeyword("unowned") { specifiers.append(unownedContextualKeyword) if let lparen = self.consume(if: .leftParen) { specifiers.append(lparen) if self.currentToken.tokenText == "safe" { specifiers.append(self.expectContextualKeywordWithoutRecovery("safe")) } else { specifiers.append(self.expectContextualKeywordWithoutRecovery("unsafe")) } specifiers.append(self.expectWithoutRecovery(.rightParen)) } } else if self.at(.identifier) || self.at(.selfKeyword) { let next = self.peek() // "x = 42", "x," and "x]" are all strong captures of x. guard next.tokenKind == .equal || next.tokenKind == .comma || next.tokenKind == .rightSquareBracket || next.tokenKind == .period else { return nil } } else { return nil } } // Squash all tokens, if any, as the specifier of the captured item. return RawTokenListSyntax(elements: specifiers, arena: self.arena) } } extension Parser { /// Parse the elements of an argument list. /// /// This is currently the same as parsing a tuple expression. In the future, /// this will be a dedicated argument list type. /// /// Grammar /// ======= /// /// tuple-element → expression | identifier ':' expression @_spi(RawSyntax) public mutating func parseArgumentListElements(pattern: PatternContext) -> [RawTupleExprElementSyntax] { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return [RawTupleExprElementSyntax( remainingTokens, label: nil, colon: nil, expression: RawExprSyntax(RawMissingExprSyntax(arena: self.arena)), trailingComma: nil, arena: self.arena )] } guard !self.at(.rightParen) else { return [] } var result = [RawTupleExprElementSyntax]() var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { let unexpectedBeforeLabel: RawUnexpectedNodesSyntax? let label: RawTokenSyntax? let colon: RawTokenSyntax? if currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon { (unexpectedBeforeLabel, label) = parseArgumentLabel() colon = consumeAnyToken() } else { unexpectedBeforeLabel = nil label = nil colon = nil } // See if we have an operator decl ref '(<op>)'. The operator token in // this case lexes as a binary operator because it neither leads nor // follows a proper subexpression. let expr: RawExprSyntax if self.at(anyIn: BinaryOperator.self) != nil && (self.peek().tokenKind == .comma || self.peek().tokenKind == .rightParen || self.peek().tokenKind == .rightSquareBracket) { let (ident, args) = self.parseDeclNameRef(.operators) expr = RawExprSyntax(RawIdentifierExprSyntax( identifier: ident, declNameArguments: args, arena: self.arena)) } else { expr = self.parseExpression(pattern: pattern) } keepGoing = self.consume(if: .comma) result.append(RawTupleExprElementSyntax( unexpectedBeforeLabel, label: label, colon: colon, expression: expr, trailingComma: keepGoing, arena: self.arena )) } while keepGoing != nil && loopProgress.evaluate(currentToken) return result } } extension Parser { /// Parse the trailing closure(s) following a call expression. /// /// Grammar /// ======= /// /// trailing-closures → closure-expression labeled-trailing-closures? /// labeled-trailing-closures → labeled-trailing-closure labeled-trailing-closures? /// labeled-trailing-closure → identifier ':' closure-expression @_spi(RawSyntax) public mutating func parseTrailingClosures(_ flavor: ExprFlavor) -> (RawClosureExprSyntax, RawMultipleTrailingClosureElementListSyntax?) { // Parse the closure. let closure = self.parseClosureExpression() // Parse labeled trailing closures. var elements = [RawMultipleTrailingClosureElementSyntax]() var loopProgress = LoopProgressCondition() while self.lookahead().isStartOfLabelledTrailingClosure() && loopProgress.evaluate(currentToken) { let (unexpectedBeforeLabel, label) = self.parseArgumentLabel() let (unexpectedBeforeColon, colon) = self.expect(.colon) let closure = self.parseClosureExpression() elements.append(RawMultipleTrailingClosureElementSyntax( unexpectedBeforeLabel, label: label, unexpectedBeforeColon, colon: colon, closure: closure, arena: self.arena )) } let trailing = elements.isEmpty ? nil : RawMultipleTrailingClosureElementListSyntax(elements: elements, arena: self.arena) return (closure, trailing) } } extension Parser.Lookahead { func isStartOfLabelledTrailingClosure() -> Bool { // Fast path: the next two tokens must be a label and a colon. // But 'default:' is ambiguous with switch cases and we disallow it // (unless escaped) even outside of switches. if !self.currentToken.canBeArgumentLabel() || self.at(.defaultKeyword) || self.peek().tokenKind != .colon { return false } // Do some tentative parsing to distinguish `label: { ... }` and // `label: switch x { ... }`. var backtrack = self.lookahead() backtrack.consumeAnyToken() if backtrack.peek().tokenKind == .leftBrace { return true } if backtrack.peek().isEditorPlaceholder { // Editor placeholder can represent entire closures return true } return false } /// Recover invalid uses of trailing closures in a situation /// where the parser requires an expr-basic (which does not allow them). We /// handle this by doing some lookahead in common situations. And later, Sema /// will emit a diagnostic with a fixit to add wrapping parens. func isValidTrailingClosure(_ flavor: Parser.ExprFlavor) -> Bool { assert(self.at(.leftBrace), "Couldn't be a trailing closure") // If this is the start of a get/set accessor, then it isn't a trailing // closure. guard !self.lookahead().isStartOfGetSetAccessor() else { return false } // If this is a normal expression (not an expr-basic) then trailing closures // are allowed, so this is obviously one. // TODO: We could handle try to disambiguate cases like: // let x = foo // {...}() // by looking ahead for the ()'s, but this has been replaced by do{}, so this // probably isn't worthwhile. guard case .basic = flavor else { return true } // If this is an expr-basic, then a trailing closure is not allowed. However, // it is very common for someone to write something like: // // for _ in numbers.filter {$0 > 4} { // // and we want to recover from this very well. We need to perform arbitrary // look-ahead to disambiguate this case, so we only do this in the case where // the token after the { is on the same line as the {. guard !self.peek().isAtStartOfLine else { return false } // Determine if the {} goes with the expression by eating it, and looking // to see if it is immediately followed by a token which indicates we should // consider it part of the preceding expression var backtrack = self.lookahead() backtrack.eat(.leftBrace) var loopProgress = LoopProgressCondition() while !backtrack.at(any: [.eof, .rightBrace, .poundEndifKeyword, .poundElseKeyword, .poundElseifKeyword ]) && loopProgress.evaluate(backtrack.currentToken) { backtrack.skipSingle() } guard backtrack.consume(if: .rightBrace) != nil else { return false } switch backtrack.currentToken.tokenKind { case .leftBrace, .whereKeyword, .comma: return true case .leftSquareBracket, .leftParen, .period, .prefixPeriod, .isKeyword, .asKeyword, .postfixQuestionMark, .infixQuestionMark, .exclamationMark, .colon, .equal, .postfixOperator, .spacedBinaryOperator, .unspacedBinaryOperator: return !backtrack.currentToken.isAtStartOfLine default: return false } } } // MARK: Lookahead extension Parser.Lookahead { // Consume 'async', 'throws', and 'rethrows', but in any order. mutating func consumeEffectsSpecifiers() { var loopProgress = LoopProgressCondition() while let (_, handle) = self.at(anyIn: EffectsSpecifier.self), loopProgress.evaluate(currentToken) { self.eat(handle) } } func canParseClosureSignature() -> Bool { // Consume attributes. var lookahead = self.lookahead() var attributesProgress = LoopProgressCondition() while let _ = lookahead.consume(if: .atSign), attributesProgress.evaluate(lookahead.currentToken) { guard lookahead.at(.identifier) else { break } _ = lookahead.canParseCustomAttribute() } // Skip by a closure capture list if present. if lookahead.consume(if: .leftSquareBracket) != nil { lookahead.skipUntil(.rightSquareBracket, .rightSquareBracket) if lookahead.consume(if: .rightSquareBracket) == nil { return false } } // Parse pattern-tuple func-signature-result? 'in'. if lookahead.consume(if: .leftParen) != nil { // Consume the ')'. // While we don't have '->' or ')', eat balanced tokens. var skipProgress = LoopProgressCondition() while !lookahead.at(any: [.eof, .rightParen]) && skipProgress.evaluate(lookahead.currentToken) { lookahead.skipSingle() } // Consume the ')', if it's there. if lookahead.consume(if: .rightParen) != nil { lookahead.consumeEffectsSpecifiers() // Parse the func-signature-result, if present. if lookahead.consume(if: .arrow) != nil { guard lookahead.canParseType() else { return false } lookahead.consumeEffectsSpecifiers() } } // Okay, we have a closure signature. } else if lookahead.at(.identifier) || lookahead.at(.wildcardKeyword) { // Parse identifier (',' identifier)* lookahead.consumeAnyToken() var parametersProgress = LoopProgressCondition() while lookahead.consume(if: .comma) != nil && parametersProgress.evaluate(lookahead.currentToken) { if lookahead.at(.identifier) || lookahead.at(.wildcardKeyword) { lookahead.consumeAnyToken() continue } return false } lookahead.consumeEffectsSpecifiers() // Parse the func-signature-result, if present. if lookahead.consume(if: .arrow) != nil { guard lookahead.canParseType() else { return false } lookahead.consumeEffectsSpecifiers() } } // Parse the 'in' at the end. guard lookahead.at(.inKeyword) else { return false } // Okay, we have a closure signature. return true } } extension Parser.Lookahead { // Helper function to see if we can parse member reference like suffixes // inside '#if'. fileprivate func isAtStartOfPostfixExprSuffix() -> Bool { guard self.at(any: [.period, .prefixPeriod]) else { return false } if self.at(.integerLiteral) { return true } if self.peek().tokenKind != .identifier, self.peek().tokenKind != .capitalSelfKeyword, self.peek().tokenKind != .selfKeyword, !self.peek().tokenKind.isKeyword { return false } return true } fileprivate func isNextTokenCallPattern() -> Bool { switch self.peek().tokenKind { case .period, .prefixPeriod, .leftParen: return true default: return false } } }
apache-2.0
ITzTravelInTime/TINU
TINU/OtherWindowsControllers.swift
1
2757
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa public class DriveDetectInfoWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title += ": Why is my storage device not detected?" } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "DriveDetectionInfo") as! NSWindowController).window) //self.window?.isFullScreenEnaled = false //self.init(windowNibName: "ContactsWindowController") } } public class DownloadAppWindowController: NSWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.isFullScreenEnaled = true self.window?.collectionBehavior.insert(.fullScreenNone) } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "DownloadApp") as! NSWindowController).window) //self.window?.isFullScreenEnaled = false //self.init(windowNibName: "ContactsWindowController") } } public class ContactsWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title += ": Contact us" } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "Contacts") as! NSWindowController).window) //self.init(windowNibName: "ContactsWindowController") } } public class CreditsWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title = "About " + (self.window?.title ?? "TINU") } convenience init() { //creates an istance of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "Credits") as! NSWindowController).window) //self.init(windowNibName: "ContactsWindowController") } }
gpl-2.0
roecrew/AudioKit
AudioKit/Common/MIDI/AKMIDIListener.swift
2
6338
// // AKMIDIListener.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Protocol that must be adhered to if you want your class to respond to MIDI /// /// Implement the AKMIDIListener protocol on any classes that need to respond /// to incoming MIDI events. Every method in the protocol is optional to allow /// the classes complete freedom to respond to only the particular MIDI messages /// of interest. /// public protocol AKMIDIListener { /// Receive the MIDI note on event /// /// - Parameters: /// - noteNumber: MIDI Note number of activated note /// - velocity: MIDI Velocity (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDINoteOn(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) /// Receive the MIDI note off event /// /// - Parameters: /// - noteNumber: MIDI Note number of released note /// - velocity: MIDI Velocity (0-127) usually speed of release, often 0. /// - channel: MIDI Channel (1-16) /// func receivedMIDINoteOff(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) /// Receive a generic controller value /// /// - Parameters: /// - controller: MIDI Controller Number /// - value: Value of this controller /// - channel: MIDI Channel (1-16) /// func receivedMIDIController(controller: Int, value: Int, channel: MIDIChannel) /// Receive single note based aftertouch event /// /// - Parameters: /// - noteNumber: Note number of touched note /// - pressure: Pressure applied to the note (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIAftertouch(noteNumber noteNumber: MIDINoteNumber, pressure: Int, channel: MIDIChannel) /// Receive global aftertouch /// /// - Parameters: /// - pressure: Pressure applied (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIAfterTouch(pressure: Int, channel: MIDIChannel) /// Receive pitch wheel value /// /// - Parameters: /// - pitchWheelValue: MIDI Pitch Wheel Value (0-16383) /// - channel: MIDI Channel (1-16) /// func receivedMIDIPitchWheel(pitchWheelValue: Int, channel: MIDIChannel) /// Receive program change /// /// - Parameters: /// - program: MIDI Program Value (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIProgramChange(program: Int, channel: MIDIChannel) /// Receive a midi system command (such as clock, sysex, etc) /// /// - parameter data: Array of integers /// func receivedMIDISystemCommand(data: [UInt8]) } /// Default listener functions public extension AKMIDIListener { /// Receive the MIDI note on event /// /// - Parameters: /// - noteNumber: Note number of activated note /// - velocity: MIDI Velocity (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDINoteOn(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { print("channel: \(channel) noteOn: \(noteNumber) velocity: \(velocity)") } /// Receive the MIDI note off event /// /// - Parameters: /// - noteNumber: Note number of released note /// - velocity: MIDI Velocity (0-127) usually speed of release, often 0. /// - channel: MIDI Channel (1-16) /// func receivedMIDINoteOff(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { print("channel: \(channel) noteOff: \(noteNumber) velocity: \(velocity)") } /// Receive a generic controller value /// /// - Parameters: /// - controller: MIDI Controller Number /// - value: Value of this controller /// - channel: MIDI Channel (1-16) /// func receivedMIDIController(controller: Int, value: Int, channel: MIDIChannel) { print("channel: \(channel) controller: \(controller) value: \(value)") } /// Receive single note based aftertouch event /// /// - Parameters: /// - noteNumber: Note number of touched note /// - pressure: Pressure applied to the note (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIAftertouch(noteNumber noteNumber: MIDINoteNumber, pressure: Int, channel: MIDIChannel) { print("channel: \(channel) midiAftertouch Note: \(noteNumber) pressure: \(pressure)") } /// Receive global aftertouch /// /// - Parameters: /// - pressure: Pressure applied (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIAfterTouch(pressure: Int, channel: MIDIChannel) { print("channel: \(channel) midiAfterTouch pressure: \(pressure)") } /// Receive pitch wheel value /// /// - Parameters: /// - pitchWheelValue: MIDI Pitch Wheel Value (0-16383) /// - channel: MIDI Channel (1-16) /// func receivedMIDIPitchWheel(pitchWheelValue: Int, channel: MIDIChannel) { print("channel: \(channel) pitchWheel: \(pitchWheelValue)") } /// Receive program change /// /// - Parameters: /// - program: MIDI Program Value (0-127) /// - channel: MIDI Channel (1-16) /// func receivedMIDIProgramChange(program: Int, channel: MIDIChannel) { print("channel: \(channel) programChange: \(program)") } /// Receive a midi system command (such as clock, sysex, etc) /// /// - parameter data: Array of integers /// func receivedMIDISystemCommand(data: [UInt8]) { print("MIDI System Command: \(AKMIDISystemCommand(rawValue: data[0])!)") } }
mit
Maturelittleman/ImitateQQMusicDemo
QQMusic/QQMusic/Classes/Other/Tool/ZQAudioTool.swift
1
1151
// // ZQAudioTool.swift // QQMusic // // Created by 仲琦 on 16/5/18. // Copyright © 2016年 仲琦. All rights reserved. // 提供 单手音乐的操作(播放, 暂停, 停止, 快进, 倍速) import UIKit import AVFoundation class ZQAudioTool: NSObject { var player: AVAudioPlayer? //根据音频名称播放音频 func playMusic(name: String) -> () { //取出url guard let url = NSBundle.mainBundle().URLForResource(name, withExtension: nil) else { return } //播放的是同一首歌曲 if url == player?.url { player?.play() return } //添加到 播放器中 do { player = try AVAudioPlayer(contentsOfURL: url) }catch { print(error) return } //准备播放 player?.prepareToPlay() //开始播放 player?.play() } //继续播放 func resumeCurrentMusic() { player?.play() } //暂停音频 func pauseCurrentMusic() { player?.pause() } }
apache-2.0
Sajjon/ViewComposer
Source/Classes/ViewAttribute/AttributedValues/TextInputTraitable.swift
1
2800
// // TextInputTraitable.swift // ViewComposer // // Created by Alexander Cyon on 2017-07-03. // // import Foundation protocol TextInputTraitable: class { var autocapitalizationType: UITextAutocapitalizationType { get set } var autocorrectionType: UITextAutocorrectionType { get set } var spellCheckingType: UITextSpellCheckingType { get set } var keyboardType: UIKeyboardType { get set } var keyboardAppearance: UIKeyboardAppearance { get set } var returnKeyType: UIReturnKeyType { get set } var enablesReturnKeyAutomatically: Bool { get set } var isSecureTextEntry: Bool { get set } var textContentTypeProxy: UITextContentType? { get set } } extension UITextField: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } extension UITextView: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } extension UISearchBar: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } internal extension TextInputTraitable { func apply(_ style: ViewStyle) { style.attributes.forEach { switch $0 { case .autocapitalizationType(let type): autocapitalizationType = type case .autocorrectionType(let type): autocorrectionType = type case .spellCheckingType(let type): spellCheckingType = type case .keyboardType(let type): keyboardType = type case .keyboardAppearance(let appearance): keyboardAppearance = appearance case .returnKeyType(let type): returnKeyType = type case .enablesReturnKeyAutomatically(let enables): enablesReturnKeyAutomatically = enables case .isSecureTextEntry(let isSecure): isSecureTextEntry = isSecure case .textContentType(let type): textContentTypeProxy = type default: break } } } }
mit
mluedke2/jsonjam
Pod/Classes/JSONHelper.swift
2
9844
// // JSONHelper.swift // // Created by Baris Sencan on 28/08/2014. // Copyright 2014 Baris Sencan // // Distributed under the permissive zlib license // Get the latest version from here: // // https://github.com/isair/JSONHelper // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // import Foundation /// A type of dictionary that only uses strings for keys and can contain any /// type of object as a value. public typealias JSONDictionary = [String: AnyObject] /// Operator for use in deserialization operations. infix operator <-- { associativity right precedence 150 } /// Returns nil if given object is of type NSNull. /// /// :param: object Object to convert. /// /// :returns: nil if object is of type NSNull, else returns the object itself. private func convertToNilIfNull(object: AnyObject?) -> AnyObject? { if object is NSNull { return nil } return object } /// MARK: Primitive Type Deserialization // For optionals. public func <-- <T>(inout property: T?, value: AnyObject?) -> T? { var newValue: T? "" if let unwrappedValue: AnyObject = convertToNilIfNull(value) { // We unwrapped the given value successfully, try to convert. if let convertedValue = unwrappedValue as? T { // Convert by just type-casting. newValue = convertedValue } else { // Convert by processing the value first. switch property { case is Int?: if unwrappedValue is String { if let intValue = "\(unwrappedValue)".toInt() { newValue = intValue as? T } } case is NSURL?: newValue = NSURL(string: "\(unwrappedValue)") as? T case is NSDate?: if let timestamp = unwrappedValue as? Int { newValue = NSDate(timeIntervalSince1970: Double(timestamp)) as? T } else if let timestamp = unwrappedValue as? Double { newValue = NSDate(timeIntervalSince1970: timestamp) as? T } else if let timestamp = unwrappedValue as? NSNumber { newValue = NSDate(timeIntervalSince1970: timestamp.doubleValue) as? T } default: break } } } property = newValue return property } // For non-optionals. public func <-- <T>(inout property: T, value: AnyObject?) -> T { var newValue: T? newValue <-- value if let newValue = newValue { property = newValue } return property } // Special handling for value and format pair to NSDate conversion. public func <-- (inout property: NSDate?, valueAndFormat: (AnyObject?, AnyObject?)) -> NSDate? { var newValue: NSDate? if let dateString = convertToNilIfNull(valueAndFormat.0) as? String { if let formatString = convertToNilIfNull(valueAndFormat.1) as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString if let newDate = dateFormatter.dateFromString(dateString) { newValue = newDate } } } property = newValue return property } public func <-- (inout property: NSDate, valueAndFormat: (AnyObject?, AnyObject?)) -> NSDate { var date: NSDate? date <-- valueAndFormat if let date = date { property = date } return property } // MARK: Primitive Array Deserialization public func <-- (inout array: [String]?, value: AnyObject?) -> [String]? { if let stringArray = convertToNilIfNull(value) as? [String] { array = stringArray } else { array = nil } return array } public func <-- (inout array: [String], value: AnyObject?) -> [String] { var newValue: [String]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Int]?, value: AnyObject?) -> [Int]? { if let intArray = convertToNilIfNull(value) as? [Int] { array = intArray } else { array = nil } return array } public func <-- (inout array: [Int], value: AnyObject?) -> [Int] { var newValue: [Int]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Float]?, value: AnyObject?) -> [Float]? { if let floatArray = convertToNilIfNull(value) as? [Float] { array = floatArray } else { array = nil } return array } public func <-- (inout array: [Float], value: AnyObject?) -> [Float] { var newValue: [Float]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Double]?, value: AnyObject?) -> [Double]? { if let doubleArrayDoubleExcitement = convertToNilIfNull(value) as? [Double] { array = doubleArrayDoubleExcitement } else { array = nil } return array } public func <-- (inout array: [Double], value: AnyObject?) -> [Double] { var newValue: [Double]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Bool]?, value: AnyObject?) -> [Bool]? { if let boolArray = convertToNilIfNull(value) as? [Bool] { array = boolArray } else { array = nil } return array } public func <-- (inout array: [Bool], value: AnyObject?) -> [Bool] { var newValue: [Bool]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSURL]?, value: AnyObject?) -> [NSURL]? { if let stringURLArray = convertToNilIfNull(value) as? [String] { array = [NSURL]() for stringURL in stringURLArray { if let url = NSURL(string: stringURL) { array!.append(url) } } } else { array = nil } return array } public func <-- (inout array: [NSURL], value: AnyObject?) -> [NSURL] { var newValue: [NSURL]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSDate]?, valueAndFormat: (AnyObject?, AnyObject?)) -> [NSDate]? { var newValue: [NSDate]? if let dateStringArray = convertToNilIfNull(valueAndFormat.0) as? [String] { if let formatString = convertToNilIfNull(valueAndFormat.1) as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString newValue = [NSDate]() for dateString in dateStringArray { if let date = dateFormatter.dateFromString(dateString) { newValue!.append(date) } } } } array = newValue return array } public func <-- (inout array: [NSDate], valueAndFormat: (AnyObject?, AnyObject?)) -> [NSDate] { var newValue: [NSDate]? newValue <-- valueAndFormat if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSDate]?, value: AnyObject?) -> [NSDate]? { if let timestamps = convertToNilIfNull(value) as? [AnyObject] { array = [NSDate]() for timestamp in timestamps { var date: NSDate? date <-- timestamp if date != nil { array!.append(date!) } } } else { array = nil } return array } public func <-- (inout array: [NSDate], value: AnyObject?) -> [NSDate] { var newValue: [NSDate]? newValue <-- value if let newValue = newValue { array = newValue } return array } // MARK: Custom Object Deserialization public protocol Deserializable { init(data: JSONDictionary) } public func <-- <T: Deserializable>(inout instance: T?, dataObject: AnyObject?) -> T? { if let data = convertToNilIfNull(dataObject) as? JSONDictionary { instance = T(data: data) } else { instance = nil } return instance } public func <-- <T: Deserializable>(inout instance: T, dataObject: AnyObject?) -> T { var newInstance: T? newInstance <-- dataObject if let newInstance = newInstance { instance = newInstance } return instance } // MARK: Custom Object Array Deserialization public func <-- <T: Deserializable>(inout array: [T]?, dataObject: AnyObject?) -> [T]? { if let dataArray = convertToNilIfNull(dataObject) as? [JSONDictionary] { array = [T]() for data in dataArray { array!.append(T(data: data)) } } else { array = nil } return array } public func <-- <T: Deserializable>(inout array: [T], dataObject: AnyObject?) -> [T] { var newArray: [T]? newArray <-- dataObject if let newArray = newArray { array = newArray } return array } // MARK: JSON String Deserialization private func dataStringToObject(dataString: String) -> AnyObject? { var data: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)! var error: NSError? return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) } public func <-- <T: Deserializable>(inout instance: T?, dataString: String) -> T? { return instance <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout instance: T, dataString: String) -> T { return instance <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout array: [T]?, dataString: String) -> [T]? { return array <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout array: [T], dataString: String) -> [T] { return array <-- dataStringToObject(dataString) }
mit
4taras4/totp-auth
TOTP/ViperModules/AddItemManualy/Module/Router/AddItemManualyRouter.swift
1
403
// // AddItemManualyAddItemManualyRouter.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import UIKit final class AddItemManualyRouter: AddItemManualyRouterInput { weak var transitionHandler: UIViewController! func popToRoot() { transitionHandler.navigationController?.popToRootViewController(animated: true) } }
mit
apple/swift-corelibs-foundation
Sources/Foundation/NSDate.swift
1
15544
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // @_implementationOnly import CoreFoundation public typealias TimeInterval = Double public var NSTimeIntervalSince1970: Double { return 978307200.0 } #if os(Windows) extension TimeInterval { init(_ ftTime: FILETIME) { self = Double((ftTime.dwHighDateTime << 32) | ftTime.dwLowDateTime) - NSTimeIntervalSince1970; } } #else extension timeval { internal init(_timeIntervalSince1970: TimeInterval) { let (integral, fractional) = modf(_timeIntervalSince1970) self.init(tv_sec: time_t(integral), tv_usec: suseconds_t(1.0e6 * fractional)) } } #endif open class NSDate : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFDate open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Date: return isEqual(to: other) case let other as NSDate: return isEqual(to: Date(timeIntervalSinceReferenceDate: other.timeIntervalSinceReferenceDate)) default: return false } } deinit { _CFDeinit(self) } internal final var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } internal let _base = _CFInfo(typeID: CFDateGetTypeID()) internal let _timeIntervalSinceReferenceDate: TimeInterval open var timeIntervalSinceReferenceDate: TimeInterval { return _timeIntervalSinceReferenceDate } open class var timeIntervalSinceReferenceDate: TimeInterval { return Date().timeIntervalSinceReferenceDate } public convenience override init() { self.init(timeIntervalSinceReferenceDate: CFAbsoluteTimeGetCurrent()) } public required init(timeIntervalSinceReferenceDate ti: TimeInterval) { _timeIntervalSinceReferenceDate = ti } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let ti = aDecoder.decodeDouble(forKey: "NS.time") self.init(timeIntervalSinceReferenceDate: ti) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(_timeIntervalSinceReferenceDate, forKey: "NS.time") } /** A string representation of the date object (read-only). The representation is useful for debugging only. There are a number of options to acquire a formatted string for a date including: date formatters (see [NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and [Data Formatting Guide](//apple_ref/doc/uid/10000029i)), and the `NSDate` methods `descriptionWithLocale:`, `dateWithCalendarFormat:timeZone:`, and `descriptionWithCalendarFormat:timeZone:locale:`. */ open override var description: String { let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, nil, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle) let timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, 0.0) CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, timeZone) CFDateFormatterSetFormat(dateFormatterRef, "uuuu-MM-dd HH:mm:ss '+0000'"._cfObject) return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject } /** Returns a string representation of the receiver using the given locale. - Parameter locale: An `NSLocale` object. If you pass `nil`, `NSDate` formats the date in the same way as the `description` property. - Returns: A string representation of the receiver, using the given locale, or if the locale argument is `nil`, in the international format `YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone offset in hours and minutes from UTC (for example, "2001-03-24 10:45:32 +0600") */ open func description(with locale: Locale?) -> String { guard let aLocale = locale else { return description } let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, aLocale._cfObject, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle) CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, CFTimeZoneCopySystem()) return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject } internal override var _cfTypeID: CFTypeID { return CFDateGetTypeID() } } extension NSDate { open func timeIntervalSince(_ anotherDate: Date) -> TimeInterval { return self.timeIntervalSinceReferenceDate - anotherDate.timeIntervalSinceReferenceDate } open var timeIntervalSinceNow: TimeInterval { return timeIntervalSince(Date()) } open var timeIntervalSince1970: TimeInterval { return timeIntervalSinceReferenceDate + NSTimeIntervalSince1970 } open func addingTimeInterval(_ ti: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate:_timeIntervalSinceReferenceDate + ti) } open func earlierDate(_ anotherDate: Date) -> Date { if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } else { return anotherDate } } open func laterDate(_ anotherDate: Date) -> Date { if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate { return anotherDate } else { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } } open func compare(_ other: Date) -> ComparisonResult { let t1 = self.timeIntervalSinceReferenceDate let t2 = other.timeIntervalSinceReferenceDate if t1 < t2 { return .orderedAscending } else if t1 > t2 { return .orderedDescending } else { return .orderedSame } } open func isEqual(to otherDate: Date) -> Bool { return timeIntervalSinceReferenceDate == otherDate.timeIntervalSinceReferenceDate } } extension NSDate { internal static let _distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0) open class var distantFuture: Date { return _distantFuture } internal static let _distantPast = Date(timeIntervalSinceReferenceDate: -63113904000.0) open class var distantPast: Date { return _distantPast } public convenience init(timeIntervalSinceNow secs: TimeInterval) { self.init(timeIntervalSinceReferenceDate: secs + Date().timeIntervalSinceReferenceDate) } public convenience init(timeIntervalSince1970 secs: TimeInterval) { self.init(timeIntervalSinceReferenceDate: secs - NSTimeIntervalSince1970) } public convenience init(timeInterval secsToBeAdded: TimeInterval, since date: Date) { self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + secsToBeAdded) } } extension NSDate: _SwiftBridgeable { typealias SwiftType = Date var _swiftObject: Date { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } } extension CFDate : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSDate typealias SwiftType = Date internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Date { return _nsObject._swiftObject } } extension Date : _NSBridgeable { typealias NSType = NSDate typealias CFType = CFDate internal var _nsObject: NSType { return NSDate(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } internal var _cfObject: CFType { return _nsObject._cfObject } } open class NSDateInterval : NSObject, NSCopying, NSSecureCoding { /* NSDateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. NSDateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date. */ open private(set) var startDate: Date open var endDate: Date { get { if duration == 0 { return startDate } else { return startDate + duration } } } open private(set) var duration: TimeInterval // This method initializes an NSDateInterval object with start and end dates set to the current date and the duration set to 0. public convenience override init() { self.init(start: Date(), duration: 0) } public required convenience init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let start = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else { coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil)) return nil } guard let end = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else { coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil)) return nil } self.init(start: start._swiftObject, end: end._swiftObject) } // This method will throw an exception if the duration is less than 0. public init(start startDate: Date, duration: TimeInterval) { self.startDate = startDate self.duration = duration } // This method will throw an exception if the end date comes before the start date. public convenience init(start startDate: Date, end endDate: Date) { self.init(start: startDate, duration: endDate.timeIntervalSince(startDate)) } open func copy(with zone: NSZone?) -> Any { return NSDateInterval(start: startDate, duration: duration) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(startDate._nsObject, forKey: "NS.startDate") aCoder.encode(endDate._nsObject, forKey: "NS.endDate") } public static var supportsSecureCoding: Bool { return true } /* (ComparisonResult)compare:(NSDateInterval *) prioritizes ordering by start date. If the start dates are equal, then it will order by duration. e.g. Given intervals a and b a. |-----| b. |-----| [a compare:b] would return NSOrderAscending because a's startDate is earlier in time than b's start date. In the event that the start dates are equal, the compare method will attempt to order by duration. e.g. Given intervals c and d c. |-----| d. |---| [c compare:d] would result in NSOrderDescending because c is longer than d. If both the start dates and the durations are equal, then the intervals are considered equal and NSOrderedSame is returned as the result. */ open func compare(_ dateInterval: DateInterval) -> ComparisonResult { let result = startDate.compare(dateInterval.start) if result == .orderedSame { if self.duration < dateInterval.duration { return .orderedAscending } if self.duration > dateInterval.duration { return .orderedDescending } return .orderedSame } return result } open func isEqual(to dateInterval: DateInterval) -> Bool { return startDate == dateInterval.start && duration == dateInterval.duration } open func intersects(_ dateInterval: DateInterval) -> Bool { return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(startDate) || dateInterval.contains(endDate) } /* This method returns an NSDateInterval object that represents the interval where the given date interval and the current instance intersect. In the event that there is no intersection, the method returns nil. */ open func intersection(with dateInterval: DateInterval) -> DateInterval? { if !intersects(dateInterval) { return nil } if isEqual(to: dateInterval) { return DateInterval(start: startDate, duration: duration) } let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate let timeIntervalForSelfEnd = startDate.timeIntervalSinceReferenceDate let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate let resultStartDate : Date if timeIntervalForGivenStart >= timeIntervalForSelfStart { resultStartDate = dateInterval.start } else { // self starts after given resultStartDate = startDate } let resultEndDate : Date if timeIntervalForGivenEnd >= timeIntervalForSelfEnd { resultEndDate = endDate } else { // given ends before self resultEndDate = dateInterval.end } return DateInterval(start: resultStartDate, end: resultEndDate) } open func contains(_ date: Date) -> Bool { let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate let timeIntervalforSelfEnd = endDate.timeIntervalSinceReferenceDate if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) { return true } return false } } extension NSDate : _StructTypeBridgeable { public typealias _StructType = Date public func _bridgeToSwift() -> Date { return Date._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateInterval : _StructTypeBridgeable { public typealias _StructType = DateInterval public func _bridgeToSwift() -> DateInterval { return DateInterval._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateInterval : _SwiftBridgeable { var _swiftObject: DateInterval { return _bridgeToSwift() } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Blockchain/AppDelegate/AppDelegate+LifeCycle.swift
1
666
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import UIKit extension AppDelegate { func applicationWillResignActive(_ application: UIApplication) { viewStore.send(.appDelegate(.willResignActive)) } func applicationDidEnterBackground(_ application: UIApplication) { viewStore.send(.appDelegate(.didEnterBackground(application))) } func applicationWillEnterForeground(_ application: UIApplication) { viewStore.send(.appDelegate(.willEnterForeground(application))) } func applicationDidBecomeActive(_ application: UIApplication) { viewStore.send(.appDelegate(.didBecomeActive)) } }
lgpl-3.0
huonw/swift
test/stdlib/StringOrderRelation.swift
41
559
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var StringOrderRelationTestSuite = TestSuite("StringOrderRelation") StringOrderRelationTestSuite.test("StringOrderRelation/ASCII/NullByte") { let baseString = "a" let nullbyteString = "a\0" expectTrue(baseString < nullbyteString) expectTrue(baseString <= nullbyteString) expectFalse(baseString > nullbyteString) expectFalse(baseString >= nullbyteString) expectFalse(baseString == nullbyteString) expectTrue(baseString != nullbyteString) } runAllTests()
apache-2.0
900116/GodEyeClear
Classes/Model/LeakRecordModel.swift
1
1337
// // LeakRecordModel.swift // Pods // // Created by zixun on 17/1/12. // // import Foundation import Realm import RealmSwift final class LeakRecordModel: Object { dynamic open var clazz: String! dynamic open var address: String! init(obj:NSObject) { super.init() self.clazz = NSStringFromClass(obj.classForCoder) self.address = String(format:"%p", obj) } init(clazz:String, address: String) { super.init() self.clazz = clazz self.address = address } required init() { super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm:realm,schema:schema) } required init(value: Any, schema: RLMSchema) { super.init(value:value,schema:schema) } } extension LeakRecordModel : RecordORMProtocol { static var type: RecordType { return RecordType.leak } func attributeString() -> NSAttributedString { let result = NSMutableAttributedString() result.append(self.headerString()) return result } private func headerString() -> NSAttributedString { return self.headerString(with: "Leak", content: "[\(self.clazz): \(self.address)]", color: UIColor(hex: 0xB754C4)) } }
mit
ORT-Interactive-GmbH/OnlineL10n
OnlineL10n/UI/CountryCell.swift
1
762
// // CountryCell.swift // SwiftLocalization // // Created by Sebastian Westemeyer on 28.04.16. // Copyright © 2016 ORT Interactive. All rights reserved. // import Foundation public let CountryCellStoryboardId = "CountryCell" class CountryCell: UITableViewCell { @IBOutlet weak var imageViewFlag: UIImageView! @IBOutlet weak var labelName: UILabel! @IBOutlet weak var constraintImageWidth: NSLayoutConstraint! func display(flag: Data?) { if (flag == nil) { imageViewFlag.isHidden = true constraintImageWidth.constant = 0.0 } else { imageViewFlag.isHidden = false constraintImageWidth.constant = 40.0 imageViewFlag.image = UIImage(data: flag!) } } }
mit
ORT-Interactive-GmbH/OnlineL10n
OnlineL10n/UI/UIExtensions.swift
1
2648
// // UIExtensions.swift // OnlineL18N // // Created by Sebastian Westemeyer on 27.04.16. // Copyright © 2016 ORT Interactive. All rights reserved. // import Foundation import UIKit @objc extension UILabel { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } } @objc extension UITextField { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } public func subscribeToLanguage(manager: LocalizationProvider, placeholder: String) { manager.subscribeToChange(object: self, key: placeholder, block: { (x: Any?) in self.placeholder = x as? String }) self.placeholder = manager.value(key: placeholder) } } @objc extension UITextView { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } } @objc extension UIButton { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.setTitle(x as? String, for: .normal) }) self.setTitle(manager.value(key: key), for: .normal) } } @objc extension UISegmentedControl { public func subscribeToLanguage(manager: LocalizationProvider, key: String, index: Int) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.setTitle(x as? String, forSegmentAt: index) }) self.setTitle(manager.value(key: key), forSegmentAt: index) } } @objc extension UIViewController { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.title = x as? String }) self.title = manager.value(key: key) } } @objc extension UIBarButtonItem { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.title = x as? String }) self.title = manager.value(key: key) } }
mit
Jnosh/swift
test/SourceKit/NameTranslation/enum.swift
31
1363
import Foo func foo1() { _ = FooComparisonResult.orderedAscending _ = FooComparisonResult.orderedDescending _ = FooComparisonResult.orderedSame _ = FooRuncingOptions.enableMince _ = FooRuncingOptions.enableQuince } // REQUIRES: objc_interop // RUN: %sourcekitd-test -req=translate -objc-name orderedSome -pos=4:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK1 %s // RUN: %sourcekitd-test -req=translate -objc-selector orderedSome -pos=4:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK-NONE %s // RUN: %sourcekitd-test -req=translate -objc-name enableThird -pos=7:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s // RUN: %sourcekitd-test -req=translate -objc-name FooRuncingEnableThird -pos=7:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s // RUN: %sourcekitd-test -req=translate -objc-name FooRuncinEnableThird -pos=7:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s // RUN: %sourcekitd-test -req=translate -objc-name FooRinEnableThird -pos=7:30 %s -- -F %S/Inputs/mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK3 %s // CHECK1: orderedSome // CHECK-NONE: <empty name translation info> // CHECK2: enableThird // CHECK3: inEnableThird
apache-2.0
johnfairh/TMLPersistentContainer
Sources/ModelVersionGraph.swift
1
3202
// // ModelVersionGraph.swift // TMLPersistentContainer // // Distributed under the ISC license, see LICENSE. // import Foundation import CoreData /// Manage the graph of model versions and generate routes through it. /// Class is a container + facade onto the nodes + edges classes, and /// does type-translation to the graph solver. /// @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) struct ModelVersionGraph: LogMessageEmitter { let logMessageHandler: LogMessage.Handler? let nodes: ModelVersionNodes let edges: ModelVersionEdges } @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) extension ModelVersionGraph { /// Initialize a new, empty graph init(logMessageHandler: LogMessage.Handler?) { self.logMessageHandler = logMessageHandler nodes = ModelVersionNodes(logMessageHandler: logMessageHandler) edges = ModelVersionEdges(logMessageHandler: logMessageHandler) } /// Create a new graph func filtered(order: ModelVersionOrder, allowInferredMappings: Bool) -> ModelVersionGraph { let newGraph = ModelVersionGraph(logMessageHandler: logMessageHandler, nodes: nodes.filtered(order: order), edges: edges.filtered(order: order, allowInferredMappings: allowInferredMappings)) newGraph.logAll(.info, "Filtered graph under order \(order) with allowInferredMappings \(allowInferredMappings):") return newGraph } /// Analyze the model and mapping model files and build the migration graph between them func discover(from bundles: [Bundle]) { log(.info, "Starting model discovery from bundles \(bundles)") nodes.discover(from: bundles) edges.discover(from: bundles, between: nodes.nodes) logAll(.info, "Model graph discovery complete.") } /// Log the summary contents of the graph func logAll(_ level: LogLevel, _ message: String) { log(level, message) log(level, "Model graph nodes: \(self.nodes.nodes)") log(level, "Model graph edges: \(self.edges.edges)") } /// Log the details of discovered node metadata func logNodeMetadata(_ level: LogLevel) { nodes.logMetadata(level) } /// Find the starting point in the graph func nodeForStoreMetadata(_ storeMetadata: PersistentStoreMetadata, configuration: String?) -> ModelVersionNode? { return nodes.nodeForStoreMetadata(storeMetadata, configuration: configuration) } /// Find the ending point in the graph func nodeForObjectModel(_ objectModel: NSManagedObjectModel) -> ModelVersionNode? { return nodes.nodeForObjectModel(objectModel) } /// Find the best path through the versions or throw if there is none func findPath(source: ModelVersionNode, destination: ModelVersionNode) throws -> [ModelVersionEdge] { precondition(source != destination, "Logic error - no migration required") let graph = Graph(nodeCount: nodes.nodes.count, edges: edges.edges, logMessageHandler: logMessageHandler) return try graph.findPath(source: source.name, destination: destination.name) } }
isc
bazscsa/sample-test-ios-quick
BitriseTestingSample/BitriseTestingSampleTests/BitriseTestingSampleTests.swift
1
1085
// // BitriseTestingSampleTests.swift // BitriseTestingSampleTests // // Created by Viktor Benei on 6/17/15. // Copyright (c) 2015 Bitrise. All rights reserved. // import Quick import Nimble class BitriseTestingSampleTests: QuickSpec { var viewController: ViewController! override func spec() { beforeEach { self.viewController = ViewController() } describe(".viewDidLoad()") { beforeEach { let _ = self.viewController.view } } describe(".viewWillDisappear()") { beforeEach { self.viewController.viewWillDisappear(false) } } describe("The testButton") { it("increase the variable value") { let variable = self.viewController.variable let label = self.viewController.testButton self.viewController.testButtonTouched(self) expect(variable).toNot(beLessThan(self.viewController.variable)) } } } }
mit
carabina/DDMathParser
MathParser/Functions+Defaults.swift
2
39055
// // StandardFunctions.swift // DDMathParser // // Created by Dave DeLong on 8/20/15. // // import Foundation public extension Function { private static let largestIntegerFactorial: Int = { var n = Int.max var i = 2 while i < n { n /= i i++ } return i - 1 }() // MARK: - Angle mode helpers internal static func _dtor(d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .Degrees else { return d } return d / 180 * M_PI } internal static func _rtod(d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .Degrees else { return d } return d / M_PI * 180 } public static let standardFunctions: Array<Function> = [ add, subtract, multiply, divide, mod, negate, factorial, factorial2, pow, sqrt, cuberoot, nthroot, random, abs, percent, log, ln, log2, exp, and, or, not, xor, lshift, rshift, sum, product, count, min, max, average, median, stddev, ceil, floor, sin, cos, tan, asin, acos, atan, atan2, csc, sec, cotan, acsc, asec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, csch, sech, cotanh, acsch, asech, acotanh, versin, vercosin, coversin, covercosin, haversin, havercosin, hacoversin, hacovercosin, exsec, excsc, crd, dtor, rtod, phi, pi, pi_2, pi_4, tau, sqrt2, e, log2e, log10e, ln2, ln10, l_and, l_or, l_not, l_eq, l_neq, l_lt, l_gt, l_ltoe, l_gtoe, l_if ] // MARK: - Basic functions public static let add = Function(name: "add", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 + arg2 }) public static let subtract = Function(name: "subtract", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 - arg2 }) public static let multiply = Function(names: ["multiply", "implicitmultiply"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 * arg2 }) public static let divide = Function(name: "divide", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) guard arg2 != 0 else { throw EvaluationError.DivideByZero } return arg1 / arg2 }) public static let mod = Function(names: ["mod", "modulo"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return fmod(arg1, arg2) }) public static let negate = Function(name: "negate", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return -arg1 }) public static let factorial = Function(name: "factorial", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1.factorial() }) public static let factorial2 = Function(name: "factorial2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 >= 1 else { throw EvaluationError.InvalidArguments } guard arg1 == Darwin.floor(arg1) else { throw EvaluationError.InvalidArguments } if arg1 % 2 == 0 { let k = arg1 / 2 return Darwin.pow(2, k) * k.factorial() } else { let k = (arg1 + 1) / 2 let numerator = (2*k).factorial() let denominator = Darwin.pow(2, k) * k.factorial() guard denominator != 0 else { throw EvaluationError.DivideByZero } return numerator / denominator } }) public static let pow = Function(name: "pow", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Darwin.pow(arg1, arg2) }) public static let sqrt = Function(name: "sqrt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let value = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sqrt(value) }) public static let cuberoot = Function(name: "cuberoot", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.pow(arg1, 1.0/3.0) }) public static let nthroot = Function(name: "nthroot", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) guard arg2 != 0 else { throw EvaluationError.DivideByZero } if arg1 < 0 && arg2 % 2 == 1 { // for negative numbers with an odd root, the result will be negative let root = Darwin.pow(-arg1, 1/arg2) return -root } else { return Darwin.pow(arg1, 1/arg2) } }) public static let random = Function(name: "random", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count <= 2 else { throw EvaluationError.InvalidArguments } var argValues = Array<Double>() for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) argValues.append(argValue) } let lowerBound = argValues.count > 0 ? argValues[0] : DBL_MIN let upperBound = argValues.count > 1 ? argValues[1] : DBL_MAX guard lowerBound < upperBound else { throw EvaluationError.InvalidArguments } let range = upperBound - lowerBound return (drand48() % range) + lowerBound }) public static let log = Function(name: "log", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log10(arg1) }) public static let ln = Function(name: "ln", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log(arg1) }) public static let log2 = Function(name: "log2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log2(arg1) }) public static let exp = Function(name: "exp", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.exp(arg1) }) public static let abs = Function(name: "abs", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Swift.abs(arg1) }) public static let percent = Function(name: "percent", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let percentArgument = args[0] let percentValue = try evaluator.evaluate(percentArgument, substitutions: substitutions) let percent = percentValue / 100 let percentExpression = percentArgument.parent let percentContext = percentExpression?.parent guard let contextKind = percentContext?.kind else { return percent } guard case let .Function(f, contextArgs) = contextKind else { return percent } // must be XXXX + n% or XXXX - n% guard let builtIn = BuiltInOperator(rawValue: f) where builtIn == .Add || builtIn == .Minus else { return percent } // cannot be n% + XXXX or n% - XXXX guard contextArgs[1] === percentExpression else { return percent } let context = try evaluator.evaluate(contextArgs[0], substitutions: substitutions) return context * percent }) // MARK: - Bitwise functions public static let and = Function(name: "and", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) & Int(arg2)) }) public static let or = Function(name: "or", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) | Int(arg2)) }) public static let not = Function(name: "not", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Double(~Int(arg1)) }) public static let xor = Function(name: "xor", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) ^ Int(arg2)) }) public static let rshift = Function(name: "rshift", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) >> Int(arg2)) }) public static let lshift = Function(name: "lshift", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) << Int(arg2)) }) // MARK: - Aggregate functions public static let average = Function(names: ["average", "avg", "mean"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } let value = try sum.evaluator(args, substitutions, evaluator) return value / Double(args.count) }) public static let sum = Function(names: ["sum", "∑"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = 0.0 for arg in args { value += try evaluator.evaluate(arg, substitutions: substitutions) } return value }) public static let product = Function(names: ["product", "∏"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = 1.0 for arg in args { value *= try evaluator.evaluate(arg, substitutions: substitutions) } return value }) public static let count = Function(name: "count", evaluator: { (args, substitutions, evaluator) throws -> Double in return Double(args.count) }) public static let min = Function(name: "min", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = DBL_MAX for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) value = Swift.min(value, argValue) } return value }) public static let max = Function(name: "max", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = DBL_MIN for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) value = Swift.max(value, argValue) } return value }) public static let median = Function(name: "median", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count >= 2 else { throw EvaluationError.InvalidArguments } var evaluated = Array<Double>() for arg in args { evaluated.append(try evaluator.evaluate(arg, substitutions: substitutions)) } if evaluated.count % 2 == 1 { let index = evaluated.count / 2 return evaluated[index] } else { let highIndex = evaluated.count / 2 let lowIndex = highIndex - 1 return Double((evaluated[highIndex] + evaluated[lowIndex]) / 2) } }) public static let stddev = Function(name: "stddev", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count >= 2 else { throw EvaluationError.InvalidArguments } let avg = try average.evaluator(args, substitutions, evaluator) var stddev = 0.0 for arg in args { let value = try evaluator.evaluate(arg, substitutions: substitutions) let diff = avg - value stddev += (diff * diff) } return Darwin.sqrt(stddev / Double(args.count)) }) public static let ceil = Function(name: "ceil", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.ceil(arg1) }) public static let floor = Function(names: ["floor", "trunc"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.floor(arg1) }) // MARK: - Trigonometric functions public static let sin = Function(name: "sin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let cos = Function(name: "cos", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let tan = Function(name: "tan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.tan(Function._dtor(arg1, evaluator: evaluator)) }) public static let asin = Function(name: "asin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.asin(arg1), evaluator: evaluator) }) public static let acos = Function(name: "acos", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.acos(arg1), evaluator: evaluator) }) public static let atan = Function(name: "atan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.atan(arg1), evaluator: evaluator) }) public static let atan2 = Function(name: "atan2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Function._rtod(Darwin.atan2(arg1, arg2), evaluator: evaluator) }) public static let csc = Function(name: "csc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let sec = Function(name: "sec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let cotan = Function(name: "cotan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.tan(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let acsc = Function(name: "acsc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.asin(1.0 / arg1), evaluator: evaluator) }) public static let asec = Function(name: "asec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.acos(1.0 / arg1), evaluator: evaluator) }) public static let acotan = Function(name: "acotan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.atan(1.0 / arg1), evaluator: evaluator) }) // MARK: - Hyperbolic trigonometric functions public static let sinh = Function(name: "sinh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sinh(arg1) }) public static let cosh = Function(name: "cosh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.cosh(arg1) }) public static let tanh = Function(name: "tanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.tanh(arg1) }) public static let asinh = Function(name: "asinh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.asinh(arg1) }) public static let acosh = Function(name: "acosh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.acosh(arg1) }) public static let atanh = Function(name: "atanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.atanh(arg1) }) public static let csch = Function(name: "csch", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.sinh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let sech = Function(name: "sech", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.cosh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let cotanh = Function(name: "cotanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.tanh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let acsch = Function(name: "acsch", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.asinh(1.0 / arg1) }) public static let asech = Function(name: "asech", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.acosh(1.0 / arg1) }) public static let acotanh = Function(name: "acotanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.atanh(1.0 / arg1) }) // MARK: - Geometric functions public static let versin = Function(names: ["versin", "vers", "ver"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 - Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let vercosin = Function(names: ["vercosin", "vercos"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 + Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let coversin = Function(names: ["coversin", "cvs"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 - Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let covercosin = Function(name: "covercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 + Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let haversin = Function(name: "haversin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try versin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let havercosin = Function(name: "havercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try vercosin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let hacoversin = Function(name: "hacoversin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try coversin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let hacovercosin = Function(name: "hacovercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try covercosin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let exsec = Function(name: "exsec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let cosArg1 = Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) guard cosArg1 != 0 else { throw EvaluationError.DivideByZero } return (1.0/cosArg1) - 1.0 }) public static let excsc = Function(name: "excsc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) guard sinArg1 != 0 else { throw EvaluationError.DivideByZero } return (1.0/sinArg1) - 1.0 }) public static let crd = Function(names: ["crd", "chord"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: evaluator) / 2.0) return 2 * sinArg1 }) public static let dtor = Function(name: "dtor", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1 / 180.0 * M_PI }) public static let rtod = Function(name: "rtod", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1 / M_PI * 180 }) // MARK: - Constant functions public static let phi = Function(names: ["phi", "ϕ"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return 1.6180339887498948 }) public static let pi = Function(names: ["pi", "π", "tau_2"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI }) public static let pi_2 = Function(names: ["pi_2", "tau_4"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI_2 }) public static let pi_4 = Function(names: ["pi_4", "tau_8"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI_4 }) public static let tau = Function(names: ["tau", "τ"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return 2 * M_PI }) public static let sqrt2 = Function(name: "sqrt2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_SQRT2 }) public static let e = Function(name: "e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_E }) public static let log2e = Function(name: "log2e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LOG2E }) public static let log10e = Function(name: "log10e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LOG10E }) public static let ln2 = Function(name: "ln2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LN2 }) public static let ln10 = Function(name: "ln10", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LN10 }) // MARK: - Logical Functions public static let l_and = Function(name: "l_and", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != 0 && arg2 != 0) ? 1.0 : 0.0 }) public static let l_or = Function(name: "l_or", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != 0 || arg2 != 0) ? 1.0 : 0.0 }) public static let l_not = Function(name: "l_not", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return (arg1 == 0) ? 1.0 : 0.0 }) public static let l_eq = Function(name: "l_eq", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 == arg2) ? 1.0 : 0.0 }) public static let l_neq = Function(name: "l_neq", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != arg2) ? 1.0 : 0.0 }) public static let l_lt = Function(name: "l_lt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 < arg2) ? 1.0 : 0.0 }) public static let l_gt = Function(name: "l_gt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 > arg2) ? 1.0 : 0.0 }) public static let l_ltoe = Function(name: "l_ltoe", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 <= arg2) ? 1.0 : 0.0 }) public static let l_gtoe = Function(name: "l_gtoe", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 == arg2) ? 1.0 : 0.0 }) public static let l_if = Function(names: ["l_if", "if"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 3 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) if arg1 != 0 { return try evaluator.evaluate(args[1], substitutions: substitutions) } else { return try evaluator.evaluate(args[2], substitutions: substitutions) } }) }
mit
pcperini/Thrust
Thrust/Source/Range+ThrustExtensions.swift
1
2240
// // Range+ThrustExtensions.swift // Thrust // // Created by Patrick Perini on 9/13/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation extension Range { // MARK: Properties /// Returns an array containing each element in the range. var all: [T] { return self.map({ $0 }) } // MARK: Accessors /** Returns whether the given value is within the range. :param: element A value. :returns: True if the element is greater than or equal to the range's start index, and less than the range's end index; and false otherwise. */ func contains(element: T) -> Bool { return self.all.contains(element) } /** Returns an intersection of this range and the given range. :example: (0 ..< 10).intersection(5 ..< 15) == 5 ..< 10 :param: range A range to intersect with this range. :returns: An intersection of this range and the given range. */ func intersection<T: Comparable>(range: Range<T>) -> Range<T> { var maxStartIndex: T = max(self.startIndex as T, range.startIndex) as T var minEndIndex: T = min(self.endIndex as T, range.endIndex) as T return Range<T>(start: maxStartIndex, end: minEndIndex) } /** Returns whether the given range intersects this range. :param: range A range to intersect with this range. :returns: true, if the intersection of the ranges is not empty, false otherwise. */ func intersects<T: Comparable>(range: Range<T>) -> Bool { var intersection = self.intersection(range) return !intersection.isEmpty } /** Returns an union of this range and the given range. :example: (0 ..< 10).union(5 ..< 15) == 0 ..< 15 :param: range A range to union with this range. :returns: A union of this range and the given range. */ func union<T: Comparable>(range: Range<T>) -> Range<T> { var minStartIndex: T = min(self.startIndex as T, range.startIndex) as T var maxEndIndex: T = max(self.endIndex as T, range.endIndex) as T return Range<T>(start: minStartIndex, end: maxEndIndex) } }
mit
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Sink.swift
6
1821
// // Sink.swift // RxSwift // // Created by Krunoslav Zaher on 2/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class Sink<Observer: ObserverType> : Disposable { fileprivate let _observer: Observer fileprivate let _cancel: Cancelable private let _disposed = AtomicInt(0) #if DEBUG private let _synchronizationTracker = SynchronizationTracker() #endif init(observer: Observer, cancel: Cancelable) { #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif self._observer = observer self._cancel = cancel } final func forwardOn(_ event: Event<Observer.Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif if isFlagSet(self._disposed, 1) { return } self._observer.on(event) } final func forwarder() -> SinkForward<Observer> { return SinkForward(forward: self) } final var disposed: Bool { return isFlagSet(self._disposed, 1) } func dispose() { fetchOr(self._disposed, 1) self._cancel.dispose() } deinit { #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } final class SinkForward<Observer: ObserverType>: ObserverType { typealias Element = Observer.Element private let _forward: Sink<Observer> init(forward: Sink<Observer>) { self._forward = forward } final func on(_ event: Event<Element>) { switch event { case .next: self._forward._observer.on(event) case .error, .completed: self._forward._observer.on(event) self._forward._cancel.dispose() } } }
mit
chrisjmendez/swift-exercises
Menus/MediumCopycat/MediumCopycat/BookmarksViewController.swift
1
535
// // BookmarksViewController.swift // MediumMenu // // Created by pixyzehn on 2/4/15. // Copyright (c) 2015 pixyzehn. All rights reserved. // import UIKit class BookmarksViewController: BaseViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } }
mit
teaxus/TSAppEninge
StandardProject/StandardProject/AppDelegate.swift
1
3273
// // AppDelegate.swift // StandardProject // // Created by teaxus on 16/5/9. // Copyright © 2016年 teaxus. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. TSAppEngineInit()//初始化框架 SystemInfo.delegate = SystemDelegate() // 设置字体 字体颜色以及大小 UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:UIFont.systemFont(ofSize: 20.0)] self.window = UIWindow(frame: UIScreen.main.bounds) UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) self.window!.makeKeyAndVisible() UINavigationBar.appearance().shadowImage = UIImage.ImageWithColor(color: UIColor.clear) UINavigationBar.appearance().barStyle = .black /************** 引导页 或者进入登陆页*/ //读取上一次程序的登录状态 let login_status = SystemInfo.IsLogin SystemInfo.IsLogin = login_status //因为这个程序是使用游客模式 self.window?.rootViewController = StandardProjectTabBarViewController() 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:. } }
mit
SECH-Tag-EEXCESS-Browser/iOSX-App
SechQueryComposer/SechQueryComposer/EEXCESSrecomendation.swift
1
568
// // EEXCESSrecomendation.swift // SechQueryComposer // // Copyright © 2015 Peter Stoehr. All rights reserved. // import Foundation class EEXCESSRecommendation : CustomStringConvertible { var title : String var provider : String var uri : String var description: String { get { return "Title:\(title) -- Provider:\(provider) -- URI:\(uri)" } } init(title : String, provider : String, uri : String) { self.title = title self.provider = provider self.uri = uri } }
mit
dmrschmidt/DSWaveformImage
Sources/DSWaveformImage/TempiFFT.swift
1
11959
// // TempiFFT.swift // TempiBeatDetection // // Created by John Scalo on 1/12/16. // Copyright © 2016 John Scalo. See accompanying License.txt for terms. /* A functional FFT built atop Apple's Accelerate framework for optimum performance on any device. In addition to simply performing the FFT and providing access to the resulting data, TempiFFT provides the ability to map the FFT spectrum data into logical bands, either linear or logarithmic, for further analysis. E.g. let fft = TempiFFT(withSize: frameSize, sampleRate: 44100) // Setting a window type reduces errors fft.windowType = TempiFFTWindowType.hanning // Perform the FFT fft.fftForward(samples) // Map FFT data to logical bands. This gives 4 bands per octave across 7 octaves = 28 bands. fft.calculateLogarithmicBands(minFrequency: 100, maxFrequency: 11025, bandsPerOctave: 4) // Process some data for i in 0..<fft.numberOfBands { let f = fft.frequencyAtBand(i) let m = fft.magnitudeAtBand(i) } Note that TempiFFT expects a mono signal (i.e. numChannels == 1) which is ideal for performance. */ import Foundation import Accelerate @objc enum TempiFFTWindowType: NSInteger { case none case hanning case hamming } @objc class TempiFFT : NSObject { /// The length of the sample buffer we'll be analyzing. private(set) var size: Int /// The sample rate provided at init time. private(set) var sampleRate: Float /// The Nyquist frequency is ```sampleRate``` / 2 var nyquistFrequency: Float { get { return sampleRate / 2.0 } } // After performing the FFT, contains size/2 magnitudes, one for each frequency band. private var magnitudes: [Float] = [] /// After calling calculateLinearBands() or calculateLogarithmicBands(), contains a magnitude for each band. private(set) var bandMagnitudes: [Float]! /// After calling calculateLinearBands() or calculateLogarithmicBands(), contains the average frequency for each band private(set) var bandFrequencies: [Float]! /// The average bandwidth throughout the spectrum (nyquist / magnitudes.count) var bandwidth: Float { get { return self.nyquistFrequency / Float(self.magnitudes.count) } } /// The number of calculated bands (must call calculateLinearBands() or calculateLogarithmicBands() first). private(set) var numberOfBands: Int = 0 /// The minimum and maximum frequencies in the calculated band spectrum (must call calculateLinearBands() or calculateLogarithmicBands() first). private(set) var bandMinFreq, bandMaxFreq: Float! /// Supplying a window type (hanning or hamming) smooths the edges of the incoming waveform and reduces output errors from the FFT function (aka "spectral leakage" - ewww). var windowType = TempiFFTWindowType.none private var halfSize:Int private var log2Size:Int private var window:[Float] = [] private var fftSetup:FFTSetup private var hasPerformedFFT: Bool = false private var complexBuffer: DSPSplitComplex! /// Instantiate the FFT. /// - Parameter withSize: The length of the sample buffer we'll be analyzing. Must be a power of 2. The resulting ```magnitudes``` are of length ```inSize/2```. /// - Parameter sampleRate: Sampling rate of the provided audio data. init(withSize inSize:Int, sampleRate inSampleRate: Float) { let sizeFloat: Float = Float(inSize) self.sampleRate = inSampleRate // Check if the size is a power of two let lg2 = logbf(sizeFloat) assert(remainderf(sizeFloat, powf(2.0, lg2)) == 0, "size must be a power of 2") self.size = inSize self.halfSize = inSize / 2 // create fft setup self.log2Size = Int(log2f(sizeFloat)) self.fftSetup = vDSP_create_fftsetup(UInt(log2Size), FFTRadix(FFT_RADIX2))! // Init the complexBuffer var real = [Float](repeating: 0.0, count: self.halfSize) var imaginary = [Float](repeating: 0.0, count: self.halfSize) super.init() real.withUnsafeMutableBufferPointer { realBP in imaginary.withUnsafeMutableBufferPointer { imaginaryBP in self.complexBuffer = DSPSplitComplex(realp: realBP.baseAddress!, imagp: imaginaryBP.baseAddress!) } } } deinit { // destroy the fft setup object vDSP_destroy_fftsetup(fftSetup) } /// Perform a forward FFT on the provided single-channel audio data. When complete, the instance can be queried for information about the analysis or the magnitudes can be accessed directly. /// - Parameter inMonoBuffer: Audio data in mono format func fftForward(_ inMonoBuffer:[Float]) { var analysisBuffer = inMonoBuffer // If we have a window, apply it now. Since 99.9% of the time the window array will be exactly the same, an optimization would be to create it once and cache it, possibly caching it by size. if self.windowType != .none { if self.window.isEmpty { self.window = [Float](repeating: 0.0, count: size) switch self.windowType { case .hamming: vDSP_hamm_window(&self.window, UInt(size), 0) case .hanning: vDSP_hann_window(&self.window, UInt(size), Int32(vDSP_HANN_NORM)) default: break } } // Apply the window vDSP_vmul(inMonoBuffer, 1, self.window, 1, &analysisBuffer, 1, UInt(inMonoBuffer.count)) } // vDSP_ctoz converts an interleaved vector into a complex split vector. i.e. moves the even indexed samples into frame.buffer.realp and the odd indexed samples into frame.buffer.imagp. // var imaginary = [Float](repeating: 0.0, count: analysisBuffer.count) // var splitComplex = DSPSplitComplex(realp: &analysisBuffer, imagp: &imaginary) // let length = vDSP_Length(self.log2Size) // vDSP_fft_zip(self.fftSetup, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) // Doing the job of vDSP_ctoz 😒. (See below.) var reals = [Float]() var imags = [Float]() for (idx, element) in analysisBuffer.enumerated() { if idx % 2 == 0 { reals.append(element) } else { imags.append(element) } } reals.withUnsafeMutableBufferPointer { realsBP in imags.withUnsafeMutableBufferPointer { imagsBP in self.complexBuffer = DSPSplitComplex(realp: realsBP.baseAddress!, imagp: imagsBP.baseAddress!) } } // This compiles without error but doesn't actually work. It results in garbage values being stored to the complexBuffer's real and imag parts. Why? The above workaround is undoubtedly tons slower so it would be good to get vDSP_ctoz working again. // withUnsafePointer(to: &analysisBuffer, { $0.withMemoryRebound(to: DSPComplex.self, capacity: analysisBuffer.count) { // vDSP_ctoz($0, 2, &(self.complexBuffer!), 1, UInt(self.halfSize)) // } // }) // Verifying garbage values. // let rFloats = [Float](UnsafeBufferPointer(start: self.complexBuffer.realp, count: self.halfSize)) // let iFloats = [Float](UnsafeBufferPointer(start: self.complexBuffer.imagp, count: self.halfSize)) // Perform a forward FFT vDSP_fft_zrip(self.fftSetup, &(self.complexBuffer!), 1, UInt(self.log2Size), Int32(FFT_FORWARD)) // Store and square (for better visualization & conversion to db) the magnitudes self.magnitudes = [Float](repeating: 0.0, count: self.halfSize) vDSP_zvmags(&(self.complexBuffer!), 1, &self.magnitudes, 1, UInt(self.halfSize)) self.hasPerformedFFT = true } /// Applies logical banding on top of the spectrum data. The bands are spaced linearly throughout the spectrum. func calculateLinearBands(minFrequency: Float, maxFrequency: Float, numberOfBands: Int) { assert(hasPerformedFFT, "*** Perform the FFT first.") let actualMaxFrequency = min(self.nyquistFrequency, maxFrequency) self.numberOfBands = numberOfBands self.bandMagnitudes = [Float](repeating: 0.0, count: numberOfBands) self.bandFrequencies = [Float](repeating: 0.0, count: numberOfBands) let magLowerRange = magIndexForFreq(minFrequency) let magUpperRange = magIndexForFreq(actualMaxFrequency) let ratio: Float = Float(magUpperRange - magLowerRange) / Float(numberOfBands) for i in 0..<numberOfBands { let magsStartIdx: Int = Int(floorf(Float(i) * ratio)) + magLowerRange let magsEndIdx: Int = Int(floorf(Float(i + 1) * ratio)) + magLowerRange var magsAvg: Float if magsEndIdx == magsStartIdx { // Can happen when numberOfBands < # of magnitudes. No need to average anything. magsAvg = self.magnitudes[magsStartIdx] } else { magsAvg = fastAverage(self.magnitudes, magsStartIdx, magsEndIdx) } self.bandMagnitudes[i] = magsAvg self.bandFrequencies[i] = self.averageFrequencyInRange(magsStartIdx, magsEndIdx) } self.bandMinFreq = self.bandFrequencies[0] self.bandMaxFreq = self.bandFrequencies.last } private func magIndexForFreq(_ freq: Float) -> Int { return Int(Float(self.magnitudes.count) * freq / self.nyquistFrequency) } // On arrays of 1024 elements, this is ~35x faster than an iterational algorithm. Thanks Accelerate.framework! @inline(__always) private func fastAverage(_ array:[Float], _ startIdx: Int, _ stopIdx: Int) -> Float { var mean: Float = 0 array.withUnsafeBufferPointer { arrayBP in vDSP_meanv(arrayBP.baseAddress! + startIdx, 1, &mean, UInt(stopIdx - startIdx)) } return mean } @inline(__always) private func averageFrequencyInRange(_ startIndex: Int, _ endIndex: Int) -> Float { return (self.bandwidth * Float(startIndex) + self.bandwidth * Float(endIndex)) / 2 } /// Get the magnitude for the specified frequency band. /// - Parameter inBand: The frequency band you want a magnitude for. func magnitudeAtBand(_ inBand: Int) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first") return bandMagnitudes[inBand] } /// Get the magnitude of the requested frequency in the spectrum. /// - Parameter inFrequency: The requested frequency. Must be less than the Nyquist frequency (```sampleRate/2```). /// - Returns: A magnitude. func magnitudeAtFrequency(_ inFrequency: Float) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") let index = Int(floorf(inFrequency / self.bandwidth )) return self.magnitudes[index] } /// Get the middle frequency of the Nth band. /// - Parameter inBand: An index where 0 <= inBand < size / 2. /// - Returns: The middle frequency of the provided band. func frequencyAtBand(_ inBand: Int) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first") return self.bandFrequencies[inBand] } /// A convenience function that converts a linear magnitude (like those stored in ```magnitudes```) to db (which is log 10). class func toDB(_ inMagnitude: Float) -> Float { // ceil to 128db in order to avoid log10'ing 0 let magnitude = max(inMagnitude, 0.000000000001) return 10 * log10f(magnitude) } }
mit
stripe/stripe-ios
Tests/Tests/UserDefaults+StripeTest.swift
1
1071
// // UserDefaults+StripeTest.swift // StripeiOS Tests // // Created by Yuki Tokuhiro on 5/21/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class UserDefaults_StripeTest: XCTestCase { func testFraudDetectionData() throws { let fraudDetectionData = FraudDetectionData( sid: UUID().uuidString, muid: UUID().uuidString, guid: UUID().uuidString, sidCreationDate: Date() ) UserDefaults.standard.fraudDetectionData = fraudDetectionData XCTAssertEqual(UserDefaults.standard.fraudDetectionData, fraudDetectionData) } func testCustomerToLastSelectedPaymentMethod() throws { let c = [UUID().uuidString: UUID().uuidString] UserDefaults.standard.customerToLastSelectedPaymentMethod = c XCTAssertEqual(UserDefaults.standard.customerToLastSelectedPaymentMethod, c) } }
mit
fgengine/quickly
Quickly/Views/Shape/QShapeView.swift
1
5210
// // Quickly // open class QShapeView : QView { public var model: Model? { didSet { if let model = self.model { if let fillColor = model.fillColor { self.shapeLayer.fillColor = fillColor.cgColor } else { self.shapeLayer.fillColor = nil } self.shapeLayer.fillRule = CAShapeLayerFillRule(rawValue: model.fillRule.string) if let strokeColor = model.strokeColor { self.shapeLayer.strokeColor = strokeColor.cgColor } else { self.shapeLayer.strokeColor = nil } self.shapeLayer.strokeStart = model.strokeStart self.shapeLayer.strokeEnd = model.strokeEnd self.shapeLayer.lineWidth = model.lineWidth self.shapeLayer.miterLimit = model.miterLimit self.shapeLayer.lineCap = CAShapeLayerLineCap(rawValue: model.lineCap.string) self.shapeLayer.lineJoin = CAShapeLayerLineJoin(rawValue: model.lineJoin.string) self.shapeLayer.lineDashPhase = model.lineDashPhase if let lineDashPattern = model.lineDashPattern { self.shapeLayer.lineDashPattern = lineDashPattern.compactMap({ (value: UInt) -> NSNumber? in return NSNumber(value: value) }) } else { self.shapeLayer.lineDashPattern = nil } } self.invalidateIntrinsicContentSize() self.setNeedsLayout() } } public var shapeLayer: CAShapeLayer { get { return self.layer as! CAShapeLayer } } open override class var layerClass: AnyClass { get { return CAShapeLayer.self } } open override var intrinsicContentSize: CGSize { get { return self.sizeThatFits(self.bounds.size) } } open override func sizeThatFits(_ size: CGSize) -> CGSize { guard let model = self.model else { return CGSize.zero } return model.size } open override func sizeToFit() { super.sizeToFit() self.frame.size = self.sizeThatFits(self.bounds.size) } open override func layoutSubviews() { if let model = self.model { if let path = model.prepare(self.bounds) { self.shapeLayer.path = path.cgPath } else { self.shapeLayer.path = nil } } else { self.shapeLayer.path = nil } } } extension QShapeView { public enum FillRule { case nonZero case evenOdd public var string: String { get { switch self { case .nonZero: return CAShapeLayerFillRule.nonZero.rawValue case .evenOdd: return CAShapeLayerFillRule.evenOdd.rawValue } } } } public enum LineCap { case butt case round case square public var string: String { get { switch self { case .butt: return CAShapeLayerLineCap.butt.rawValue case .round: return CAShapeLayerLineCap.round.rawValue case .square: return CAShapeLayerLineCap.square.rawValue } } } } public enum LineJoid { case miter case round case bevel public var string: String { get { switch self { case .miter: return CAShapeLayerLineJoin.miter.rawValue case .round: return CAShapeLayerLineJoin.round.rawValue case .bevel: return CAShapeLayerLineJoin.bevel.rawValue } } } } open class Model { open var fillColor: UIColor? open var fillRule: FillRule open var strokeColor: UIColor? open var strokeStart: CGFloat open var strokeEnd: CGFloat open var lineWidth: CGFloat open var miterLimit: CGFloat open var lineCap: LineCap open var lineJoin: LineJoid open var lineDashPhase: CGFloat open var lineDashPattern: [UInt]? open var size: CGSize public init(size: CGSize) { self.fillColor = nil self.fillRule = .nonZero self.strokeColor = nil self.strokeStart = 0 self.strokeEnd = 1 self.lineWidth = 1 self.miterLimit = 10 self.lineCap = .butt self.lineJoin = .miter self.lineDashPhase = 0 self.lineDashPattern = nil self.size = size } open func make() -> UIBezierPath? { return nil } open func prepare(_ bounds: CGRect) -> UIBezierPath? { guard let path = self.make() else { return nil } path.apply(CGAffineTransform(translationX: (bounds.width / 2), y: (bounds.height / 2))) return path } } }
mit