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
nubbel/swift-tensorflow
Sources/compare_test.pb.swift
1
26301
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: tensorflow/python/util/protobuf/compare_test.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ /// Test messages used in compare_test.py. import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public enum CompareTest_Enum: SwiftProtobuf.Enum { public typealias RawValue = Int case a // = 0 case b // = 1 case c // = 2 public init() { self = .a } public init?(rawValue: Int) { switch rawValue { case 0: self = .a case 1: self = .b case 2: self = .c default: return nil } } public var rawValue: Int { switch self { case .a: return 0 case .b: return 1 case .c: return 2 } } } public struct CompareTest_Small: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".Small" public var strings: [String] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeRepeatedStringField(value: &self.strings) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.strings.isEmpty { try visitor.visitRepeatedStringField(value: self.strings, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } } public struct CompareTest_Medium: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".Medium" public var int32S: [Int32] = [] public var smalls: [CompareTest_Small] = [] public var groupA: [CompareTest_Medium.GroupA] = [] public var floats: [Float] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public struct GroupA: SwiftProtobuf.Message { public static let protoMessageName: String = CompareTest_Medium.protoMessageName + ".GroupA" public var groupB: [CompareTest_Medium.GroupA.GroupB] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public struct GroupB: SwiftProtobuf.Message { public static let protoMessageName: String = CompareTest_Medium.GroupA.protoMessageName + ".GroupB" public var strings: String { get {return _strings ?? String()} set {_strings = newValue} } /// Returns true if `strings` has been explicitly set. public var hasStrings: Bool {return self._strings != nil} /// Clears the value of `strings`. Subsequent reads from it will return its default value. public mutating func clearStrings() {self._strings = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} public var isInitialized: Bool { if self._strings == nil {return false} return true } /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 5: try decoder.decodeSingularStringField(value: &self._strings) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._strings { try visitor.visitSingularStringField(value: v, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } fileprivate var _strings: String? = nil } public init() {} public var isInitialized: Bool { if !SwiftProtobuf.Internal.areAllInitialized(self.groupB) {return false} return true } /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 4: try decoder.decodeRepeatedGroupField(value: &self.groupB) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.groupB.isEmpty { try visitor.visitRepeatedGroupField(value: self.groupB, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } } public init() {} public var isInitialized: Bool { if !SwiftProtobuf.Internal.areAllInitialized(self.groupA) {return false} return true } /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeRepeatedInt32Field(value: &self.int32S) case 2: try decoder.decodeRepeatedMessageField(value: &self.smalls) case 3: try decoder.decodeRepeatedGroupField(value: &self.groupA) case 6: try decoder.decodeRepeatedFloatField(value: &self.floats) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.int32S.isEmpty { try visitor.visitRepeatedInt32Field(value: self.int32S, fieldNumber: 1) } if !self.smalls.isEmpty { try visitor.visitRepeatedMessageField(value: self.smalls, fieldNumber: 2) } if !self.groupA.isEmpty { try visitor.visitRepeatedGroupField(value: self.groupA, fieldNumber: 3) } if !self.floats.isEmpty { try visitor.visitRepeatedFloatField(value: self.floats, fieldNumber: 6) } try unknownFields.traverse(visitor: &visitor) } } public struct CompareTest_Large: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".Large" public var string_: String { get {return _storage._string_ ?? String()} set {_uniqueStorage()._string_ = newValue} } /// Returns true if `string_` has been explicitly set. public var hasString_: Bool {return _storage._string_ != nil} /// Clears the value of `string_`. Subsequent reads from it will return its default value. public mutating func clearString_() {_storage._string_ = nil} public var int64_: Int64 { get {return _storage._int64_ ?? 0} set {_uniqueStorage()._int64_ = newValue} } /// Returns true if `int64_` has been explicitly set. public var hasInt64_: Bool {return _storage._int64_ != nil} /// Clears the value of `int64_`. Subsequent reads from it will return its default value. public mutating func clearInt64_() {_storage._int64_ = nil} public var float_: Float { get {return _storage._float_ ?? 0} set {_uniqueStorage()._float_ = newValue} } /// Returns true if `float_` has been explicitly set. public var hasFloat_: Bool {return _storage._float_ != nil} /// Clears the value of `float_`. Subsequent reads from it will return its default value. public mutating func clearFloat_() {_storage._float_ = nil} public var bool_: Bool { get {return _storage._bool_ ?? false} set {_uniqueStorage()._bool_ = newValue} } /// Returns true if `bool_` has been explicitly set. public var hasBool_: Bool {return _storage._bool_ != nil} /// Clears the value of `bool_`. Subsequent reads from it will return its default value. public mutating func clearBool_() {_storage._bool_ = nil} public var enum_: CompareTest_Enum { get {return _storage._enum_ ?? .a} set {_uniqueStorage()._enum_ = newValue} } /// Returns true if `enum_` has been explicitly set. public var hasEnum_: Bool {return _storage._enum_ != nil} /// Clears the value of `enum_`. Subsequent reads from it will return its default value. public mutating func clearEnum_() {_storage._enum_ = nil} public var int64S: [Int64] { get {return _storage._int64S} set {_uniqueStorage()._int64S = newValue} } public var medium: CompareTest_Medium { get {return _storage._medium ?? CompareTest_Medium()} set {_uniqueStorage()._medium = newValue} } /// Returns true if `medium` has been explicitly set. public var hasMedium: Bool {return _storage._medium != nil} /// Clears the value of `medium`. Subsequent reads from it will return its default value. public mutating func clearMedium() {_storage._medium = nil} public var small: CompareTest_Small { get {return _storage._small ?? CompareTest_Small()} set {_uniqueStorage()._small = newValue} } /// Returns true if `small` has been explicitly set. public var hasSmall: Bool {return _storage._small != nil} /// Clears the value of `small`. Subsequent reads from it will return its default value. public mutating func clearSmall() {_storage._small = nil} public var double_: Double { get {return _storage._double_ ?? 0} set {_uniqueStorage()._double_ = newValue} } /// Returns true if `double_` has been explicitly set. public var hasDouble_: Bool {return _storage._double_ != nil} /// Clears the value of `double_`. Subsequent reads from it will return its default value. public mutating func clearDouble_() {_storage._double_ = nil} public var withMap: CompareTest_WithMap { get {return _storage._withMap ?? CompareTest_WithMap()} set {_uniqueStorage()._withMap = newValue} } /// Returns true if `withMap` has been explicitly set. public var hasWithMap: Bool {return _storage._withMap != nil} /// Clears the value of `withMap`. Subsequent reads from it will return its default value. public mutating func clearWithMap() {_storage._withMap = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} public var isInitialized: Bool { return withExtendedLifetime(_storage) { (_storage: _StorageClass) in if let v = _storage._medium, !v.isInitialized {return false} return true } } /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &_storage._string_) case 2: try decoder.decodeSingularInt64Field(value: &_storage._int64_) case 3: try decoder.decodeSingularFloatField(value: &_storage._float_) case 4: try decoder.decodeSingularBoolField(value: &_storage._bool_) case 5: try decoder.decodeSingularEnumField(value: &_storage._enum_) case 6: try decoder.decodeRepeatedInt64Field(value: &_storage._int64S) case 7: try decoder.decodeSingularMessageField(value: &_storage._medium) case 8: try decoder.decodeSingularMessageField(value: &_storage._small) case 9: try decoder.decodeSingularDoubleField(value: &_storage._double_) case 10: try decoder.decodeSingularMessageField(value: &_storage._withMap) default: break } } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if let v = _storage._string_ { try visitor.visitSingularStringField(value: v, fieldNumber: 1) } if let v = _storage._int64_ { try visitor.visitSingularInt64Field(value: v, fieldNumber: 2) } if let v = _storage._float_ { try visitor.visitSingularFloatField(value: v, fieldNumber: 3) } if let v = _storage._bool_ { try visitor.visitSingularBoolField(value: v, fieldNumber: 4) } if let v = _storage._enum_ { try visitor.visitSingularEnumField(value: v, fieldNumber: 5) } if !_storage._int64S.isEmpty { try visitor.visitRepeatedInt64Field(value: _storage._int64S, fieldNumber: 6) } if let v = _storage._medium { try visitor.visitSingularMessageField(value: v, fieldNumber: 7) } if let v = _storage._small { try visitor.visitSingularMessageField(value: v, fieldNumber: 8) } if let v = _storage._double_ { try visitor.visitSingularDoubleField(value: v, fieldNumber: 9) } if let v = _storage._withMap { try visitor.visitSingularMessageField(value: v, fieldNumber: 10) } } try unknownFields.traverse(visitor: &visitor) } fileprivate var _storage = _StorageClass.defaultInstance } public struct CompareTest_Labeled: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".Labeled" public var required: Int32 { get {return _required ?? 0} set {_required = newValue} } /// Returns true if `required` has been explicitly set. public var hasRequired: Bool {return self._required != nil} /// Clears the value of `required`. Subsequent reads from it will return its default value. public mutating func clearRequired() {self._required = nil} public var optional: Int32 { get {return _optional ?? 0} set {_optional = newValue} } /// Returns true if `optional` has been explicitly set. public var hasOptional: Bool {return self._optional != nil} /// Clears the value of `optional`. Subsequent reads from it will return its default value. public mutating func clearOptional() {self._optional = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} public var isInitialized: Bool { if self._required == nil {return false} return true } /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularInt32Field(value: &self._required) case 2: try decoder.decodeSingularInt32Field(value: &self._optional) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._required { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } if let v = self._optional { try visitor.visitSingularInt32Field(value: v, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } fileprivate var _required: Int32? = nil fileprivate var _optional: Int32? = nil } public struct CompareTest_WithMap: SwiftProtobuf.Message { public static let protoMessageName: String = _protobuf_package + ".WithMap" public var valueMessage: Dictionary<Int32,CompareTest_Small> = [:] public var valueString: Dictionary<String,String> = [:] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,CompareTest_Small>.self, value: &self.valueMessage) case 2: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &self.valueString) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.valueMessage.isEmpty { try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMessageMap<SwiftProtobuf.ProtobufInt32,CompareTest_Small>.self, value: self.valueMessage, fieldNumber: 1) } if !self.valueString.isEmpty { try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: self.valueString, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "compare_test" extension CompareTest_Enum: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "A"), 1: .same(proto: "B"), 2: .same(proto: "C"), ] } extension CompareTest_Small: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "strings"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_Small) -> Bool { if self.strings != other.strings {return false} if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_Medium: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "int32s"), 2: .same(proto: "smalls"), 3: .unique(proto: "GroupA", json: "groupa"), 6: .same(proto: "floats"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_Medium) -> Bool { if self.int32S != other.int32S {return false} if self.smalls != other.smalls {return false} if self.groupA != other.groupA {return false} if self.floats != other.floats {return false} if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_Medium.GroupA: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 4: .unique(proto: "GroupB", json: "groupb"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_Medium.GroupA) -> Bool { if self.groupB != other.groupB {return false} if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_Medium.GroupA.GroupB: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 5: .same(proto: "strings"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_Medium.GroupA.GroupB) -> Bool { if self._strings != other._strings {return false} if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_Large: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "string_"), 2: .standard(proto: "int64_"), 3: .standard(proto: "float_"), 4: .standard(proto: "bool_"), 5: .standard(proto: "enum_"), 6: .same(proto: "int64s"), 7: .same(proto: "medium"), 8: .same(proto: "small"), 9: .standard(proto: "double_"), 10: .standard(proto: "with_map"), ] fileprivate class _StorageClass { var _string_: String? = nil var _int64_: Int64? = nil var _float_: Float? = nil var _bool_: Bool? = nil var _enum_: CompareTest_Enum? = nil var _int64S: [Int64] = [] var _medium: CompareTest_Medium? = nil var _small: CompareTest_Small? = nil var _double_: Double? = nil var _withMap: CompareTest_WithMap? = nil static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _string_ = source._string_ _int64_ = source._int64_ _float_ = source._float_ _bool_ = source._bool_ _enum_ = source._enum_ _int64S = source._int64S _medium = source._medium _small = source._small _double_ = source._double_ _withMap = source._withMap } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public func _protobuf_generated_isEqualTo(other: CompareTest_Large) -> Bool { if _storage !== other._storage { let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in if _storage._string_ != other_storage._string_ {return false} if _storage._int64_ != other_storage._int64_ {return false} if _storage._float_ != other_storage._float_ {return false} if _storage._bool_ != other_storage._bool_ {return false} if _storage._enum_ != other_storage._enum_ {return false} if _storage._int64S != other_storage._int64S {return false} if _storage._medium != other_storage._medium {return false} if _storage._small != other_storage._small {return false} if _storage._double_ != other_storage._double_ {return false} if _storage._withMap != other_storage._withMap {return false} return true } if !storagesAreEqual {return false} } if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_Labeled: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "required"), 2: .same(proto: "optional"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_Labeled) -> Bool { if self._required != other._required {return false} if self._optional != other._optional {return false} if unknownFields != other.unknownFields {return false} return true } } extension CompareTest_WithMap: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "value_message"), 2: .standard(proto: "value_string"), ] public func _protobuf_generated_isEqualTo(other: CompareTest_WithMap) -> Bool { if self.valueMessage != other.valueMessage {return false} if self.valueString != other.valueString {return false} if unknownFields != other.unknownFields {return false} return true } }
mit
ginppian/fif2016
DetailTableViewCell.swift
1
812
// // DetailTableViewCell.swift // FIF 16 // // Created by ginppian on 10/11/16. // Copyright © 2016 AzureChen. All rights reserved. // import UIKit class DetailTableViewCell: UITableViewCell { @IBOutlet weak var labelEvento: UILabel! @IBOutlet weak var labelHora: UILabel! @IBOutlet weak var labelPonente: UILabel! @IBOutlet weak var labelPais: UILabel! @IBOutlet weak var labelSede: UILabel! @IBOutlet weak var labelDireccion: UILabel! @IBOutlet weak var labelDescripcion: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
xxxAIRINxxx/ARNHeaderStretchFlowLayout-Swift
Lib/ARNHeaderStretchFlowLayout.swift
1
1488
// // ARNHeaderStretchFlowLayout.swift // // Created by xxxAIRINxxx on 2014/09/17. // Copyright (c) 2014 xxxAIRINxxx. All rights reserved. // import UIKit public class ARNHeaderStretchFlowLayout: UICollectionViewFlowLayout { public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let att = super.layoutAttributesForElementsInRect(rect) var attributes:[UICollectionViewLayoutAttributes] = [] att?.forEach() { attributes.append($0.copy() as! UICollectionViewLayoutAttributes) } let offset = self.collectionView!.contentOffset let minY = 0 - self.collectionView!.contentInset.top if offset.y < minY { let headerSize = self.headerReferenceSize let deltaY = fabsf(CFloat(offset.y) - CFloat(minY)) attributes.forEach() { if $0.representedElementKind == UICollectionElementKindSectionHeader && $0.indexPath.section == 0 { var headerRect = $0.frame headerRect.size.height = max(minY, CGFloat(headerSize.height) + CGFloat(deltaY)) headerRect.origin.y = headerRect.origin.y - CGFloat(deltaY) $0.frame = headerRect } } } return attributes } }
mit
GraphQLSwift/GraphQL
Sources/GraphQL/Map/Number.swift
1
4343
import Foundation public struct Number { public enum StorageType { case bool case int case double case unknown } private var _number: NSNumber public var storageType: StorageType public var number: NSNumber { mutating get { if !isKnownUniquelyReferenced(&_number) { _number = _number.copy() as! NSNumber } return _number } set { _number = newValue } } public init(_ value: NSNumber) { _number = value storageType = .unknown } public init(_ value: Bool) { _number = NSNumber(value: value) storageType = .bool } @available(OSX 10.5, *) public init(_ value: Int) { _number = NSNumber(value: value) storageType = .int } @available(OSX 10.5, *) public init(_ value: UInt) { _number = NSNumber(value: value) storageType = .int } public init(_ value: Int8) { _number = NSNumber(value: value) storageType = .int } public init(_ value: UInt8) { _number = NSNumber(value: value) storageType = .int } public init(_ value: Int16) { _number = NSNumber(value: value) storageType = .int } public init(_ value: UInt16) { _number = NSNumber(value: value) storageType = .int } public init(_ value: Int32) { _number = NSNumber(value: value) storageType = .int } public init(_ value: UInt32) { _number = NSNumber(value: value) storageType = .int } public init(_ value: Int64) { _number = NSNumber(value: value) storageType = .int } public init(_ value: UInt64) { _number = NSNumber(value: value) storageType = .int } public init(_ value: Float) { _number = NSNumber(value: value) storageType = .double } public init(_ value: Double) { _number = NSNumber(value: value) storageType = .double } public var boolValue: Bool { return _number.boolValue } @available(OSX 10.5, *) public var intValue: Int { return _number.intValue } @available(OSX 10.5, *) public var uintValue: UInt { return _number.uintValue } public var int8Value: Int8 { return _number.int8Value } public var uint8Value: UInt8 { return _number.uint8Value } public var int16Value: Int16 { return _number.int16Value } public var uint16Value: UInt16 { return _number.uint16Value } public var int32Value: Int32 { return _number.int32Value } public var uint32Value: UInt32 { return _number.uint32Value } public var int64Value: Int64 { return _number.int64Value } public var uint64Value: UInt64 { return _number.uint64Value } public var floatValue: Float { return _number.floatValue } public var doubleValue: Double { return _number.doubleValue } public var stringValue: String { return _number.stringValue } } extension Number: Hashable {} extension Number: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._number == rhs._number } } extension Number: Comparable { public static func < (lhs: Number, rhs: Number) -> Bool { return lhs._number.compare(rhs._number) == .orderedAscending } } extension Number: ExpressibleByBooleanLiteral { /// Create an instance initialized to `value`. public init(booleanLiteral value: Bool) { _number = NSNumber(value: value) storageType = .bool } } extension Number: ExpressibleByIntegerLiteral { /// Create an instance initialized to `value`. public init(integerLiteral value: Int) { _number = NSNumber(value: value) storageType = .int } } extension Number: ExpressibleByFloatLiteral { /// Create an instance initialized to `value`. public init(floatLiteral value: Double) { _number = NSNumber(value: value) storageType = .double } } extension Number: CustomStringConvertible { public var description: String { return _number.description } }
mit
MoZhouqi/iOS8SelfSizingCells
iOS8SelfSizingCells/KMTableViewCell.swift
1
1170
// // KMTableViewCell.swift // iOS8SelfSizingCells // // Created by Zhouqi Mo on 1/28/15. // Copyright (c) 2015 Zhouqi Mo. All rights reserved. // import UIKit class KMTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var leadingConstraint: NSLayoutConstraint! @IBOutlet weak var trailingConstraint: NSLayoutConstraint! var tableView: UIView! var maxLayoutWidth: CGFloat { // So weird! The value is 47.0 in IB, but it is actually 48.0. let CellTrailingToContentViewTrailingConstant: CGFloat = 48.0 // Minus the left/right padding for the label let maxLayoutWidth = CGRectGetWidth(tableView.frame) - leadingConstraint.constant - trailingConstraint.constant - CellTrailingToContentViewTrailingConstant return maxLayoutWidth } func updateFonts() { titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) } override func layoutSubviews() { super.layoutSubviews() if tableView != nil { titleLabel.preferredMaxLayoutWidth = maxLayoutWidth } } }
mit
JohnEstropia/RxCoreStore
Sources/RxDynamicObject+Observing.swift
1
2442
// // RxDynamicObject.swift // RxCoreStore // // Copyright © 2017 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 CoreStore import RxCocoa import RxSwift // MARK: - Reactive where Base: NSManagedObject extension Reactive where Base: NSManagedObject { public func monitorObject() -> Signal<RxObjectChange<Base>> { switch self.base.fetchSource() { case let dataStack as DataStack: return dataStack.monitorObject(self.base).asSignal(onErrorSignalWith: .never()) case let transaction as UnsafeDataTransaction: return transaction.monitorObject(self.base).asSignal(onErrorSignalWith: .never()) default: return .empty() } } } // MARK: - Reactive where Base: CoreStoreObject extension Reactive where Base: CoreStoreObject { public func monitorObject() -> Signal<RxObjectChange<Base>> { switch self.base.fetchSource() { case let dataStack as DataStack: return dataStack.monitorObject(self.base).asSignal(onErrorSignalWith: .never()) case let transaction as UnsafeDataTransaction: return transaction.monitorObject(self.base).asSignal(onErrorSignalWith: .never()) default: return .empty() } } }
mit
gsempe/ADVOperation
Source/BlockObserver.swift
1
1306
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows how to implement the OperationObserver protocol. */ import Foundation /** The `BlockObserver` is a way to attach arbitrary blocks to significant events in an `Operation`'s lifecycle. */ struct BlockObserver: OperationObserver { // MARK: Properties private let startHandler: (Operation -> Void)? private let produceHandler: ((Operation, NSOperation) -> Void)? private let finishHandler: ((Operation, [NSError]) -> Void)? init(startHandler: (Operation -> Void)? = nil, produceHandler: ((Operation, NSOperation) -> Void)? = nil, finishHandler: ((Operation, [NSError]) -> Void)? = nil) { self.startHandler = startHandler self.produceHandler = produceHandler self.finishHandler = finishHandler } // MARK: OperationObserver func operationDidStart(operation: Operation) { startHandler?(operation) } func operation(operation: Operation, didProduceOperation newOperation: NSOperation) { produceHandler?(operation, newOperation) } func operationDidFinish(operation: Operation, errors: [NSError]) { finishHandler?(operation, errors) } }
unlicense
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/variables/class/main.swift
2
750
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- class Base { var b : String init () { b = "Hello" } } class Foo : Base { var x : Int var y : Float override init () { x = 12 y = 2.25 super.init() } } func main() -> Int { var f = Foo() return f.x// Set breakpoint here } main()
apache-2.0
j-chao/venture
source/venture/UIViewX.swift
1
2247
// // UIViewX.swift // DesignableX // // Created by Mark Moeykens on 12/31/16. // Copyright © 2016 Mark Moeykens. All rights reserved. // import UIKit @IBDesignable class UIViewX: UIView { // MARK: - Gradient @IBInspectable var firstColor: UIColor = UIColor.white { didSet { updateView() } } @IBInspectable var secondColor: UIColor = UIColor.white { didSet { updateView() } } @IBInspectable var horizontalGradient: Bool = false { didSet { updateView() } } override class var layerClass: AnyClass { get { return CAGradientLayer.self } } func updateView() { let layer = self.layer as! CAGradientLayer layer.colors = [ firstColor.cgColor, secondColor.cgColor ] if (horizontalGradient) { layer.startPoint = CGPoint(x: 0.0, y: 0.5) layer.endPoint = CGPoint(x: 1.0, y: 0.5) } else { layer.startPoint = CGPoint(x: 0, y: 0) layer.endPoint = CGPoint(x: 0, y: 1) } } // MARK: - Border @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } // MARK: - Shadow @IBInspectable public var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable public var shadowColor: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColor.cgColor } } @IBInspectable public var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable public var shadowOffsetY: CGFloat = 0 { didSet { layer.shadowOffset.height = shadowOffsetY } } }
mit
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/LegalHoldDetails/Sections/SingleViewSectionController.swift
1
2952
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit class CollectionViewCellAdapter: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) } var wrappedView: UIView? { didSet { guard wrappedView != oldValue else { return } contentView.subviews.forEach({ $0.removeFromSuperview() }) guard let wrappedView = wrappedView else { return } wrappedView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(wrappedView) NSLayoutConstraint.activate([ wrappedView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), wrappedView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), wrappedView.topAnchor.constraint(equalTo: contentView.topAnchor), wrappedView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) } } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SingleViewSectionController: NSObject, CollectionViewSectionController { fileprivate var view: UIView init(view: UIView) { self.view = view super.init() } func prepareForUse(in collectionView: UICollectionView?) { collectionView?.register(CollectionViewCellAdapter.self, forCellWithReuseIdentifier: CollectionViewCellAdapter.zm_reuseIdentifier) } var isHidden: Bool { return false } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { view.size(fittingWidth: collectionView.bounds.size.width) return view.bounds.size } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(ofType: CollectionViewCellAdapter.self, for: indexPath) cell.wrappedView = view return cell } }
gpl-3.0
PaulWoodIII/tipski
TipskyiOS/Tipski/TourGuide.swift
1
210
// // TourGuide.swift // Tipski // // Created by Paul Wood on 10/28/16. // Copyright © 2016 Paul Wood. All rights reserved. // import Foundation import UIKit class TourGuide : TipViewController { }
mit
esttorhe/SlackTeamExplorer
SlackTeamExplorer/Pods/Nimble/Nimble/DSL+Wait.swift
28
1971
import Foundation /// Only classes, protocols, methods, properties, and subscript declarations can be /// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style /// asynchronous waiting logic so that it may be called from Objective-C and Swift. @objc internal class NMBWait { internal class func until(#timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { var completed = false var token: dispatch_once_t = 0 let result = pollBlock(pollInterval: 0.01, timeoutInterval: timeout) { dispatch_once(&token) { dispatch_async(dispatch_get_main_queue()) { action() { completed = true } } } return completed } if result == PollResult.Failure { let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) } else if result == PollResult.Timeout { fail("Stall on main thread - too much enqueued on main run loop before waitUntil executes.", file: file, line: line) } } internal class func until(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { until(timeout: 1, file: file, line: line, action: action) } } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(#timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { NMBWait.until(timeout: timeout, file: file, line: line, action: action) } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { NMBWait.until(file: file, line: line, action: action) }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/07843-swift-sourcemanager-getmessage.swift
11
290
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { var _ = [Void{ class c : String { var b { struct S<f : BooleanType, A : String { protocol c : a { class case c,
mit
LoopKit/LoopKit
MockKitUI/MockService+UI.swift
1
905
// // MockService+UI.swift // MockKitUI // // Created by Darin Krauss on 5/17/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import SwiftUI import LoopKit import LoopKitUI import MockKit import HealthKit extension MockService: ServiceUI { public static var image: UIImage? { return UIImage(systemName: "icloud.and.arrow.up") } public static func setupViewController(colorPalette: LoopUIColorPalette) -> SetupUIResult<ServiceViewController, ServiceUI> { return .userInteractionRequired(ServiceNavigationController(rootViewController: MockServiceTableViewController(service: MockService(), for: .create))) } public func settingsViewController(colorPalette: LoopUIColorPalette) -> ServiceViewController { return ServiceNavigationController(rootViewController: MockServiceTableViewController(service: self, for: .update)) } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/15391-no-stacktrace.swift
11
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { deinit { { case ( { class c { { } protocol a { class case ,
mit
LDlalala/LDZBLiving
LDZBLiving/LDZBLiving/Classes/Main/Main/LDConst.swift
1
289
// // LDConst.swift // LDZBLiving // // Created by 李丹 on 17/8/7. // Copyright © 2017年 LD. All rights reserved. // import UIKit let KScreenW = UIScreen.main.bounds.width let KScreenH = UIScreen.main.bounds.height let KNavgationBarH = 64 let KStatusBarH = 20 let KTabBarH = 44
mit
LoopKit/LoopKit
LoopKit/Extensions/Double.swift
1
537
// // Double.swift // Naterade // // Created by Nathan Racklyeft on 2/12/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // extension Double: RawRepresentable { public typealias RawValue = Double public init?(rawValue: RawValue) { self = rawValue } public var rawValue: RawValue { return self } } infix operator =~ : ComparisonPrecedence extension Double { static func =~ (lhs: Double, rhs: Double) -> Bool { return fabs(lhs - rhs) < Double.ulpOfOne } }
mit
ixx1232/Getting-Started-swift
GettingStartedSwift/GettingStartedSwiftTests/GettingStartedSwiftTests.swift
1
1026
// // GettingStartedSwiftTests.swift // GettingStartedSwiftTests // // Created by apple on 16/1/21. // Copyright © 2016年 www.ixxcome123.com. All rights reserved. // import XCTest @testable import GettingStartedSwift class GettingStartedSwiftTests: 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
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01013-swift-module-lookupconformance.swift
1
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing (true as 1 func b { { T { } } struct S { func c<S : c
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01782-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
1
224
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A<T { { } func x: String { enum A { func b( (T.a
mit
v2panda/DaysofSwift
swift2.3/My-SnapchatMenu/My-SnapchatMenu/ViewController.swift
1
1632
// // ViewController.swift // My-SnapchatMenu // // Created by Panda on 16/2/19. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarHidden = true let leftVC = LeftViewController(nibName: "LeftViewController", bundle: nil) let centerVC = CameraViewController(nibName: "CameraViewController", bundle: nil) let rightVC = RightViewController(nibName: "RightViewController", bundle: nil) self.addChildViewController(leftVC) self.scrollView.addSubview(leftVC.view) // leftVC.didMoveToParentViewController(self) self.addChildViewController(centerVC) self.scrollView.addSubview(centerVC.view) self.addChildViewController(rightVC) self.scrollView.addSubview(rightVC.view) var centerViewFrame: CGRect = centerVC.view.frame centerViewFrame.origin.x = self.view.frame.width centerVC.view.frame = centerViewFrame var rightViewFrame: CGRect = rightVC.view.frame rightViewFrame.origin.x = 2 * self.view.frame.width rightVC.view.frame = rightViewFrame self.scrollView.contentSize = CGSizeMake(self.view.frame.width * 3, self.view.frame.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
fawkes32/swiftCourse
PickList/PickList/AppDelegate.swift
1
2152
// // AppDelegate.swift // PickList // // Created by Daniel Marquez on 6/23/15. // Copyright (c) 2015 Tec de Monterrey. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/02035-swift-constraints-constraintsystem-matchdeepequalitytypes.swift
12
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<h, e { protocol a { { } init( ) { } } { } struct c: a
mit
calgaryscientific/pureweb-ios-samples
Swift-Asteroids/Asteroids/AsteroidsTests/AsteroidsTests.swift
1
986
// // AsteroidsTests.swift // AsteroidsTests // // Created by Jonathan Neitz on 2016-02-10. // Copyright © 2016 Jonathan Neitz. All rights reserved. // import XCTest @testable import Asteroids class AsteroidsTests: 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.measure { // Put the code you want to measure the time of here. } } }
mit
daltoniam/SwiftHTTP
Source/Operation.swift
1
21381
// // Operation.swift // SwiftHTTP // // Created by Dalton Cherry on 8/2/15. // Copyright © 2015 vluxe. All rights reserved. // import Foundation enum HTTPOptError: Error { case invalidRequest } /** This protocol exist to allow easy and customizable swapping of a serializing format within an class methods of HTTP. */ public protocol HTTPSerializeProtocol { /** implement this protocol to support serializing parameters to the proper HTTP body or URL -parameter request: The URLRequest object you will modify to add the parameters to -parameter parameters: The container (array or dictionary) to convert and append to the URL or Body */ func serialize(_ request: inout URLRequest, parameters: HTTPParameterProtocol) -> Error? } /** Standard HTTP encoding */ public struct HTTPParameterSerializer: HTTPSerializeProtocol { public init() { } public func serialize(_ request: inout URLRequest, parameters: HTTPParameterProtocol) -> Error? { return request.appendParameters(parameters) } } /** Send the data as a JSON body */ public struct JSONParameterSerializer: HTTPSerializeProtocol { public init() { } public func serialize(_ request: inout URLRequest, parameters: HTTPParameterProtocol) -> Error? { return request.appendParametersAsJSON(parameters) } } /** All the things of an HTTP response */ open class Response { /// The header values in HTTP response. open var headers: Dictionary<String,String>? /// The mime type of the HTTP response. open var mimeType: String? /// The suggested filename for a downloaded file. open var suggestedFilename: String? /// The body data of the HTTP response. open var data: Data { return collectData as Data } /// The status code of the HTTP response. open var statusCode: Int? /// The URL of the HTTP response. open var URL: Foundation.URL? /// The Error of the HTTP response (if there was one). open var error: Error? ///Returns the response as a string open var text: String? { return String(data: data, encoding: .utf8) } ///get the description of the response open var description: String { var buffer = "" if let u = URL { buffer += "URL:\n\(u)\n\n" } if let code = self.statusCode { buffer += "Status Code:\n\(code)\n\n" } if let heads = headers { buffer += "Headers:\n" for (key, value) in heads { buffer += "\(key): \(value)\n" } buffer += "\n" } if let t = text { buffer += "Payload:\n\(t)\n" } return buffer } ///private things ///holds the collected data var collectData = NSMutableData() ///finish closure var completionHandler:((Response) -> Void)? //progress closure. Progress is between 0 and 1. var progressHandler:((Float) -> Void)? //download closure. the URL is the file URL where the temp file has been download. //This closure will be called so you can move the file where you desire. var downloadHandler:((Response, URL) -> Void)? ///This gets called on auth challenges. If nil, default handling is use. ///Returning nil from this method will cause the request to be rejected and cancelled var auth:((URLAuthenticationChallenge) -> URLCredential?)? ///This is for doing SSL pinning var security: HTTPSecurity? } /** The class that does the magic. Is a subclass of NSOperation so you can use it with operation queues or just a good ole HTTP request. */ open class HTTP { /** Get notified with a request finishes. */ open var onFinish:((Response) -> Void)? { didSet { if let handler = onFinish { DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in handler(response) }) } } } ///This is for handling authenication open var auth:((URLAuthenticationChallenge) -> URLCredential?)? { set { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } resp.auth = newValue } get { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } return resp.auth } } ///This is for doing SSL pinning open var security: HTTPSecurity? { set { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } resp.security = newValue } get { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } return resp.security } } ///This is for monitoring progress open var progress: ((Float) -> Void)? { set { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } resp.progressHandler = newValue } get { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } return resp.progressHandler } } ///This is for handling downloads open var downloadHandler: ((Response, URL) -> Void)? { set { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } resp.downloadHandler = newValue } get { guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } return resp.downloadHandler } } ///the actual task var task: URLSessionTask! /** creates a new HTTP request. */ public init(_ req: URLRequest, session: URLSession = SharedSession.defaultSession, isDownload: Bool = false) { if isDownload { task = session.downloadTask(with: req) } else { task = session.dataTask(with: req) } DelegateManager.sharedInstance.addResponseForTask(task) } /** start/sends the HTTP task with a completionHandler. Use this when *NOT* using an NSOperationQueue. */ open func run(_ completionHandler: ((Response) -> Void)? = nil) { if let handler = completionHandler { onFinish = handler } task.resume() } /** Cancel the running task */ open func cancel() { task.cancel() } /** Class method to run a GET request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func GET(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } /** Class method to run a HEAD request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func HEAD(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } /** Class method to run a DELETE request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func DELETE(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } /** Class method to run a POST request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func POST(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } /** Class method to run a PUT request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func PUT(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } /** Class method to run a PUT request that handles the URLRequest and parameter encoding for you. */ @discardableResult open class func PATCH(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { return Run(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) } @discardableResult class func Run(_ url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { guard let task = HTTP.New(url, method: method, parameters: parameters, headers: headers, requestSerializer: requestSerializer, completionHandler: completionHandler) else {return nil} task.run() return task } /** Class method to create a Download request that handles the URLRequest and parameter encoding for you. */ open class func Download(_ url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completion:@escaping ((Response, URL) -> Void)) { guard let task = HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer) else {return} task.downloadHandler = completion task.run() } /** Class method to create a HTTP request that handles the URLRequest and parameter encoding for you. */ open class func New(_ url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer(), completionHandler: ((Response) -> Void)? = nil) -> HTTP? { guard var req = URLRequest(urlString: url, headers: headers) else { guard let handler = completionHandler else { return nil } let resp = Response() resp.error = HTTPOptError.invalidRequest handler(resp) return nil } if let handler = DelegateManager.sharedInstance.requestHandler { handler(&req) } req.verb = method if let params = parameters { if let error = requestSerializer.serialize(&req, parameters: params) { guard let handler = completionHandler else { return nil } let resp = Response() resp.error = error handler(resp) return nil } } let httpReq = HTTP(req) httpReq.onFinish = completionHandler return httpReq } /** Set the global auth handler */ open class func globalAuth(_ handler: ((URLAuthenticationChallenge) -> URLCredential?)?) { DelegateManager.sharedInstance.auth = handler } /** Set the global security handler */ open class func globalSecurity(_ security: HTTPSecurity?) { DelegateManager.sharedInstance.security = security } /** Set the global request handler */ open class func globalRequest(_ handler: ((inout URLRequest) -> Void)?) { DelegateManager.sharedInstance.requestHandler = handler } } extension HTTP { static func == (left: HTTP, right: HTTP) -> Bool { return left.task.taskIdentifier == right.task.taskIdentifier } static func != (left: HTTP, right: HTTP) -> Bool { return !(left == right) } } /** Absorb all the delegates methods of NSURLSession and forwards them to pretty closures. This is basically the sin eater for NSURLSession. */ public class DelegateManager: NSObject, URLSessionDataDelegate, URLSessionDownloadDelegate { //the singleton to handle delegate needs of NSURLSession static let sharedInstance = DelegateManager() /// this is for global authenication handling var auth:((URLAuthenticationChallenge) -> URLCredential?)? ///This is for global SSL pinning var security: HTTPSecurity? /// this is for global request handling var requestHandler:((inout URLRequest) -> Void)? var taskMap = Dictionary<Int,Response>() //"install" a task by adding the task to the map and setting the completion handler func addTask(_ task: URLSessionTask, completionHandler:@escaping ((Response) -> Void)) { addResponseForTask(task) if let resp = responseForTask(task) { resp.completionHandler = completionHandler } } //"remove" a task by removing the task from the map func removeTask(_ task: URLSessionTask) { taskMap.removeValue(forKey: task.taskIdentifier) } //add the response task func addResponseForTask(_ task: URLSessionTask) { if taskMap[task.taskIdentifier] == nil { taskMap[task.taskIdentifier] = Response() } } //get the response object for the task func responseForTask(_ task: URLSessionTask) -> Response? { return taskMap[task.taskIdentifier] } //handle getting data public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { addResponseForTask(dataTask) guard let resp = responseForTask(dataTask) else { return } resp.collectData.append(data) if resp.progressHandler != nil { //don't want the extra cycles for no reason guard let taskResp = dataTask.response else { return } progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length)) } } //handle task finishing public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let resp = responseForTask(task) else { return } resp.error = error as NSError? if let hresponse = task.response as? HTTPURLResponse { resp.headers = hresponse.allHeaderFields as? Dictionary<String,String> resp.mimeType = hresponse.mimeType resp.suggestedFilename = hresponse.suggestedFilename resp.statusCode = hresponse.statusCode resp.URL = hresponse.url } if let code = resp.statusCode, code > 299 { resp.error = createError(code) } if let handler = resp.completionHandler { handler(resp) } removeTask(task) } //handle authenication public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var sec = security var au = auth if let resp = responseForTask(task) { if let s = resp.security { sec = s } if let a = resp.auth { au = a } } if let sec = sec , challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let space = challenge.protectionSpace if let trust = space.serverTrust { if sec.isValid(trust, domain: space.host) { completionHandler(.useCredential, URLCredential(trust: trust)) return } } completionHandler(.cancelAuthenticationChallenge, nil) return } else if let a = au { let cred = a(challenge) if let c = cred { completionHandler(.useCredential, c) return } completionHandler(.rejectProtectionSpace, nil) return } completionHandler(.performDefaultHandling, nil) } //upload progress public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { guard let resp = responseForTask(task) else { return } progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent) } //download progress public func urlSession(_ session: Foundation.URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { guard let resp = responseForTask(downloadTask) else { return } progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: totalBytesWritten) } //handle download task public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let resp = responseForTask(downloadTask) else { return } guard let handler = resp.downloadHandler else { return } handler(resp, location) } //handle progress public func progressHandler(_ response: Response, expectedLength: Int64, currentLength: Int64) { guard let handler = response.progressHandler else { return } let slice = Float(1.0)/Float(expectedLength) handler(slice*Float(currentLength)) } /** Create an error for response you probably don't want (400-500 HTTP responses for example). -parameter code: Code for error. -returns An NSError. */ fileprivate func createError(_ code: Int) -> NSError { let text = HTTPStatusCode(statusCode: code).statusDescription return NSError(domain: "HTTP", code: code, userInfo: [NSLocalizedDescriptionKey: text]) } } /** Handles providing singletons of NSURLSession. */ public class SharedSession { public static let defaultSession = URLSession(configuration: URLSessionConfiguration.default, delegate: DelegateManager.sharedInstance, delegateQueue: nil) static let ephemeralSession = URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: DelegateManager.sharedInstance, delegateQueue: nil) } /** Bare bones queue to manage HTTP Requests */ open class HTTPQueue { public var maxSimultaneousRequest = 5 var queue = [HTTP]() let mutex = NSLock() var activeReq = [Int: HTTP]() var finishedHandler: (() -> Void)? public init(maxSimultaneousRequest: Int) { self.maxSimultaneousRequest = maxSimultaneousRequest } open func add(request: URLRequest) { add(http: HTTP(request)) } open func add(http: HTTP) { var doWork = false mutex.lock() queue.append(http) if activeReq.count < maxSimultaneousRequest { doWork = true } mutex.unlock() if doWork { run() } } open func finished(queue: DispatchQueue = DispatchQueue.main, completionHandler: @escaping (() -> Void)) { finishedHandler = completionHandler } func run() { guard let http = nextItem() else { mutex.lock() let count = activeReq.count mutex.unlock() if count == 0 { finishedHandler?() } return } let handler = http.onFinish http.run {[weak self] (response) in handler?(response) self?.mutex.lock() self?.activeReq.removeValue(forKey: http.task.taskIdentifier) self?.mutex.unlock() self?.run() } } func nextItem() -> HTTP? { mutex.lock() if queue.count == 0 { mutex.unlock() return nil } let next = queue.removeFirst() activeReq[next.task.taskIdentifier] = next mutex.unlock() return next } }
apache-2.0
clappr/clappr-ios
Sources/Clappr/Classes/Log/Logger.swift
1
1170
import Foundation open class Logger: NSObject { fileprivate static var logLevel = LogLevel.info open class func setLevel(_ level: LogLevel) { logLevel = level } fileprivate class func log(_ level: LogLevel, message: String) { if level.rawValue <= logLevel.rawValue { print("\(level.description()) \(message)") } } fileprivate class func log(_ level: LogLevel, scope: String?, message: String) { if let scope = scope { log(level, message: "[\(scope)] \(message)") } else { log(level, message: message) } } @objc open class func logError(_ message: String, scope: String? = nil) { log(.error, scope: scope, message: message) } @objc open class func logWarn(_ message: String, scope: String? = nil) { log(.warning, scope: scope, message: message) } @objc open class func logInfo(_ message: String, scope: String? = nil) { log(.info, scope: scope, message: message) } @objc open class func logDebug(_ message: String, scope: String? = nil) { log(.debug, scope: scope, message: message) } }
bsd-3-clause
306244907/Weibo
JLSina/JLSina/Classes/Tools(工具)/UI框架/Emoticon/Model/CZEmoticonPackage.swift
1
2465
// // CZEmoticonPackage.swift // 表情包数据 // // Created by 盘赢 on 2017/12/7. // Copyright © 2017年 盘赢. All rights reserved. // import UIKit import YYModel //表情包模型 @objcMembers class CZEmoticonPackage: NSObject { //表情包分组名 var groupName: String? //背景图片名称 var bgImageName: String? //表情包目录,从目录下加载info.plist可以创建表情模型数组 var directory: String? { didSet { //当设置目录时,从目录下加载info.plist guard let directory = directory , let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil) , let bundle = Bundle(path: path) , let infoPath = bundle.path(forResource: "info.plist", ofType: nil, inDirectory: directory) , let array = NSArray(contentsOfFile: infoPath) as? [[String : String]] , let models = NSArray.yy_modelArray(with: CZEmoticon.self, json: array) as? [CZEmoticon] else { return } //遍历models数组,设置每一个表情符号的目录 for m in models { m.directory = directory } //设置表情模型数组 emoticons += models } } //懒加载的表情模型的空数组 //使用懒加载可以避免后续解包 lazy var emoticons = [CZEmoticon]() ///表情页面数量 var numberOfPages: Int { return (emoticons.count - 1) / 20 + 1 } ///从懒加载的表情包中,按照page截取最多20个表情模型的数组 //例如有25个模型 ///例如:page == 0,返回0~20个 ///page == 1,返回20~25个模型 func emoticon(page: Int) -> [CZEmoticon] { //每页的数量 let count = 20 let location = page * count var length = count //判断数组是否越界 if location + length > emoticons.count { length = emoticons.count - location } let range = NSRange(location: location, length: length) //截取数组的子数组 let subArray = (emoticons as NSArray).subarray(with: range) return subArray as! [CZEmoticon] } override var description: String { return yy_modelDescription() } }
mit
NghiaTranUIT/Unofficial-Uber-macOS
UberGo/UberGo/UberAlertView.swift
1
1593
// // UberAlertView.swift // UberGo // // Created by Nghia Tran on 7/27/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Cocoa class UberAlertView: NSView { // MARK: - OUTLET @IBOutlet fileprivate var errorTitle: NSTextField! // MARK: - Variable fileprivate var isShow = false // MARK: - Public public func showError(_ error: NSError, view: NSView) { let title = error.userInfo["message"] as? String ?? error.description errorTitle.stringValue = title // Animate addSubViewIfNeed(view) fadeInAnimation() } } // MARK: - Animation extension UberAlertView { fileprivate func addSubViewIfNeed(_ view: NSView) { guard self.superview == nil else { return } translatesAutoresizingMaskIntoConstraints = false view.addSubview(self) // Constraints top(to: view) left(to: view) right(to: view) height(36) } fileprivate func fadeInAnimation() { self.alphaValue = 0 NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 1 }) { self.fadeOutAnimation() } } fileprivate func fadeOutAnimation() { DispatchQueue.main.asyncAfter(wallDeadline: .now() + 5.0) { NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 0 }) { self.removeFromSuperview() } } } } // MARK: - XIBInitializable extension UberAlertView: XIBInitializable { typealias XibType = UberAlertView }
mit
netguru/ResponseDetective
ResponseDetective/Tests/Specs/ResponseDetectiveSpec.swift
1
6682
// // ResponseDetectiveSpec.swift // // Copyright © 2016-2020 Netguru S.A. All rights reserved. // Licensed under the MIT License. // import Foundation import Nimble import OHHTTPStubs import ResponseDetective import Quick internal final class ResponseDetectiveSpec: QuickSpec { override func spec() { describe("ResponseDetective") { beforeSuite { stub(condition: isHost("httpbin.org")) { _ in return HTTPStubsResponse(data: Data(), statusCode: 200, headers: nil) } } beforeEach { ResponseDetective.reset() } afterSuite { HTTPStubs.removeAllStubs() } describe("initial state") { it("should use default output facility") { expect(type(of: ResponseDetective.outputFacility) == ConsoleOutputFacility.self).to(beTruthy()) } it("should use default url protocol class") { expect(ResponseDetective.URLProtocolClass).to(beIdenticalTo(NSClassFromString("RDTURLProtocol")!)) } } describe("enabling in url session configuration") { let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.enable(inConfiguration: configuration) } it("should add protocol class at the beginning of array") { expect(configuration.protocolClasses!.first == ResponseDetective.URLProtocolClass).to(beTrue()) } } describe("ignoring requests") { let request = URLRequest(url: URL(string: "http://foo.bar")!) context("before adding predicate") { it("should not ignore the request") { expect { ResponseDetective.canIncercept(request: request) }.to(beTruthy()) } } context("after adding predicate") { beforeEach { ResponseDetective.ignoreRequests(matchingPredicate: NSPredicate { subject, _ in guard let subject = subject as? URLRequest, let url = subject.url else { return true } let string = url.absoluteString return string.contains("foo") }) } it("should ignore the request") { expect { ResponseDetective.canIncercept(request: request) }.to(beFalsy()) } } } describe("body deserialization") { context("before registering a custom body deserializer") { it("should return no deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar") }.to(beNil()) } } context("after registering an explicit body deserializer") { beforeEach { ResponseDetective.registerBodyDeserializer( TestBodyDeserializer(fixedDeserializedBody: "lorem ipsum"), forContentType: "foo/bar" ) } it("should return a deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar") }.to(equal("lorem ipsum")) } it("should return a deserialized body for content type containing properties") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar; charset=utf8") }.to(equal("lorem ipsum")) } } context("after registering a wildcard body deserializer") { beforeEach { ResponseDetective.registerBodyDeserializer( TestBodyDeserializer(fixedDeserializedBody: "dolor sit amet"), forContentType: "foo/*" ) } it("should return a deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/baz") }.to(equal("dolor sit amet")) } } } describe("request interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no requests") { expect(buffer.requestRepresentations).to(beEmpty()) } } context("after request has been sent") { let request: URLRequest = { var request = URLRequest(url: URL(string: "https://httpbin.org/post")!) request.httpMethod = "POST" request.httpBody = Data(base64Encoded: "foo", options: []) return request }() beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept it") { expect(buffer.requestRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) expect(buffer.responseRepresentations.last?.body).toEventuallyNot(beNil(), timeout: .seconds(5)) } } } describe("response interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no responses") { expect(buffer.responseRepresentations).to(beEmpty()) } } context("after request has been sent") { let request = URLRequest(url: URL(string: "https://httpbin.org/get")!) beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept its response") { expect(buffer.responseRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) } } } describe("error interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no errors") { expect(buffer.responseRepresentations).to(beEmpty()) } } context("after request has been sent") { let request = URLRequest(url: URL(string: "https://foobar")!) beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept its error") { expect(buffer.errorRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) } } } } } }
mit
ahoppen/swift
stdlib/public/core/FloatingPoint.swift
5
79312
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A floating-point numeric type. /// /// Floating-point types are used to represent fractional numbers, like 5.5, /// 100.0, or 3.14159274. Each floating-point type has its own possible range /// and precision. The floating-point types in the standard library are /// `Float`, `Double`, and `Float80` where available. /// /// Create new instances of floating-point types using integer or /// floating-point literals. For example: /// /// let temperature = 33.2 /// let recordHigh = 37.5 /// /// The `FloatingPoint` protocol declares common arithmetic operations, so you /// can write functions and algorithms that work on any floating-point type. /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// Because the `hypotenuse(_:_:)` function uses a generic parameter /// constrained to the `FloatingPoint` protocol, you can call it using any /// floating-point type. /// /// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// Floating-point values are represented as a *sign* and a *magnitude*, where /// the magnitude is calculated using the type's *radix* and the instance's /// *significand* and *exponent*. This magnitude calculation takes the /// following form for a floating-point value `x` of type `F`, where `**` is /// exponentiation: /// /// x.significand * F.radix ** x.exponent /// /// Here's an example of the number -8.5 represented as an instance of the /// `Double` type, which defines a radix of 2. /// /// let y = -8.5 /// // y.sign == .minus /// // y.significand == 1.0625 /// // y.exponent == 3 /// /// let magnitude = 1.0625 * Double(2 ** 3) /// // magnitude == 8.5 /// /// Types that conform to the `FloatingPoint` protocol provide most basic /// (clause 5) operations of the [IEEE 754 specification][spec]. The base, /// precision, and exponent range are not fixed in any way by this protocol, /// but it enforces the basic requirements of any IEEE 754 floating-point /// type. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// Additional Considerations /// ========================= /// /// In addition to representing specific numbers, floating-point types also /// have special values for working with overflow and nonnumeric results of /// calculation. /// /// Infinity /// -------- /// /// Any value whose magnitude is so great that it would round to a value /// outside the range of representable numbers is rounded to *infinity*. For a /// type `F`, positive and negative infinity are represented as `F.infinity` /// and `-F.infinity`, respectively. Positive infinity compares greater than /// every finite value and negative infinity, while negative infinity compares /// less than every finite value and positive infinity. Infinite values with /// the same sign are equal to each other. /// /// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] /// print(values.sorted()) /// // Prints "[-inf, -10.0, 10.0, 25.0, inf]" /// /// Operations with infinite values follow real arithmetic as much as possible: /// Adding or subtracting a finite value, or multiplying or dividing infinity /// by a nonzero finite value, results in infinity. /// /// NaN ("not a number") /// -------------------- /// /// Floating-point types represent values that are neither finite numbers nor /// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with /// any value, including another NaN, results in `false`. /// /// let myNaN = Double.nan /// print(myNaN > 0) /// // Prints "false" /// print(myNaN < 0) /// // Prints "false" /// print(myNaN == .nan) /// // Prints "false" /// /// Because testing whether one NaN is equal to another NaN results in `false`, /// use the `isNaN` property to test whether a value is NaN. /// /// print(myNaN.isNaN) /// // Prints "true" /// /// NaN propagates through many arithmetic operations. When you are operating /// on many values, this behavior is valuable because operations on NaN simply /// forward the value and don't cause runtime errors. The following example /// shows how NaN values operate in different contexts. /// /// Imagine you have a set of temperature data for which you need to report /// some general statistics: the total number of observations, the number of /// valid observations, and the average temperature. First, a set of /// observations in Celsius is parsed from strings to `Double` values: /// /// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] /// let tempsCelsius = temperatureData.map { Double($0) ?? .nan } /// print(tempsCelsius) /// // Prints "[21.5, 19.25, 27, nan, 28.25, nan, 23.0]" /// /// /// Note that some elements in the `temperatureData ` array are not valid /// numbers. When these invalid strings are parsed by the `Double` failable /// initializer, the example uses the nil-coalescing operator (`??`) to /// provide NaN as a fallback value. /// /// Next, the observations in Celsius are converted to Fahrenheit: /// /// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } /// print(tempsFahrenheit) /// // Prints "[70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]" /// /// The NaN values in the `tempsCelsius` array are propagated through the /// conversion and remain NaN in `tempsFahrenheit`. /// /// Because calculating the average of the observations involves combining /// every value of the `tempsFahrenheit` array, any NaN values cause the /// result to also be NaN, as seen in this example: /// /// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count) /// // badAverage.isNaN == true /// /// Instead, when you need an operation to have a specific numeric result, /// filter out any NaN values using the `isNaN` property. /// /// let validTemps = tempsFahrenheit.filter { !$0.isNaN } /// let average = validTemps.reduce(0.0, +) / Double(validTemps.count) /// /// Finally, report the average temperature and observation counts: /// /// print("Average: \(average)°F in \(validTemps.count) " + /// "out of \(tempsFahrenheit.count) observations.") /// // Prints "Average: 74.84°F in 5 out of 7 observations." public protocol FloatingPoint: SignedNumeric, Strideable, Hashable where Magnitude == Self { /// A type that can represent any written exponent. associatedtype Exponent: SignedInteger /// Creates a new value from the given sign, exponent, and significand. /// /// The following example uses this initializer to create a new `Double` /// instance. `Double` is a binary floating-point type that has a radix of /// `2`. /// /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) /// // x == 0.375 /// /// This initializer is equivalent to the following calculation, where `**` /// is exponentiation, computed as if by a single, correctly rounded, /// floating-point operation: /// /// let sign: FloatingPointSign = .plus /// let exponent = -2 /// let significand = 1.5 /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent /// // y == 0.375 /// /// As with any basic operation, if this value is outside the representable /// range of the type, overflow or underflow occurs, and zero, a subnormal /// value, or infinity may result. In addition, there are two other edge /// cases: /// /// - If the value you pass to `significand` is zero or infinite, the result /// is zero or infinite, regardless of the value of `exponent`. /// - If the value you pass to `significand` is NaN, the result is NaN. /// /// For any floating-point value `x` of type `F`, the result of the following /// is equal to `x`, with the distinction that the result is canonicalized /// if `x` is in a noncanonical encoding: /// /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) /// /// This initializer implements the `scaleB` operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign to use for the new value. /// - exponent: The new value's exponent. /// - significand: The new value's significand. init(sign: FloatingPointSign, exponent: Exponent, significand: Self) /// Creates a new floating-point value using the sign of one value and the /// magnitude of another. /// /// The following example uses this initializer to create a new `Double` /// instance with the sign of `a` and the magnitude of `b`: /// /// let a = -21.5 /// let b = 305.15 /// let c = Double(signOf: a, magnitudeOf: b) /// print(c) /// // Prints "-305.15" /// /// This initializer implements the IEEE 754 `copysign` operation. /// /// - Parameters: /// - signOf: A value from which to use the sign. The result of the /// initializer has the same sign as `signOf`. /// - magnitudeOf: A value from which to use the magnitude. The result of /// the initializer has the same magnitude as `magnitudeOf`. init(signOf: Self, magnitudeOf: Self) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init(_ value: Int) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init<Source: BinaryInteger>(_ value: Source) /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. init?<Source: BinaryInteger>(exactly value: Source) /// The radix, or base of exponentiation, for a floating-point type. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// x.significand * (F.radix ** x.exponent) /// /// A conforming type may use any integer radix, but values other than 2 (for /// binary floating-point types) or 10 (for decimal floating-point types) /// are extraordinarily rare in practice. static var radix: Int { get } /// A quiet NaN ("not a number"). /// /// A NaN compares not equal, not greater than, and not less than every /// value, including itself. Passing a NaN to an operation generally results /// in NaN. /// /// let x = 1.21 /// // x > Double.nan == false /// // x < Double.nan == false /// // x == Double.nan == false /// /// Because a NaN always compares not equal to itself, to test whether a /// floating-point value is NaN, use its `isNaN` property instead of the /// equal-to operator (`==`). In the following example, `y` is NaN. /// /// let y = x + Double.nan /// print(y == Double.nan) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" static var nan: Self { get } /// A signaling NaN ("not a number"). /// /// The default IEEE 754 behavior of operations involving a signaling NaN is /// to raise the Invalid flag in the floating-point environment and return a /// quiet NaN. /// /// Operations on types conforming to the `FloatingPoint` protocol should /// support this behavior, but they might also support other options. For /// example, it would be reasonable to implement alternative operations in /// which operating on a signaling NaN triggers a runtime error or results /// in a diagnostic for debugging purposes. Types that implement alternative /// behaviors for a signaling NaN must document the departure. /// /// Other than these signaling operations, a signaling NaN behaves in the /// same manner as a quiet NaN. static var signalingNaN: Self { get } /// Positive infinity. /// /// Infinity compares greater than all finite numbers and equal to other /// infinite values. /// /// let x = Double.greatestFiniteMagnitude /// let y = x * 2 /// // y == Double.infinity /// // y > x static var infinity: Self { get } /// The greatest finite number representable by this type. /// /// This value compares greater than or equal to all finite numbers, but less /// than `infinity`. /// /// This value corresponds to type-specific C macros such as `FLT_MAX` and /// `DBL_MAX`. The naming of those macros is slightly misleading, because /// `infinity` is greater than this value. static var greatestFiniteMagnitude: Self { get } /// The [mathematical constant π][wiki], approximately equal to 3.14159. /// /// When measuring an angle in radians, π is equivalent to a half-turn. /// /// This value is rounded toward zero to keep user computations with angles /// from inadvertently ending up in the wrong quadrant. A type that conforms /// to the `FloatingPoint` protocol provides the value for `pi` at its best /// possible precision. /// /// print(Double.pi) /// // Prints "3.14159265358979" /// /// [wiki]: https://en.wikipedia.org/wiki/Pi static var pi: Self { get } // NOTE: Rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastNonzeroMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of this value. /// /// This is the unit of the least significant digit in this value's /// significand. For most numbers `x`, this is the difference between `x` /// and the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - If `x` is not a finite number, then `x.ulp` is NaN. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. If a type does not support subnormals, `x.ulp` may be rounded /// to zero. /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next /// greater representable value is `infinity`. /// /// See also the `ulpOfOne` static property. var ulp: Self { get } /// The unit in the last place of 1.0. /// /// The positive difference between 1.0 and the next greater representable /// number. `ulpOfOne` corresponds to the value represented by the C macros /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or /// *machine epsilon*. Swift deliberately avoids using the term "epsilon" /// because: /// /// - Historically "epsilon" has been used to refer to several different /// concepts in different languages, leading to confusion and bugs. /// /// - The name "epsilon" suggests that this quantity is a good tolerance to /// choose for approximate comparisons, but it is almost always unsuitable /// for that purpose. /// /// See also the `ulp` member property. static var ulpOfOne: Self { get } /// The least positive normal number. /// /// This value compares less than or equal to all positive normal numbers. /// There may be smaller positive numbers, but they are *subnormal*, meaning /// that they are represented with less precision than normal numbers. /// /// This value corresponds to type-specific C macros such as `FLT_MIN` and /// `DBL_MIN`. The naming of those macros is slightly misleading, because /// subnormals, zeros, and negative numbers are smaller than this value. static var leastNormalMagnitude: Self { get } /// The least positive number. /// /// This value compares less than or equal to all positive numbers, but /// greater than zero. If the type supports subnormal values, /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; /// otherwise they are equal. static var leastNonzeroMagnitude: Self { get } /// The sign of the floating-point value. /// /// The `sign` property is `.minus` if the value's signbit is set, and /// `.plus` otherwise. For example: /// /// let x = -33.375 /// // x.sign == .minus /// /// Don't use this property to check whether a floating point value is /// negative. For a value `x`, the comparison `x.sign == .minus` is not /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` /// could be either `.plus` or `.minus`. var sign: FloatingPointSign { get } /// The exponent of the floating-point value. /// /// The *exponent* of a floating-point value is the integer part of the /// logarithm of the value's magnitude. For a value `x` of a floating-point /// type `F`, the magnitude can be calculated as the following, where `**` /// is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// The `exponent` property has the following edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// This property implements the `logB` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var exponent: Exponent { get } /// The significand of the floating-point value. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// If a type's radix is 2, then for finite nonzero numbers, the significand /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` /// is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinite, then `x.significand` is infinity. /// - If `x` is NaN, then `x.significand` is NaN. /// - Note: The significand is frequently also called the *mantissa*, but /// significand is the preferred terminology in the [IEEE 754 /// specification][spec], to allay confusion with the use of mantissa for /// the fractional part of a logarithm. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var significand: Self { get } /// Adds two values and produces their sum, rounded to a /// representable value. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// let x = 1.5 /// let y = x + 2.25 /// // y == 3.75 /// /// The `+` operator implements the addition operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable, /// rounded to a representable value. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Calculates the additive inverse of a value. /// /// The unary minus operator (prefix `-`) calculates the negation of its /// operand. The result is always exact. /// /// let x = 21.5 /// let y = -x /// // y == -21.5 /// /// - Parameter operand: The value to negate. override static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The result is always exact. This example uses the `negate()` method to /// negate the value of the variable `x`: /// /// var x = 21.5 /// x.negate() /// // x == -21.5 override mutating func negate() /// Subtracts one value from another and produces their difference, rounded /// to a representable value. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x - 2.25 /// // y == 5.25 /// /// The `-` operator implements the subtraction operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in /// the left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product, rounding to a /// representable value. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x * 2.25 /// // y == 16.875 /// /// The `*` operator implements the multiplication operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the quotient of dividing the first value by the second, rounded /// to a representable value. /// /// The division operator (`/`) calculates the quotient of the division if /// `rhs` is nonzero. If `rhs` is zero, the result of the division is /// infinity, with the sign of the result matching the sign of `lhs`. /// /// let x = 16.875 /// let y = x / 2.25 /// // y == 7.5 /// /// let z = x / 0 /// // z.isInfinite == true /// /// The `/` operator implements the division operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of this value divided by the given value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// let r = x.remainder(dividingBy: 0.75) /// // r == -0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `remainder(dividingBy:)` method is always exact. This method implements /// the remainder operation defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other`. func remainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// x.formRemainder(dividingBy: 0.75) /// // x == -0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `formRemainder(dividingBy:)` method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formRemainder(dividingBy other: Self) /// Returns the remainder of this value divided by the given value using /// truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// let r = x.truncatingRemainder(dividingBy: 0.75) /// // r == 0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method /// is always exact. /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other` using /// truncating division. func truncatingRemainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value using truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// x.formTruncatingRemainder(dividingBy: 0.75) /// // x == 0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` /// method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formTruncatingRemainder(dividingBy other: Self) /// Returns the square root of the value, rounded to a representable value. /// /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// /// func hypotenuse(_ a: Double, _ b: Double) -> Double { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// - Returns: The square root of the value. func squareRoot() -> Self /// Replaces this value with its square root, rounded to a representable /// value. mutating func formSquareRoot() /// Returns the result of adding the product of the two given values to this /// value, computed without intermediate rounding. /// /// This method is equivalent to the C `fma` function and implements the /// `fusedMultiplyAdd` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. /// - Returns: The product of `lhs` and `rhs`, added to this value. func addingProduct(_ lhs: Self, _ rhs: Self) -> Self /// Adds the product of the two given values to this value in place, computed /// without intermediate rounding. /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. mutating func addProduct(_ lhs: Self, _ rhs: Self) /// Returns the lesser of the two given values. /// /// This method returns the minimum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.minimum(10.0, -25.0) /// // -25.0 /// Double.minimum(10.0, .nan) /// // 10.0 /// Double.minimum(.nan, -25.0) /// // -25.0 /// Double.minimum(.nan, .nan) /// // nan /// /// The `minimum` method implements the `minNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The minimum of `x` and `y`, or whichever is a number if the /// other is NaN. static func minimum(_ x: Self, _ y: Self) -> Self /// Returns the greater of the two given values. /// /// This method returns the maximum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.maximum(10.0, -25.0) /// // 10.0 /// Double.maximum(10.0, .nan) /// // 10.0 /// Double.maximum(.nan, -25.0) /// // -25.0 /// Double.maximum(.nan, .nan) /// // nan /// /// The `maximum` method implements the `maxNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The greater of `x` and `y`, or whichever is a number if the /// other is NaN. static func maximum(_ x: Self, _ y: Self) -> Self /// Returns the value with lesser magnitude. /// /// This method returns the value with lesser magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.minimumMagnitude(10.0, -25.0) /// // 10.0 /// Double.minimumMagnitude(10.0, .nan) /// // 10.0 /// Double.minimumMagnitude(.nan, -25.0) /// // -25.0 /// Double.minimumMagnitude(.nan, .nan) /// // nan /// /// The `minimumMagnitude` method implements the `minNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is /// a number if the other is NaN. static func minimumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns the value with greater magnitude. /// /// This method returns the value with greater magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.maximumMagnitude(10.0, -25.0) /// // -25.0 /// Double.maximumMagnitude(10.0, .nan) /// // 10.0 /// Double.maximumMagnitude(.nan, -25.0) /// // -25.0 /// Double.maximumMagnitude(.nan, .nan) /// // nan /// /// The `maximumMagnitude` method implements the `maxNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is /// a number if the other is NaN. static func maximumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns this value rounded to an integral value using the specified /// rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// let x = 6.5 /// /// // Equivalent to the C 'round' function: /// print(x.rounded(.toNearestOrAwayFromZero)) /// // Prints "7.0" /// /// // Equivalent to the C 'trunc' function: /// print(x.rounded(.towardZero)) /// // Prints "6.0" /// /// // Equivalent to the C 'ceil' function: /// print(x.rounded(.up)) /// // Prints "7.0" /// /// // Equivalent to the C 'floor' function: /// print(x.rounded(.down)) /// // Prints "6.0" /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `rounded()` /// method instead. /// /// print(x.rounded()) /// // Prints "7.0" /// /// - Parameter rule: The rounding rule to use. /// - Returns: The integral value found by rounding using `rule`. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Rounds the value to an integral value using the specified rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// // Equivalent to the C 'round' function: /// var w = 6.5 /// w.round(.toNearestOrAwayFromZero) /// // w == 7.0 /// /// // Equivalent to the C 'trunc' function: /// var x = 6.5 /// x.round(.towardZero) /// // x == 6.0 /// /// // Equivalent to the C 'ceil' function: /// var y = 6.5 /// y.round(.up) /// // y == 7.0 /// /// // Equivalent to the C 'floor' function: /// var z = 6.5 /// z.round(.down) /// // z == 6.0 /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `round()` method /// instead. /// /// var w1 = 6.5 /// w1.round() /// // w1 == 7.0 /// /// - Parameter rule: The rounding rule to use. mutating func round(_ rule: FloatingPointRoundingRule) /// The least representable value that compares greater than this value. /// /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or /// `infinity`, `x.nextUp` is `x` itself. The following special cases also /// apply: /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. var nextUp: Self { get } /// The greatest representable value that compares less than this value. /// /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. var nextDown: Self { get } /// Returns a Boolean value indicating whether this instance is equal to the /// given value. /// /// This method serves as the basis for the equal-to operator (`==`) for /// floating-point values. When comparing two values with this method, `-0` /// is equal to `+0`. NaN is not equal to any value, including itself. For /// example: /// /// let x = 15.0 /// x.isEqual(to: 15.0) /// // true /// x.isEqual(to: .nan) /// // false /// Double.nan.isEqual(to: .nan) /// // false /// /// The `isEqual(to:)` method implements the equality predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; /// otherwise, `false`. If either this value or `other` is NaN, the result /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the /// given value. /// /// This method serves as the basis for the less-than operator (`<`) for /// floating-point values. Some special cases apply: /// /// - Because NaN compares not less than nor greater than any value, this /// method returns `false` when called on NaN or when NaN is passed as /// `other`. /// - `-infinity` compares less than all values except for itself and NaN. /// - Every value except for NaN and `+infinity` compares less than /// `+infinity`. /// /// let x = 15.0 /// x.isLess(than: 20.0) /// // true /// x.isLess(than: .nan) /// // false /// Double.nan.isLess(than: x) /// // false /// /// The `isLess(than:)` method implements the less-than predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if this value is less than `other`; otherwise, `false`. /// If either this value or `other` is NaN, the result of this method is /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or /// equal to the given value. /// /// This method serves as the basis for the less-than-or-equal-to operator /// (`<=`) for floating-point values. Some special cases apply: /// /// - Because NaN is incomparable with any value, this method returns `false` /// when called on NaN or when NaN is passed as `other`. /// - `-infinity` compares less than or equal to all values except NaN. /// - Every value except NaN compares less than or equal to `+infinity`. /// /// let x = 15.0 /// x.isLessThanOrEqualTo(20.0) /// // true /// x.isLessThanOrEqualTo(.nan) /// // false /// Double.nan.isLessThanOrEqualTo(x) /// // false /// /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal /// predicate defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` is greater than this value; otherwise, /// `false`. If either this value or `other` is NaN, the result of this /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool /// Returns a Boolean value indicating whether this instance should precede /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including /// signed zeros and NaNs. /// /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } /// print(numbers) /// // Prints "[-9.5, 2.5, 3.0, 21.25, nan]" /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. /// - Returns: `true` if this value is ordered below or the same as `other` /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. /// /// A *normal* value is a finite number that uses the full precision /// available to values of a type. Zero is neither a normal nor a subnormal /// number. var isNormal: Bool { get } /// A Boolean value indicating whether this instance is finite. /// /// All values other than NaN and infinity are considered finite, whether /// normal or subnormal. For NaN, both `isFinite` and `isInfinite` are false. var isFinite: Bool { get } /// A Boolean value indicating whether the instance is equal to zero. /// /// The `isZero` property of a value `x` is `true` when `x` represents either /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: /// `x == 0.0`. /// /// let x = -0.0 /// x.isZero // true /// x == 0.0 // true var isZero: Bool { get } /// A Boolean value indicating whether the instance is subnormal. /// /// A *subnormal* value is a nonzero number that has a lesser magnitude than /// the smallest normal number. Subnormal values don't use the full /// precision available to values of a type. /// /// Zero is neither a normal nor a subnormal number. Subnormal numbers are /// often called *denormal* or *denormalized*---these are different names /// for the same concept. var isSubnormal: Bool { get } /// A Boolean value indicating whether the instance is infinite. /// /// For NaN, both `isFinite` and `isInfinite` are false. var isInfinite: Bool { get } /// A Boolean value indicating whether the instance is NaN ("not a number"). /// /// Because NaN is not equal to any value, including NaN, use this property /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) /// to test whether a value is or is not NaN. For example: /// /// let x = 0.0 /// let y = x * .infinity /// // y is a NaN /// /// // Comparing with the equal-to operator never returns 'true' /// print(x == Double.nan) /// // Prints "false" /// print(y == Double.nan) /// // Prints "false" /// /// // Test with the 'isNaN' property instead /// print(x.isNaN) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" /// /// This property is `true` for both quiet and signaling NaNs. var isNaN: Bool { get } /// A Boolean value indicating whether the instance is a signaling NaN. /// /// Signaling NaNs typically raise the Invalid flag when used in general /// computing operations. var isSignalingNaN: Bool { get } /// The classification of this value. /// /// A value's `floatingPointClass` property describes its "class" as /// described by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var floatingPointClass: FloatingPointClassification { get } /// A Boolean value indicating whether the instance's representation is in /// its canonical form. /// /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, /// encoding of a floating-point value. On platforms that fully support /// IEEE 754, every `Float` or `Double` value is canonical, but /// non-canonical values can exist on other platforms or for other types. /// Some examples: /// /// - On platforms that flush subnormal numbers to zero (such as armv7 /// with the default floating-point environment), Swift interprets /// subnormal `Float` and `Double` values as non-canonical zeros. /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these /// values, which is the incorrect value.) /// /// - On i386 and x86_64, `Float80` has a number of non-canonical /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are /// interpreted as non-canonical encodings of subnormal values. /// /// - Decimal floating-point types admit a large number of non-canonical /// encodings. Consult the IEEE 754 standard for additional details. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var isCanonical: Bool { get } } /// The sign of a floating-point value. @frozen public enum FloatingPointSign: Int, Sendable { /// The sign for a positive value. case plus /// The sign for a negative value. case minus // Explicit declarations of otherwise-synthesized members to make them // @inlinable, promising that we will never change the implementation. @inlinable public init?(rawValue: Int) { switch rawValue { case 0: self = .plus case 1: self = .minus default: return nil } } @inlinable public var rawValue: Int { switch self { case .plus: return 0 case .minus: return 1 } } @_transparent @inlinable public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool { return a.rawValue == b.rawValue } @inlinable public var hashValue: Int { return rawValue.hashValue } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable public func _rawHashValue(seed: Int) -> Int { return rawValue._rawHashValue(seed: seed) } } /// The IEEE 754 floating-point classes. @frozen public enum FloatingPointClassification: Sendable { /// A signaling NaN ("not a number"). /// /// A signaling NaN sets the floating-point exception status when used in /// many floating-point operations. case signalingNaN /// A silent NaN ("not a number") value. case quietNaN /// A value equal to `-infinity`. case negativeInfinity /// A negative value that uses the full precision of the floating-point type. case negativeNormal /// A negative, nonzero number that does not use the full precision of the /// floating-point type. case negativeSubnormal /// A value equal to zero with a negative sign. case negativeZero /// A value equal to zero with a positive sign. case positiveZero /// A positive, nonzero number that does not use the full precision of the /// floating-point type. case positiveSubnormal /// A positive value that uses the full precision of the floating-point type. case positiveNormal /// A value equal to `+infinity`. case positiveInfinity } /// A rule for rounding a floating-point number. public enum FloatingPointRoundingRule: Sendable { /// Round to the closest allowed value; if two values are equally close, the /// one with greater magnitude is chosen. /// /// This rounding rule is also known as "schoolbook rounding." The following /// example shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrAwayFromZero) /// // 5.0 /// (5.5).rounded(.toNearestOrAwayFromZero) /// // 6.0 /// (-5.2).rounded(.toNearestOrAwayFromZero) /// // -5.0 /// (-5.5).rounded(.toNearestOrAwayFromZero) /// // -6.0 /// /// This rule is equivalent to the C `round` function and implements the /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrAwayFromZero /// Round to the closest allowed value; if two values are equally close, the /// even one is chosen. /// /// This rounding rule is also known as "bankers rounding," and is the /// default IEEE 754 rounding mode for arithmetic. The following example /// shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrEven) /// // 5.0 /// (5.5).rounded(.toNearestOrEven) /// // 6.0 /// (4.5).rounded(.toNearestOrEven) /// // 4.0 /// /// This rule implements the `roundToIntegralTiesToEven` operation defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrEven /// Round to the closest allowed value that is greater than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.up) /// // 6.0 /// (5.5).rounded(.up) /// // 6.0 /// (-5.2).rounded(.up) /// // -5.0 /// (-5.5).rounded(.up) /// // -5.0 /// /// This rule is equivalent to the C `ceil` function and implements the /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case up /// Round to the closest allowed value that is less than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.down) /// // 5.0 /// (5.5).rounded(.down) /// // 5.0 /// (-5.2).rounded(.down) /// // -6.0 /// (-5.5).rounded(.down) /// // -6.0 /// /// This rule is equivalent to the C `floor` function and implements the /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case down /// Round to the closest allowed value whose magnitude is less than or equal /// to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.towardZero) /// // 5.0 /// (5.5).rounded(.towardZero) /// // 5.0 /// (-5.2).rounded(.towardZero) /// // -5.0 /// (-5.5).rounded(.towardZero) /// // -5.0 /// /// This rule is equivalent to the C `trunc` function and implements the /// `roundToIntegralTowardZero` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case towardZero /// Round to the closest allowed value whose magnitude is greater than or /// equal to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.awayFromZero) /// // 6.0 /// (5.5).rounded(.awayFromZero) /// // 6.0 /// (-5.2).rounded(.awayFromZero) /// // -6.0 /// (-5.5).rounded(.awayFromZero) /// // -6.0 case awayFromZero } extension FloatingPoint { @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.isEqual(to: rhs) } @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.isLess(than: rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs.isLessThanOrEqualTo(rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs.isLess(than: lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return rhs.isLessThanOrEqualTo(lhs) } } /// A radix-2 (binary) floating-point type. /// /// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol /// with operations specific to floating-point binary types, as defined by the /// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in /// the standard library by `Float`, `Double`, and `Float80` where available. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { /// A type that represents the encoded significand of a value. associatedtype RawSignificand: UnsignedInteger /// A type that represents the encoded exponent of a value. associatedtype RawExponent: UnsignedInteger /// Creates a new instance from the specified sign and bit patterns. /// /// The values passed as `exponentBitPattern` and `significandBitPattern` are /// interpreted in the binary interchange format defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign of the new value. /// - exponentBitPattern: The bit pattern to use for the exponent field of /// the new value. /// - significandBitPattern: The bit pattern to use for the significand /// field of the new value. init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Double) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float80) #endif /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. init<Source: BinaryFloatingPoint>(_ value: Source) /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. A value that is NaN ("not a number") cannot be /// represented exactly if its payload cannot be encoded exactly. /// /// - Parameter value: A floating-point value to be converted. init?<Source: BinaryFloatingPoint>(exactly value: Source) /// The number of bits used to represent the type's exponent. /// /// A binary floating-point type's `exponentBitCount` imposes a limit on the /// range of the exponent for normal, finite values. The *exponent bias* of /// a type `F` can be calculated as the following, where `**` is /// exponentiation: /// /// let bias = 2 ** (F.exponentBitCount - 1) - 1 /// /// The least normal exponent for values of the type `F` is `1 - bias`, and /// the largest finite exponent is `bias`. An all-zeros exponent is reserved /// for subnormals and zeros, and an all-ones exponent is reserved for /// infinity and NaN. /// /// For example, the `Float` type has an `exponentBitCount` of 8, which gives /// an exponent bias of `127` by the calculation above. /// /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 /// // bias == 127 /// print(Float.greatestFiniteMagnitude.exponent) /// // Prints "127" /// print(Float.leastNormalMagnitude.exponent) /// // Prints "-126" static var exponentBitCount: Int { get } /// The available number of fractional significand bits. /// /// For fixed-width floating-point types, this is the actual number of /// fractional significand bits. /// /// For extensible floating-point types, `significandBitCount` should be the /// maximum allowed significand width (without counting any leading integral /// bit of the significand). If there is no upper limit, then /// `significandBitCount` should be `Int.max`. /// /// Note that `Float80.significandBitCount` is 63, even though 64 bits are /// used to store the significand in the memory representation of a /// `Float80` (unlike other floating-point types, `Float80` explicitly /// stores the leading integral significand bit, but the /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't /// need to be aware of this detail). static var significandBitCount: Int { get } /// The raw encoding of the value's exponent field. /// /// This value is unadjusted by the type's exponent bias. var exponentBitPattern: RawExponent { get } /// The raw encoding of the value's significand field. /// /// The `significandBitPattern` property does not include the leading /// integral bit of the significand, even for types like `Float80` that /// store it explicitly. var significandBitPattern: RawSignificand { get } /// The floating-point value with the same sign and exponent as this value, /// but with a significand of 1.0. /// /// A *binade* is a set of binary floating-point values that all have the /// same sign and exponent. The `binade` property is a member of the same /// binade as this value, but with a unit significand. /// /// In this example, `x` has a value of `21.5`, which is stored as /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is /// equal to `1.0 * 2**4`, or `16.0`. /// /// let x = 21.5 /// // x.significand == 1.34375 /// // x.exponent == 4 /// /// let y = x.binade /// // y == 16.0 /// // y.significand == 1.0 /// // y.exponent == 4 var binade: Self { get } /// The number of bits required to represent the value's significand. /// /// If this value is a finite nonzero number, `significandWidth` is the /// number of fractional bits required to represent the value of /// `significand`; otherwise, `significandWidth` is -1. The value of /// `significandWidth` is always -1 or between zero and /// `significandBitCount`. For example: /// /// - For any representable power of two, `significandWidth` is zero, because /// `significand` is `1.0`. /// - If `x` is 10, `x.significand` is `1.01` in binary, so /// `x.significandWidth` is 2. /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in /// binary, and `x.significandWidth` is 23. var significandWidth: Int { get } } extension FloatingPoint { @inlinable // FIXME(sil-serialize-all) public static var ulpOfOne: Self { return (1 as Self).ulp } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs } @_transparent public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } @_transparent public mutating func round() { round(.toNearestOrAwayFromZero) } @inlinable // FIXME(inline-always) public var nextDown: Self { @inline(__always) get { return -(-self).nextUp } } @inlinable // FIXME(inline-always) @inline(__always) public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self lhs.formTruncatingRemainder(dividingBy: other) return lhs } @inlinable // FIXME(inline-always) @inline(__always) public func remainder(dividingBy other: Self) -> Self { var lhs = self lhs.formRemainder(dividingBy: other) return lhs } @_transparent public func squareRoot( ) -> Self { var lhs = self lhs.formSquareRoot( ) return lhs } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self addend.addProduct(lhs, rhs) return addend } @inlinable public static func minimum(_ x: Self, _ y: Self) -> Self { if x <= y || y.isNaN { return x } return y } @inlinable public static func maximum(_ x: Self, _ y: Self) -> Self { if x > y || y.isNaN { return x } return y } @inlinable public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude <= y.magnitude || y.isNaN { return x } return y } @inlinable public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude > y.magnitude || y.isNaN { return x } return y } @inlinable public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity } if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal } if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal } return sign == .minus ? .negativeZero : .positiveZero } } extension BinaryFloatingPoint { @inlinable @inline(__always) public static var radix: Int { return 2 } @inlinable public init(signOf: Self, magnitudeOf: Self) { self.init( sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern ) } public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self, exact: Bool) { guard _fastPath(!source.isZero) else { return (source.sign == .minus ? -0.0 : 0, true) } guard _fastPath(source.isFinite) else { if source.isInfinite { return (source.sign == .minus ? -.infinity : .infinity, true) } // IEEE 754 requires that any NaN payload be propagated, if possible. let payload_ = source.significandBitPattern & ~(Source.nan.significandBitPattern | Source.signalingNaN.significandBitPattern) let mask = Self.greatestFiniteMagnitude.significandBitPattern & ~(Self.nan.significandBitPattern | Self.signalingNaN.significandBitPattern) let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern, // we do not *need* to rely on this relation, and therefore we do not. let value = source.isSignalingNaN ? Self( sign: source.sign, exponentBitPattern: Self.signalingNaN.exponentBitPattern, significandBitPattern: payload | Self.signalingNaN.significandBitPattern) : Self( sign: source.sign, exponentBitPattern: Self.nan.exponentBitPattern, significandBitPattern: payload | Self.nan.significandBitPattern) // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. return (value, false) } let exponent = source.exponent var exemplar = Self.leastNormalMagnitude let exponentBitPattern: Self.RawExponent let leadingBitIndex: Int let shift: Int let significandBitPattern: Self.RawSignificand if exponent < exemplar.exponent { // The floating-point result is either zero or subnormal. exemplar = Self.leastNonzeroMagnitude let minExponent = exemplar.exponent if exponent + 1 < minExponent { return (source.sign == .minus ? -0.0 : 0, false) } if _slowPath(exponent + 1 == minExponent) { // Although the most significant bit (MSB) of a subnormal source // significand is explicit, Swift BinaryFloatingPoint APIs actually // omit any explicit MSB from the count represented in // significandWidth. For instance: // // Double.leastNonzeroMagnitude.significandWidth == 0 // // Therefore, we do not need to adjust our work here for a subnormal // source. return source.significandWidth == 0 ? (source.sign == .minus ? -0.0 : 0, false) : (source.sign == .minus ? -exemplar : exemplar, false) } exponentBitPattern = 0 as Self.RawExponent leadingBitIndex = Int(Self.Exponent(exponent) - minExponent) shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let leadingBit = source.isNormal ? (1 as Self.RawSignificand) << leadingBitIndex : 0 significandBitPattern = leadingBit | (shift >= 0 ? Self.RawSignificand(source.significandBitPattern) << shift : Self.RawSignificand(source.significandBitPattern >> -shift)) } else { // The floating-point result is either normal or infinite. exemplar = Self.greatestFiniteMagnitude if exponent > exemplar.exponent { return (source.sign == .minus ? -.infinity : .infinity, false) } exponentBitPattern = exponent < 0 ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent) : (1 as Self).exponentBitPattern + Self.RawExponent(exponent) leadingBitIndex = exemplar.significandWidth shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let sourceLeadingBit = source.isSubnormal ? (1 as Source.RawSignificand) << (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) : 0 significandBitPattern = shift >= 0 ? Self.RawSignificand( sourceLeadingBit ^ source.significandBitPattern) << shift : Self.RawSignificand( (sourceLeadingBit ^ source.significandBitPattern) >> -shift) } let value = Self( sign: source.sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) if source.significandWidth <= leadingBitIndex { return (value, true) } // We promise to round to the closest representation. Therefore, we must // take a look at the bits that we've just truncated. let ulp = (1 as Source.RawSignificand) << -shift let truncatedBits = source.significandBitPattern & (ulp - 1) if truncatedBits < ulp / 2 { return (value, false) } let rounded = source.sign == .minus ? value.nextDown : value.nextUp if _fastPath(truncatedBits > ulp / 2) { return (rounded, false) } // If two representable values are equally close, we return the value with // more trailing zeros in its significand bit pattern. return significandBitPattern.trailingZeroBitCount > rounded.significandBitPattern.trailingZeroBitCount ? (value, false) : (rounded, false) } /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init<Source: BinaryFloatingPoint>(_ value: Source) { // If two IEEE 754 binary interchange formats share the same exponent bit // count and significand bit count, then they must share the same encoding // for finite and infinite values. switch (Source.exponentBitCount, Source.significandBitCount) { #if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64)) case (5, 10): guard #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) //SwiftStdlib 5.3 else { // Convert signaling NaN to quiet NaN by multiplying by 1. self = Self._convert(from: value).value * 1 break } let value_ = value as? Float16 ?? Float16( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt16(truncatingIfNeeded: value.significandBitPattern)) self = Self(Float(value_)) #endif case (8, 23): let value_ = value as? Float ?? Float( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt32(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) case (11, 52): let value_ = value as? Double ?? Double( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt64(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) case (15, 63): let value_ = value as? Float80 ?? Float80( sign: value.sign, exponentBitPattern: UInt(truncatingIfNeeded: value.exponentBitPattern), significandBitPattern: UInt64(truncatingIfNeeded: value.significandBitPattern)) self = Self(value_) #endif default: // Convert signaling NaN to quiet NaN by multiplying by 1. self = Self._convert(from: value).value * 1 } } /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init?<Source: BinaryFloatingPoint>(exactly value: Source) { // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. if value.isNaN { return nil } if (Source.exponentBitCount > Self.exponentBitCount || Source.significandBitCount > Self.significandBitCount) && value.isFinite && !value.isZero { let exponent = value.exponent if exponent < Self.leastNormalMagnitude.exponent { if exponent < Self.leastNonzeroMagnitude.exponent { return nil } if value.significandWidth > Int(Self.Exponent(exponent) - Self.leastNonzeroMagnitude.exponent) { return nil } } else { if exponent > Self.greatestFiniteMagnitude.exponent { return nil } if value.significandWidth > Self.greatestFiniteMagnitude.significandWidth { return nil } } } self = Self(value) } @inlinable public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } if other > self { return false } // Self and other are either equal or unordered. // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // sign bit of self. if sign != other.sign { return sign == .minus } // Sign bits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return sign == .minus } if exponentBitPattern < other.exponentBitPattern { return sign == .plus } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return sign == .minus } if significandBitPattern < other.significandBitPattern { return sign == .plus } // Sign, exponent, and significand all match. return true } } extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger { public // @testable static func _convert<Source: BinaryInteger>( from source: Source ) -> (value: Self, exact: Bool) { // Useful constants: let exponentBias = (1 as Self).exponentBitPattern let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1 // Zero is really extra simple, and saves us from trying to normalize a // value that cannot be normalized. if _fastPath(source == 0) { return (0, true) } // We now have a non-zero value; convert it to a strictly positive value // by taking the magnitude. let magnitude = source.magnitude var exponent = magnitude._binaryLogarithm() // If the exponent would be larger than the largest representable // exponent, the result is just an infinity of the appropriate sign. guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } // If exponent <= significandBitCount, we don't need to round it to // construct the significand; we just need to left-shift it into place; // the result is always exact as we've accounted for exponent-too-large // already and no rounding can occur. if exponent <= Self.significandBitCount { let shift = Self.significandBitCount &- exponent let significand = RawSignificand(magnitude) &<< shift let value = Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ) return (value, true) } // exponent > significandBitCount, so we need to do a rounding right // shift, and adjust exponent if needed let shift = exponent &- Self.significandBitCount let halfway = (1 as Source.Magnitude) << (shift - 1) let mask = 2 * halfway - 1 let fraction = magnitude & mask var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask if fraction > halfway || (fraction == halfway && significand & 1 == 1) { var carry = false (significand, carry) = significand.addingReportingOverflow(1) if carry || significand > significandMask { exponent += 1 guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } } } return (Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ), fraction == 0) } /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init<Source: BinaryInteger>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init?<Source: BinaryInteger>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } }
apache-2.0
kenwilcox/Swift-Linux
Hello/Sources/Greeter.swift
1
162
func sayHello(name: String) { print("Hello, \(name)!") if (name == "John Jacob Jingleheimer Schmidt") { print("Your name is my name too!") } }
mit
suragch/MongolAppDevelopment-iOS
Mongol App Componants/KeyboardKey.swift
1
5273
// This is a generic Keyboard Key class for specific key classes to subclass. Its main purposes are to // (1) provide a common background appearance for all keys // (2) set the standard for how to communicate with the parent keyboard class import UIKit // protocol for communication with keyboard protocol KeyboardKeyDelegate: class { func keyTextEntered(_ keyText: String) func keyFvsTapped(_ fvs: String) func keyBackspaceTapped() func keyKeyboardTapped() func keyNewKeyboardChosen(_ keyboardName: String) func otherAvailableKeyboards(_ displayNames: [String]) } @IBDesignable class KeyboardKey: UIControl { weak var delegate: KeyboardKeyDelegate? // probably a keyboard class fileprivate let backgroundLayer = KeyboardKeyBackgroundLayer() fileprivate var oldFrame = CGRect.zero // space between the frame edge of the visible border of the key var padding: CGFloat { get { return backgroundLayer.padding } } var fillColor = UIColor.white { didSet { backgroundLayer.setNeedsDisplay() } } var borderColor = UIColor.gray { didSet { backgroundLayer.setNeedsDisplay() } } @IBInspectable var cornerRadius: CGFloat = 8 { didSet { backgroundLayer.setNeedsDisplay() } } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initializeBackgroundLayer() } required init?(coder: NSCoder) { super.init(coder: coder) initializeBackgroundLayer() } override var frame: CGRect { didSet { // only update frames if non-zero and changed if frame != CGRect.zero && frame != oldFrame { updateBackgroundFrame() } } } func initializeBackgroundLayer() { // Background layer backgroundLayer.keyboardKey = self backgroundLayer.contentsScale = UIScreen.main.scale layer.addSublayer(backgroundLayer) // Long press guesture recognizer addLongPressGestureRecognizer() } // subclasses can override this method if they don't want the gesture recognizer func addLongPressGestureRecognizer() { let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:))) self.addGestureRecognizer(longPress) } func updateBackgroundFrame() { backgroundLayer.frame = bounds backgroundLayer.setNeedsDisplay() } // MARK: - Other methods func longPress(_ guesture: UILongPressGestureRecognizer) { if guesture.state == UIGestureRecognizerState.began { backgroundLayer.highlighted = false longPressBegun(guesture) } else if guesture.state == UIGestureRecognizerState.changed { longPressStateChanged(guesture) } else if guesture.state == UIGestureRecognizerState.ended { longPressEnded() } else if guesture.state == UIGestureRecognizerState.cancelled { longPressCancelled() } } func longPressBegun(_ guesture: UILongPressGestureRecognizer) { // this method is for subclasses to override } func longPressStateChanged(_ guesture: UILongPressGestureRecognizer) { // this method is for subclasses to override } func longPressEnded() { // this method is for subclasses to override } func longPressCancelled() { // this method is for subclasses to override } // MARK: - Overrides override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { backgroundLayer.highlighted = true return backgroundLayer.highlighted } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { backgroundLayer.highlighted = false } } // MARK: - Key Background Layer Class class KeyboardKeyBackgroundLayer: CALayer { var highlighted: Bool = false { didSet { setNeedsDisplay() } } weak var keyboardKey: KeyboardKey? let padding: CGFloat = 2.0 override func draw(in ctx: CGContext) { if let key = keyboardKey { let keyFrame = bounds.insetBy(dx: padding, dy: padding) let keyPath = UIBezierPath(roundedRect: keyFrame, cornerRadius: key.cornerRadius) //let borderColor = key.borderColor.CGColor // Fill ctx.setFillColor(key.fillColor.cgColor) ctx.addPath(keyPath.cgPath) ctx.fillPath() // Outline ctx.setStrokeColor(key.borderColor.cgColor) ctx.setLineWidth(0.5) ctx.addPath(keyPath.cgPath) ctx.strokePath() if highlighted { ctx.setFillColor(UIColor(white: 0.0, alpha: 0.1).cgColor) ctx.addPath(keyPath.cgPath) ctx.fillPath() } } } }
mit
Moballo/MOBCore
Sources-iOS-only/MOBAlerts.swift
2
7834
// // MOBAlerts.swift // MOBCore // // Created by Jason Morcos on 12/4/15. // Copyright © 2017 Moballo, LLC. All rights reserved. // import UIKit public var MOBAlertQueue = [MOBAlertController]() public var MOBAlertTimer: Timer? public class MOBAlertHandler: NSObject { @objc var internalApplication: UIApplication @objc public func MOBAlertTimerCall() { self.presentAlertController() } @objc public init(_ application: UIApplication) { internalApplication = application super.init() } @objc public func dismissAlert(completion: (() -> Void)? = nil) { if let keyWindow = internalApplication.getCurrentWindow() { if let rootVC = keyWindow.rootViewController { let topVC = getTopmostNavController(relativeTo: rootVC) if topVC.presentedViewController is MOBAlertController { topVC.dismiss(animated: true, completion: completion) return } } } if ((completion) != nil) { completion!() } } @objc public func tryQueuedAlerts() { self.presentAlertController() } @objc public func minimizeAllAlerts(completion: (() -> Void)? = nil) { if let theTimer = MOBAlertTimer , MOBAlertQueue.count == 0 { theTimer.invalidate() MOBAlertTimer = nil } if let keyWindow = internalApplication.getCurrentWindow() { if let rootVC = keyWindow.rootViewController { let topVC = getTopmostNavController(relativeTo: rootVC) if let currentAlert = topVC.presentedViewController as? MOBAlertController { MOBAlertQueue.insert(currentAlert, at: 0) DispatchQueue.main.async { topVC.dismiss(animated: true, completion: completion) } return } } } if ((completion) != nil) { completion!() } } fileprivate func presentAlertController(_ inputAlert: MOBAlertController? = nil, placeOnTopOfQueue:Bool = false, completion: (() -> Void)? = nil) { if let keyWindow = internalApplication.getCurrentWindow() { if let rootVC = keyWindow.rootViewController { let topVC = getTopmostNavController(relativeTo: rootVC) if let inputAlertItem = inputAlert { if let alertIdentifier = inputAlertItem.alertIdentifier { if let presented = topVC.presentedViewController as? MOBAlertController { if presented.alertIdentifier == alertIdentifier { return } } if MOBAlertQueue.count > 0 { for anAlert in MOBAlertQueue { if anAlert.alertIdentifier == alertIdentifier { return } } } } if (placeOnTopOfQueue) { MOBAlertQueue.insert(inputAlertItem, at: 0) } else { MOBAlertQueue.append(inputAlertItem) } } if MOBAlertTimer == nil { MOBAlertTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.MOBAlertTimerCall), userInfo: nil, repeats: true) } if let _ = topVC.presentedViewController as? UIAlertController { return } if MOBAlertQueue.count > 0 && topVC.isViewLoaded { if let toPresent = MOBAlertQueue.first { toPresent.alertHandler = self topVC.present(toPresent, animated: true, completion: { if ((completion) != nil) { completion!() } if let textFields = toPresent.textFields , (keyWindow.bounds.height < 667.0 && keyWindow.bounds.width < 667.0) { self.mobAlertDelay(0.1) { toPresent.resignFirstResponder() for aField in textFields { aField.resignFirstResponder() } toPresent.resignFirstResponder() } } if MOBAlertQueue.count > 0 { MOBAlertQueue.removeFirst() } if let theTimer = MOBAlertTimer , MOBAlertQueue.count == 0 { theTimer.invalidate() MOBAlertTimer = nil } }) } } } } if let theTimer = MOBAlertTimer , MOBAlertQueue.count == 0 { theTimer.invalidate() MOBAlertTimer = nil } } private func getTopmostNavController(relativeTo inputView: UIViewController) -> UIViewController { if let presented = inputView.presentedViewController as? UINavigationController { return getTopmostNavController(relativeTo: presented) } return inputView } private func mobAlertDelay(_ delay: Double, closure: @escaping ()->()) { let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: closure) } @objc public static func resetQueue() { if let theTimer = MOBAlertTimer { theTimer.invalidate() } MOBAlertQueue = [MOBAlertController]() } } public class MOBAlertController: UIAlertController { //used to make duplicate alerts not a thing @objc public var alertIdentifier: String? @objc var alertHandler: MOBAlertHandler? @objc public static func alertControllerWithTitle(title:String?,message:String?,actions:[UIAlertAction],dismissingActionTitle:String? = "Dismiss", dismissBlock:(() -> ())?) -> MOBAlertController { let alertController = MOBAlertController(title: title, message: message, preferredStyle: .alert) if dismissingActionTitle != nil { let okAction = UIAlertAction(title: dismissingActionTitle, style: .default) { (action) -> Void in if dismissBlock != nil { dismissBlock?() } } alertController.addAction(okAction) } for action in actions { alertController.addAction(action) } return alertController } deinit { if let handler = alertHandler { handler.tryQueuedAlerts() } } @objc public func show(_ application: UIApplication) { let handler = MOBAlertHandler(application) handler.presentAlertController(self) } @objc public func showNow(_ application: UIApplication, completion: (() -> Void)? = nil) { let handler = MOBAlertHandler(application) handler.minimizeAllAlerts() handler.presentAlertController(self, placeOnTopOfQueue: true, completion: completion) } @objc public func showNext(_ application: UIApplication) { let handler = MOBAlertHandler(application) handler.presentAlertController(self, placeOnTopOfQueue: true) } }
mit
emilstahl/swift
validation-test/compiler_crashers/26206-swift-constraints-constraintsystem-opengeneric.swift
9
278
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A{init()}func b{struct c<T where I:a{class a:A
apache-2.0
JamieScanlon/AugmentKit
AugmentKit/AKCore/Anchors/AugmentedAnchor.swift
1
4589
// // AugmentedAnchor.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import ARKit import Foundation import ModelIO /** A generic implementation of `AKAugmentedAnchor`. An AR anchor that can be placed in the AR world. These can be created and given to the AR engine to render in the AR world. */ open class AugmentedAnchor: AKAugmentedAnchor { /** Returns "AugmentedAnchor" */ public static var type: String { return "AugmentedAnchor" } /** The location of the anchor */ public var worldLocation: AKWorldLocation /** The locaiton of the anchor */ public var heading: AKHeading = NorthHeading() /** The `MDLAsset` associated with the entity. */ public var asset: MDLAsset /** A unique, per-instance identifier */ public var identifier: UUID? /** An array of `AKEffect` objects that are applied by the renderer */ public var effects: [AnyEffect<Any>]? /** Specified a perfered renderer to use when rendering this enitity. Most will use the standard PBR renderer but some entities may prefer a simpiler renderer when they are not trying to achieve the look of real-world objects. Defaults to the PBR renderer. */ public var shaderPreference: ShaderPreference = .pbr /** Indicates whether this geometry participates in the generation of augmented shadows. Since this is an augmented geometry, it does generate shadows. */ public var generatesShadows: Bool = true /** If `true`, the current base color texture of the entity has changed since the last time it was rendered and the pixel data needs to be updated. This flag can be used to achieve dynamically updated textures for rendered objects. */ public var needsColorTextureUpdate: Bool = false /// If `true` the underlying mesh for this geometry has changed and the renderer needs to update. This can be used to achieve dynamically generated geometries that change over time. public var needsMeshUpdate: Bool = false /** An `ARAnchor` that will be tracked in the AR world by `ARKit` */ public var arAnchor: ARAnchor? /** Initialize a new object with an `MDLAsset` and an `AKWorldLocation` - Parameters: - withModelAsset: The `MDLAsset` associated with the entity. - at: The location of the anchor */ public init(withModelAsset asset: MDLAsset, at location: AKWorldLocation) { self.asset = asset self.worldLocation = location } /** Sets a new `arAnchor` - Parameters: - _: An `ARAnchor` */ public func setARAnchor(_ arAnchor: ARAnchor) { self.arAnchor = arAnchor if identifier == nil { identifier = arAnchor.identifier } worldLocation.transform = arAnchor.transform } } /// :nodoc: extension AugmentedAnchor: CustomDebugStringConvertible, CustomStringConvertible { /// :nodoc: public var description: String { return debugDescription } /// :nodoc: public var debugDescription: String { let myDescription = "<AugmentedAnchor: \(Unmanaged.passUnretained(self).toOpaque())> worldLocation: \(worldLocation), identifier:\(identifier?.debugDescription ?? "None"), effects: \(effects?.debugDescription ?? "None"), arAnchor: \(arAnchor?.debugDescription ?? "None"), asset: \(asset)" return myDescription } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/25663-swift-concretedeclref-specializeddeclref-create.swift
1
429
// 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 func d{a< protocol e var e{{e{
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/06542-swift-unqualifiedlookup-unqualifiedlookup.swift
1
460
// 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 struct Q<H{var b{struct d<T where k=b{}struct d<T where H.g:d
apache-2.0
IndisputableLabs/Swifthereum
Swifthereum/Classes/Web3/Models/NewTransaction.swift
1
771
// // NewTransaction.swift // Swifthereum // // Created by Ronald Mannak on 10/19/17. // import Foundation /** Used to create a new transaction params: [{ "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", // 30400, "gasPrice": "0x9184e72a000", // 10000000000000 "value": "0x9184e72a", // 2441406250 "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }] */ public struct NewTransaction { public let from: Address? public let to: Address public let gas: Wei? public let gasPrice: Wei? public let value: HashString? public let data: String? public let nonce: Int? } //extension NewTransaction: Codable { //}
mit
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/Items/Responses/HistorySinceResponse.swift
1
3579
// // HistorySinceResponse.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 15.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ struct HistorySinceResponse { // MARK: - Constants // Raw values equal to field names received in responses from server. enum JSONField: String { case data = "data" } // MARK: - Properties private var historyResponseData: HistoryResponseData? // MARK: - Initialization init(jsonDictionary: [String: Any?]) { if let dataDictionary = jsonDictionary[JSONField.data.rawValue] as? [String: Any?] { historyResponseData = HistoryResponseData(jsonDictionary: dataDictionary) } } // MARK: - Methods func getData() -> HistoryResponseData? { return historyResponseData } // MARK: - struct HistoryResponseData { // MARK: - Constants // Raw values equal to field names received in responses from server. enum JSONField: String { case hasMore = "hasMore" case messages = "messages" case revision = "revision" } // MARK: - Properties private var hasMore: Bool? private var messages: [MessageItem]? private var revision: String? // MARK: - Initialization init(jsonDictionary: [String: Any?]) { var messages = [MessageItem]() if let messagesArray = jsonDictionary[JSONField.messages.rawValue] as? [Any?] { for item in messagesArray { if let messageDictionary = item as? [String: Any?] { let messageItem = MessageItem(jsonDictionary: messageDictionary) messages.append(messageItem) } } } self.messages = messages hasMore = ((jsonDictionary[JSONField.hasMore.rawValue] as? Bool) ?? false) revision = jsonDictionary[JSONField.revision.rawValue] as? String } // MARK: - Methods func getMessages() -> [MessageItem]? { return messages } func isHasMore() -> Bool? { return hasMore } func getRevision() -> String? { return revision } } }
mit
julienbodet/wikipedia-ios
Wikipedia/Code/UIViewController+WMFChildViewController.swift
1
807
import Foundation import WMF extension UIViewController { /// Embeds a view controller's view in a container view ensuring the container view expands vertically as needed to encompass any AutoLayout changes to the embedded view which affect its height. /// /// - Parameters: /// - childController: Controller whose view will be embedded in containerView /// - containerView: View to which childController's view will be added as a subview @objc public func wmf_add(childController: UIViewController!, andConstrainToEdgesOfContainerView containerView: UIView!) { addChildViewController(childController) containerView.wmf_addHeightDeterminingSubviewWithConstraintsToEdges(childController.view) childController.didMove(toParentViewController: self) } }
mit
Seanalair/GreenAR
GreenAR/Classes/Helpers/QRCodeLocator.swift
1
8380
// // QRCodeLocator.swift // GreenAR_Example // // Created by Daniel Grenier on 10/20/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import UIKit import ARKit public class QRCodeLocator { /** Initializes a CIDetector and attempts to find a QR code in the provided image. - Parameter image: The `CIImage` to attempt to find a QR code in. - Returns: A `CIQRCodeFeature` representing the QR code detected, or `nil` if no QR code is detected. */ public static func performQRCodeDetection(image: CIImage) -> CIQRCodeFeature? { let detectorOptions = [CIDetectorAccuracy: CIDetectorAccuracyHigh] if let qrCodeDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: detectorOptions) { let features = qrCodeDetector.features(in: image) for feature in features as! [CIQRCodeFeature] { return feature } } return nil } /** Attempts to find a QR code in the view of the world currently visible in the provided `ARSCNView`. - Parameter sceneView: The `ARSCNView` to attempt to find a QR code in. - Returns: A tuple of the `String` encoded in the detected QR code and an `SCNVector3` representing its location in the world, or `(nil, nil)` if a QR code is not detected. */ public static func captureAndLocateQRCode(sceneView:ARSCNView) -> (String?, SCNVector3?) { let snapshot = sceneView.snapshot() // If we are unable to find a QR code in the snapshot, simply return (nil, nil) guard let cgSnapshot = snapshot.cgImage, let qrCodeFeature = performQRCodeDetection(image: CIImage(cgImage:cgSnapshot)) else { print("No QRCode Found.") return (nil, nil); } // Determine the minimum and maximum x and y values of the detected qr code let codeMinX = min(qrCodeFeature.topLeft.x / 2, qrCodeFeature.topRight.x / 2, qrCodeFeature.bottomLeft.x / 2, qrCodeFeature.bottomRight.x / 2) let codeMaxX = max(qrCodeFeature.topLeft.x / 2, qrCodeFeature.topRight.x / 2, qrCodeFeature.bottomLeft.x / 2, qrCodeFeature.bottomRight.x / 2) let codeWidth = codeMaxX - codeMinX let codeMinY = min(qrCodeFeature.topLeft.y / 2, qrCodeFeature.topRight.y / 2, qrCodeFeature.bottomLeft.y / 2, qrCodeFeature.bottomRight.y / 2) let codeMaxY = max(qrCodeFeature.topLeft.y / 2, qrCodeFeature.topRight.y / 2, qrCodeFeature.bottomLeft.y / 2, qrCodeFeature.bottomRight.y / 2) let codeHeight = codeMaxY - codeMinY // Initialize the list of view locations to use for hit testing and populate it with a 5 x 5 grid of test locations var hitTestPoints: [CGPoint]! = [CGPoint]() for xIndex in 0...4 { for yIndex in 0...4 { let fractionOfWidth = CGFloat(Double(xIndex) * 0.25) let portionOfWidth = codeWidth * fractionOfWidth let x = codeMinX + portionOfWidth let fractionOfHeight = CGFloat(Double(yIndex) * 0.25) let portionOfHeight = codeHeight * fractionOfHeight let y = codeMinY + portionOfHeight hitTestPoints.append(CGPoint(x:x, y:sceneView.bounds.height - y)) } } // Initialize the list of hit test results and the variables that will track debugging information about the hit tests performed to find the QR code in the world. var hitTestResults: [ARHitTestResult]! = [ARHitTestResult]() var hitTestSuccesses = 0 var hitTestFailures = 0 var minDistance: CGFloat! = CGFloat(-1) var maxDistance: CGFloat! = CGFloat(-1) var meanDistance: CGFloat! = CGFloat(0) var sortedDistances: [CGFloat]! = [CGFloat]() // Perform the hit tests for point in hitTestPoints { let results = sceneView.hitTest(point, types: .featurePoint) if let hitTestResult = results.first { // Update minimum and maximum hit test result distance, if applicable if (minDistance == -1 || (hitTestResult.distance < minDistance)) { minDistance = hitTestResult.distance } if (maxDistance == -1 || (hitTestResult.distance > maxDistance)) { maxDistance = hitTestResult.distance } // Update running sum used to calculate mean distance meanDistance = meanDistance + hitTestResult.distance // Insert this distance into the sorted list of distances (for finding median distance) if (sortedDistances.count == 0) { sortedDistances.append(hitTestResult.distance) } else { for index in 0..<sortedDistances.endIndex { if (hitTestResult.distance < sortedDistances[index]) { sortedDistances.insert(hitTestResult.distance, at: index) break } } } // Add this result to the list of results hitTestResults.append(hitTestResult) hitTestSuccesses += 1 } else { // print debugging information about the failed hit test point print("Unable to find hit at \(String(describing: point))") hitTestFailures += 1 } } // Determine mean and median distance, for debugging meanDistance = meanDistance / CGFloat(hitTestResults.count) var medianDistance: CGFloat! = CGFloat(0) if (sortedDistances.count > 0) { medianDistance = sortedDistances[sortedDistances.count / 2] } // print debugging information about hit tests print("\(hitTestSuccesses) successful tests, \(hitTestFailures) failed tests.") print("Minimum Distance:\(minDistance) - Maximum Distance:\(maxDistance) - Mean Distance:\(meanDistance) - Median Distance:\(medianDistance)") // Filter to the extreme end of the range of distances found that the mean distance is closer to. let filterOnMaximum = ((maxDistance - meanDistance) < (meanDistance - minDistance)) // Keep a running sum of the x, y, and z values of the points that make it through our filter so we can calculate a single "average" coordinate location var totalX:Float = 0 var totalY:Float = 0 var totalZ:Float = 0 var filteredCollisionPoints: [SCNVector3] = [SCNVector3]() for result in hitTestResults { // Ignore results not within 20% of the end of the range that the mean distance is closer to if ((filterOnMaximum && ((result.distance / maxDistance) > 0.8)) || (!filterOnMaximum && ((minDistance / result.distance) > 0.8))) { let x = result.worldTransform[3][0] let y = result.worldTransform[3][1] let z = result.worldTransform[3][2] totalX += x totalY += y totalZ += z filteredCollisionPoints.append(SCNVector3(x, y, z)) } } if (filteredCollisionPoints.count > 0) { // If and points passed our test (i.e. we did not get 0 results from our hit tests), return the qr code's message and the average coordinates of our successful hit tests let averageX = totalX / Float(filteredCollisionPoints.count) let averageY = totalY / Float(filteredCollisionPoints.count) let averageZ = totalZ / Float(filteredCollisionPoints.count) return (qrCodeFeature.messageString, SCNVector3(averageX, averageY, averageZ)) } // If we got 0 successful hit test results, return (nil, nil) return (nil, nil) } }
mit
apparata/ProjectKit
Sources/ProjectKit/Project File Objects/TargetDependency.swift
1
995
import Foundation /// References a target through content proxies. public class TargetDependency: ProjectFileObject { public class ID: ObjectID { } /// Object type from project file. public static var isa: String { return "PBXTargetDependency" } /// A 96 bit unique identifier. public private(set) var id: ID /// A 96 bit unique identifier. public var objectID: ObjectID { return id } /// The raw dictionary representation of the object. public private(set) var object: NSDictionary /// The target to build to satisfy this dependency. public private(set) var target: NativeTarget.ID? // Proxy for the target to build. public private(set) var targetProxy: ContainerItemProxy.ID? public init(id: ID, object: NSDictionary) { self.id = id self.object = object target = decodeID(object["target"]) targetProxy = decodeID(object["targetProxy"]) } }
mit
britez/sdk-ios
sdk_ios_v2/Extensions.swift
2
1894
// Extensions.swift // import Alamofire extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } } extension Float: JSONEncodable { func encodeToJSON() -> Any { return self as Any } } extension Int: JSONEncodable { func encodeToJSON() -> Any { return self as Any } } extension Int32: JSONEncodable { func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } } extension Int64: JSONEncodable { func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } } extension Double: JSONEncodable { func encodeToJSON() -> Any { return self as Any } } extension String: JSONEncodable { func encodeToJSON() -> Any { return self as Any } } private func encodeIfPossible<T>(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { return object as Any } } extension Array: JSONEncodable { func encodeToJSON() -> Any { return self.map(encodeIfPossible) } } extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() for (key, value) in self { dictionary[key as! NSObject] = encodeIfPossible(value) } return dictionary as Any } } extension Data: JSONEncodable { func encodeToJSON() -> Any { return self.base64EncodedString(options: Data.Base64EncodingOptions()) } } private let dateFormatter: DateFormatter = { let fmt = DateFormatter() fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" fmt.locale = Locale(identifier: "en_US_POSIX") return fmt }() extension Date: JSONEncodable { func encodeToJSON() -> Any { return dateFormatter.string(from: self) as Any } } extension UUID: JSONEncodable { func encodeToJSON() -> Any { return self.uuidString } }
mit
gustavosaume/DotUserDefaults
DotUserDefaults/Classes/NSUserDefaults+DotExtensions.swift
1
6576
// // UserDefaultsUtils.swift // UserDefaultsUtils // // Created by Gustavo Saume on 4/28/16. // Copyright © 2016 BigPanza. All rights reserved. // import Foundation public enum RawRepresentableError: ErrorType { case InvalidRawValue } extension NSUserDefaults { public func objectForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> AnyObject? { return objectForKey(defaultName.rawValue) } public func setObject<K: RawRepresentable where K.RawValue == String>(value: AnyObject?, forKey defaultName: K) { setObject(value, forKey: defaultName.rawValue) } public func removeObjectForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) { removeObjectForKey(defaultName.rawValue) } public func stringForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> String? { return stringForKey(defaultName.rawValue) } public func arrayForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> [AnyObject]? { return arrayForKey(defaultName.rawValue) } public func dictionaryForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> [String : AnyObject]? { return dictionaryForKey(defaultName.rawValue) } public func dataForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> NSData? { return dataForKey(defaultName.rawValue) } public func stringArrayForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> [String]? { return stringArrayForKey(defaultName.rawValue) } public func integerForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> Int { return integerForKey(defaultName.rawValue) } public func floatForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> Float { return floatForKey(defaultName.rawValue) } public func doubleForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> Double { return doubleForKey(defaultName.rawValue) } public func boolForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> Bool { return boolForKey(defaultName.rawValue) } public func URLForKey<K: RawRepresentable where K.RawValue == String>(defaultName: K) -> NSURL? { return URLForKey(defaultName.rawValue) } public func enumForKey<T: RawRepresentable where T.RawValue == Int>(defaultName: String) -> T? { guard let storedEnum = T(rawValue: integerForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<K: RawRepresentable, T: RawRepresentable where K.RawValue == String, T.RawValue == Int>(defaultName: K) -> T? { guard let storedEnum = T(rawValue: integerForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<T: RawRepresentable where T.RawValue == Double>(defaultName: String) -> T? { guard let storedEnum = T(rawValue: doubleForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<K: RawRepresentable, T: RawRepresentable where K.RawValue == String, T.RawValue == Double>(defaultName: K) -> T? { guard let storedEnum = T(rawValue: doubleForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<T: RawRepresentable where T.RawValue == Float>(defaultName: String) -> T? { guard let storedEnum = T(rawValue: floatForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<K: RawRepresentable, T: RawRepresentable where K.RawValue == String, T.RawValue == Float>(defaultName: K) -> T? { guard let storedEnum = T(rawValue: floatForKey(defaultName)) else { return nil } return storedEnum } public func enumForKey<T: RawRepresentable where T.RawValue == String>(defaultName: String) -> T? { guard let storedString = stringForKey(defaultName), storedEnum = T(rawValue: storedString) else { return nil } return storedEnum } public func enumForKey<K: RawRepresentable, T: RawRepresentable where K.RawValue == String, T.RawValue == String>(defaultName: K) -> T? { guard let storedString = stringForKey(defaultName), storedEnum = T(rawValue: storedString) else { return nil } return storedEnum } // MARK: - Setters public func setInteger<K: RawRepresentable where K.RawValue == String>(value: Int, forKey defaultName: K) { setInteger(value, forKey: defaultName.rawValue) } public func setFloat<K: RawRepresentable where K.RawValue == String>(value: Float, forKey defaultName: K) { setFloat(value, forKey: defaultName.rawValue) } public func setDouble<K: RawRepresentable where K.RawValue == String>(value: Double, forKey defaultName: K) { setDouble(value, forKey: defaultName.rawValue) } public func setBool<K: RawRepresentable where K.RawValue == String>(value: Bool, forKey defaultName: K) { setBool(value, forKey: defaultName.rawValue) } @available(iOS 4.0, *) public func setURL<K: RawRepresentable where K.RawValue == String>(url: NSURL?, forKey defaultName: K) { setURL(url, forKey: defaultName.rawValue) } public func setEnum<V: RawRepresentable where V.RawValue == String>(value: V, forKey key: String) { setObject(value.rawValue, forKey: key) } public func setEnum<V: RawRepresentable, K: RawRepresentable where V.RawValue == String, K.RawValue == String>(value: V, forKey key: K) { setObject(value.rawValue, forKey: key.rawValue) } public func setEnum<V: RawRepresentable where V.RawValue == Int>(value: V, forKey key: String) { setInteger(value.rawValue, forKey: key) } public func setEnum<V: RawRepresentable, K: RawRepresentable where V.RawValue == Int, K.RawValue == String>(value: V, forKey key: K) { setInteger(value.rawValue, forKey: key.rawValue) } public func setEnum<V: RawRepresentable where V.RawValue == Double>(value: V, forKey key: String) { setDouble(value.rawValue, forKey: key) } public func setEnum<V: RawRepresentable, K: RawRepresentable where V.RawValue == Double, K.RawValue == String>(value: V, forKey key: K) { setDouble(value.rawValue, forKey: key.rawValue) } public func setEnum<V: RawRepresentable where V.RawValue == Float>(value: V, forKey key: String) { setFloat(value.rawValue, forKey: key) } public func setEnum<V: RawRepresentable, K: RawRepresentable where V.RawValue == Float, K.RawValue == String>(value: V, forKey key: K) { setFloat(value.rawValue, forKey: key.rawValue) } }
mit
mentrena/SyncKit
SyncKit/Classes/RealmSwift/SyncedEntity.swift
1
970
// // SyncedEntity.swift // Pods // // Created by Manuel Entrena on 29/08/2017. // // import Foundation import RealmSwift class SyncedEntity: Object { @objc dynamic var entityType: String = "" @objc dynamic var identifier: String = "" @objc dynamic var state: Int = 0 @objc dynamic var changedKeys: String? @objc dynamic var updated: Date? @objc dynamic var record: Record? @objc dynamic var share: SyncedEntity? convenience init(entityType: String, identifier: String, state: Int) { self.init() self.entityType = entityType self.identifier = identifier self.state = state } override static func primaryKey() -> String? { return "identifier" } var entityState: SyncedEntityState { set { state = newValue.rawValue } get { return SyncedEntityState(rawValue: state)! } } }
mit
GuiBayma/PasswordVault
PasswordVaultTests/Scenes/Group Detail/ItemTableViewCellTests.swift
1
1514
// // ItemTableViewCellTests.swift // PasswordVault // // Created by Guilherme Bayma on 7/28/17. // Copyright © 2017 Bayma. All rights reserved. // import Foundation import Quick import Nimble @testable import PasswordVault class ItemTableViewCellTests: QuickSpec { override func spec() { describe("ItemTableViewCell tests") { var sut: ItemTableViewCell? let item = ItemManager.sharedInstance.newItem() beforeEach { sut = ItemTableViewCell() } afterSuite { if let itm = item { if !ItemManager.sharedInstance.delete(object: itm) { fail("could not delete Item") } } } it("should not be nil") { expect(sut).toNot(beNil()) } #if arch(x86_64) && _runtime(_ObjC) && !SWIFT_PACKAGE it("should not load through storyboard") { expect { _ = ItemTableViewCell(coder: NSCoder()) }.to(throwAssertion()) } #endif it("should configure correctly") { guard let item = item else { fail("item is nil") return } item.name = "Item name" sut?.configure(item) expect(sut?.label.text) == item.name } } } }
mit
Vienta/kuafu
kuafu/kuafu/src/Manager/KFDBManager.swift
1
1477
// // KFDBManager.swift // kuafu // // Created by Vienta on 15/6/5. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit import FMDB let SQLDOC = "iDoc" let KF_EVENT_SQL = "KFEvent.sqlite" private let sharedInstance = KFDBManager() class KFDBManager: NSObject { var dbQueue: FMDatabaseQueue? class var sharedManager : KFDBManager { return sharedInstance } override init() { super.init() dbQueue = FMDatabaseQueue(path: self.databasePath()) } func sqlPath() -> String { let docPath:String = KFUtil.documentFilePath(SQLDOC) let fileExist:Bool = NSFileManager.defaultManager().fileExistsAtPath(docPath) if(!fileExist) { NSFileManager.defaultManager().createDirectoryAtPath(docPath, withIntermediateDirectories: true, attributes: nil, error: nil) } KFUtil.skipBackupAttributeToItemAtPath(NSURL.fileURLWithPath(docPath)!) return docPath } func databasePath() -> String? { self.sqlPath() // let filePathString = SQLDOC + "/" + KF_EVENT_SQL // var dbPath: String = KFUtil.documentFilePath(filePathString) var dbGroupPath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(KF_GROUP_ID) dbGroupPath = dbGroupPath!.URLByAppendingPathComponent(KF_EVENT_SQL) return dbGroupPath?.path } }
mit
willer88/Rappi-Catalog
RappiCatalog/RappiCatalog/Controllers/AppDetailController.swift
1
1141
// // AppDetailController.swift // RappiCatalog // // Created by wilmar lema on 6/14/16. // Copyright © 2016 Lemax Inc. All rights reserved. // import UIKit class AppDetailController: UIViewController { @IBOutlet weak var appImage: UIImageView! @IBOutlet weak var appDescriptionLbl: UILabel! var app: App? override func viewDidLoad() { super.viewDidLoad() self.title = app?.name self.appImage.kf_showIndicatorWhenLoading = true self.appImage.kf_setImageWithURL(NSURL(string: app!.iconUrl)!) self.appDescriptionLbl.text = self.app?.description } override func viewWillDisappear(animated: Bool) { UIView.animateWithDuration(0.75, animations: { () -> Void in UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut) UIView.setAnimationTransition(UIViewAnimationTransition.CurlUp, forView: self.navigationController!.view, cache: false) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
Bartlebys/Bartleby
Bartleby.xOS/core/extensions/ManagedModel+ProvisionChanges.swift
1
5590
// // ManagedModel+ProvisionChanges.swift // BartlebyKit // // Created by Benoit Pereira da silva on 24/11/2016. // // import Foundation extension ManagedModel:ProvisionChanges{ /** The change provisionning is related to multiple essential notions. ## **Supervision** is a local mechanism used to determine if an object has changed. Properties that are declared `supervisable` provision their changes using this method. ## **Commit** is the first phase of the **distribution** mechanism (the second is Push, and the Third Trigger and integration on another node) If auto-commit is enabled on any supervised change an object is "staged" in its collection ## You can add **supervisers** to any ManagedModel. On supervised change the closure of the supervisers will be invoked. ## **Inspection** During debbuging or when Bartleby's inspector is opened we record and analyse the changes If Bartleby.inspectable we store in memory the changes changed Keys to allow Bartleby's runtime inspections (we use `KeyedChanges` objects) `provisionChanges` is the entry point of those mechanisms. - parameter key: the key - parameter oldValue: the oldValue - parameter newValue: the newValue */ open func provisionChanges(forKey key:String,oldValue:Any?,newValue:Any?){ // Invoke the closures (changes Observers) // note that it occurs even changes are not inspectable. for (_,supervisionClosure) in self._supervisers{ supervisionClosure(key,oldValue,newValue) } if self._autoCommitIsEnabled == true { self.collection?.stage(self) } // Changes propagation & Inspection // Propagate item changes to its collections if key=="*" && !(self is BartlebyCollection){ if self.isInspectable { // Dictionnary or NSData Patch self._appendChanges(key:key,changes:"\(type(of: self).typeName()) \(self.UID) has been patched") } self.collection?.provisionChanges(forKey: "item", oldValue: self, newValue: self) }else{ if let collection = self as? BartlebyCollection { if self.isInspectable { let entityName=Pluralization.singularize(collection.d_collectionName) if key=="_items"{ if let oldArray=oldValue as? [ManagedModel], let newArray=newValue as? [ManagedModel]{ if oldArray.count < newArray.count{ let stringValue:String! = (newArray.last?.UID ?? "") self._appendChanges(key:key,changes:"Added a new \(entityName) \(stringValue))") }else{ self._appendChanges(key:key,changes:"Removed One \(entityName)") } } } if key == "item" { if let o = newValue as? ManagedModel{ self._appendChanges(key:key,changes:"\(entityName) \(o.UID) has changed") }else{ self._appendChanges(key:key,changes:"\(entityName) has changed anomaly") } } if key == "*" { self._appendChanges(key:key,changes:"This collection has been patched") } } }else if let collectibleNewValue = newValue as? Collectible{ if self.isInspectable { // Collectible objects self._appendChanges(key:key,changes:"\(collectibleNewValue.runTimeTypeName()) \(collectibleNewValue.UID) has changed") } // Relay the as a global change to the collection self.collection?.provisionChanges(forKey: "item", oldValue: self, newValue: self) }else{ // Natives types let o = oldValue ?? "void" let n = newValue ?? "void" if self.isInspectable { self._appendChanges(key:key,changes:"\(o) ->\(n)") } // Relay the as a global change to the collection self.collection?.provisionChanges(forKey: "item", oldValue: self, newValue: self) } } } /// Performs the deserialization without invoking provisionChanges /// /// - parameter changes: the changes closure public func quietChanges(_ changes:()->()){ self._quietChanges=true changes() self._quietChanges=false } /// Performs the deserialization without invoking provisionChanges /// /// - parameter changes: the changes closure public func quietThrowingChanges(_ changes:()throws->())rethrows{ self._quietChanges=true try changes() self._quietChanges=false } // MARK : - public var wantsQuietChanges:Bool{ return self._quietChanges } /// **Inspection** /// Appends the change to the changedKey /// /// - parameter key: the key /// - parameter changes: the description of the changes private func _appendChanges(key:String,changes:String){ let kChanges=KeyedChanges() kChanges.key=key kChanges.changes=changes self.changedKeys.append(kChanges) } open func stage(){ self.collection?.stage(self) } }
apache-2.0
nofelmahmood/Seam
Example/SeamDemoTests/SeamDemoTests.swift
3
7446
// // SeamDemoTests.swift // SeamDemoTests // // Created by Nofel Mahmood on 12/08/2015. // Copyright © 2015 CloudKitSpace. All rights reserved. // import XCTest import CoreData @testable import SeamDemo class SeamDemoTests: 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 testStoreCreation() { let _ = CoreDataStack.defaultStack.managedObjectContext } func testDeletionOfTasks() { let fetchRequest = NSFetchRequest(entityName: "Task") fetchRequest.includesPropertyValues = false let result = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(result) let objects = result as? [Task] XCTAssertNotNil(objects) objects!.forEach({ CoreDataStack.defaultStack.managedObjectContext.deleteObject($0) }) let deletionResult = try? CoreDataStack.defaultStack.managedObjectContext.save() XCTAssertNotNil(deletionResult) } func testDeletionOfTags() { let fetchRequest = NSFetchRequest(entityName: "Tag") fetchRequest.includesPropertyValues = false let result = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(result) let objects = result as? [Tag] XCTAssertNotNil(objects) objects!.forEach({ print($0.name) CoreDataStack.defaultStack.managedObjectContext.deleteObject($0) }) XCTAssertNotNil(try? CoreDataStack.defaultStack.managedObjectContext.save()) } func testAddingOfObjects() { let task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: CoreDataStack.defaultStack.managedObjectContext) as! Task task.name = "Programming" let result = try? CoreDataStack.defaultStack.managedObjectContext.save() XCTAssertNotNil(result) let fetchRequest = NSFetchRequest(entityName: "Task") let fetchResult = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(fetchResult) let objects = fetchResult as? [Task] XCTAssertNotNil(objects) objects!.forEach({ XCTAssertNotNil($0.name) print($0.name) }) } func testUpdatingOfObjects() { let fetchRequest = NSFetchRequest(entityName: "Task") let result = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(result) let objects = result as? [Task] XCTAssertNotNil(objects) objects!.forEach({ XCTAssertNotNil($0.name) $0.name = "task name changed" }) let saveResult = try? CoreDataStack.defaultStack.managedObjectContext.save() XCTAssertNotNil(saveResult) } func testFetchingOfObjects() { let fetchRequest = NSFetchRequest(entityName: "Task") let result = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(result) let objects = result as? [Task] XCTAssertNotNil(objects) objects!.forEach({ XCTAssertNotNil($0.name) print($0.name!) }) } func testSettingRelationshipsUsingANewObject() { let tags = Tag.all(inContext: CoreDataStack.defaultStack.managedObjectContext) as? [Tag] let task = Task.new(inContext: CoreDataStack.defaultStack.managedObjectContext) as? Task task?.name = "NewTaskForSettingTags" XCTAssertNotNil(tags) XCTAssertNotNil(task) tags!.forEach { tag in tag.task = task! } XCTAssertNotNil(try? CoreDataStack.defaultStack.managedObjectContext.save()) } func testFetchingOfObjectsWithRelationships() { let fetchRequest = NSFetchRequest(entityName: "Task") let result = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(result) let objects = result as? [Task] XCTAssertNotNil(objects) objects!.forEach({ let tagName = ($0.tags?.allObjects.first as? Tag)?.name XCTAssertNotNil(tagName) print(tagName) }) } func testAddingObjectsAndRelationships() { let task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: CoreDataStack.defaultStack.managedObjectContext) as? Task XCTAssertNotNil(task) task!.name = "Test Task" let tag = NSEntityDescription.insertNewObjectForEntityForName("Tag", inManagedObjectContext: CoreDataStack.defaultStack.managedObjectContext) as? Tag XCTAssertNotNil(tag) tag!.name = "Tag for Test Task" var tags = task!.tags?.allObjects XCTAssertNotNil(tags) tags!.append(tag!) task!.tags = Set(tags as! [NSManagedObject]) let saveResult = try? CoreDataStack.defaultStack.managedObjectContext.save() XCTAssertNotNil(saveResult) CoreDataStack.defaultStack.managedObjectContext.reset() let fetchRequest = NSFetchRequest(entityName: "Task") let fetchResult = try? CoreDataStack.defaultStack.managedObjectContext.executeFetchRequest(fetchRequest) XCTAssertNotNil(fetchResult) let tasks = fetchResult as? [Task] XCTAssertNotNil(tasks) tasks!.forEach({ task in print("Task \(task.name!)") XCTAssertNotNil(task.tags) task.tags!.forEach({ tag in print("Tag \(tag.name!)") }) }) } func testFetchingOfTagAndSettingItToNewTask() { let tasks = Task.all(inContext: CoreDataStack.defaultStack.managedObjectContext) as? [Task] XCTAssertNotNil(tasks) let tags = Tag.all(inContext: CoreDataStack.defaultStack.managedObjectContext) as? [Tag] XCTAssertNotNil(tags) let newTask = Task.new(inContext: CoreDataStack.defaultStack.managedObjectContext) as? Task XCTAssertNotNil(newTask) newTask!.name = "Dagha Rora" print("OLD VALUES") tasks!.forEach({ task in print("\(task.name!)") XCTAssertNotNil(task.tags) task.tags!.forEach({ tag in print("\(tag.name!)") }) }) tags!.forEach({ tag in tag.task = newTask! }) let saveResult = try? CoreDataStack.defaultStack.managedObjectContext.save() XCTAssertNotNil(saveResult) CoreDataStack.defaultStack.managedObjectContext.reset() } func testAccessingOfToOneRelationship() { let tag = Tag.all(inContext: CoreDataStack.defaultStack.managedObjectContext)?.first as? Tag XCTAssertNotNil(tag) print(tag!.name!) print(tag!.task?.name) } func testAccessingOfToManyRelationship() { let task = Task.all(inContext: CoreDataStack.defaultStack.managedObjectContext, satisfyingPredicate: NSPredicate(format: "name = %@","Dagha Rora"))?.first as? Task print(task?.name) XCTAssertNotNil(task) XCTAssertNotNil(task?.tags) let tagsArray = task!.tags!.allObjects as? [Tag] XCTAssertNotNil(tagsArray) tagsArray!.forEach({ tag in XCTAssertNotNil(tag.name) print(tag.name) }) } 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
xwu/swift
test/ModuleInterface/modifiers.swift
6
3305
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule -emit-module-interface-path %t/Test.swiftinterface -module-name Test -disable-objc-attr-requires-foundation-module -enable-objc-interop %s // RUN: %FileCheck %s --check-prefix FROMSOURCE --check-prefix CHECK < %t/Test.swiftinterface // RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-module-interface-path - -module-name Test -enable-objc-interop | %FileCheck %s --check-prefix FROMMODULE --check-prefix CHECK // CHECK-LABEL: final public class FinalClass { public final class FinalClass { // CHECK: @inlinable final public class var a: Swift.Int { // FROMSOURCE-NEXT: {{^}} get { // FROMSOURCE-NEXT: return 3 // FROMSOURCE-NEXT: } // FROMMODULE-NEXT: get{{$}} // CHECK-NEXT: } @inlinable public final class var a: Int { return 3 } // CHECK: final public class var b: Swift.Int { // FROMSOURCE-NEXT: {{^}} @inlinable get { // FROMSOURCE-NEXT: return 3 // FROMSOURCE-NEXT: } // FROMMODULE-NEXT: {{^}} @inlinable get{{$}} // CHECK-NEXT: set[[NEWVALUE:(\(newValue\))?]]{{$}} // CHECK-NEXT: } public final class var b: Int { @inlinable get { return 3 } set { print("x") } } // CHECK: public static var c: Swift.Int { // CHECK-NEXT: {{^}} get // FROMSOURCE-NEXT: @inlinable set[[NEWVALUE]] {} // FROMMODULE-NEXT: @inlinable set[[NEWVALUE]]{{$}} // CHECK-NEXT: } public static var c: Int { get { return 0 } @inlinable set {} } // CHECK: @objc dynamic final public var d: Swift.Int { // CHECK-NEXT: {{^}} @objc get{{$}} // CHECK-NEXT: {{^}} @objc set[[NEWVALUE]]{{$}} // CHECK-NEXT: } @objc public dynamic var d: Int { get { return 0 } set {} } } // CHECK-LABEL: public class Base { public class Base { // CHECK-NEXT: @objc public init(){{$}} @objc public init() {} // CHECK-NEXT: @objc required public init(x: Swift.Int){{$}} @objc public required init(x: Int) {} // CHECK-NEXT: @objc deinit{{$}} } // CHECK-NEXT: {{^}$}} // CHECK-LABEL: public class SubImplicit : {{(Test[.])?Base}} { public class SubImplicit: Base { // CHECK-NEXT: @objc override public init(){{$}} // CHECK-NEXT: @objc required public init(x: Swift.Int){{$}} // CHECK-NEXT: @objc deinit{{$}} } // CHECK-NEXT: {{^}$}} // CHECK-LABEL: public class SubExplicit : {{(Test[.])?Base}} { public class SubExplicit: Base { // Make sure adding "required" preserves both "required" and "override". // CHECK-NEXT: @objc override required public init(){{$}} public override required init() { super.init() } // CHECK-NEXT: @objc required public init(x: Swift.Int){{$}} public required init(x: Int) { super.init() } // CHECK-NEXT: @objc deinit{{$}} } // CHECK-NEXT: {{^}$}} // CHECK-LABEL: public struct MyStruct { public struct MyStruct { // CHECK: public var e: Swift.Int { // CHECK-NEXT: {{^}} mutating get{{$}} // FROMSOURCE-NEXT: {{^}} @inlinable nonmutating set[[NEWVALUE]] {} // FROMMODULE-NEXT: {{^}} @inlinable nonmutating set[[NEWVALUE]]{{$}} // CHECK-NEXT: } public var e: Int { mutating get { return 0 } @inlinable nonmutating set {} } // CHECK-NEXT: } }
apache-2.0
Draveness/RbSwift
Sources/String+Inflections.swift
1
5370
// // Inflections.swift // SwiftPatch // // Created by draveness on 18/03/2017. // Copyright © 2017 draveness. All rights reserved. // import Foundation // MARK: - Inflections public extension String { /// An enum used to control the output of camelize as parameter /// /// - upper: Return the UppcaseCamelCase when specified /// - lower: Return the lowerCamelCase when specified public enum LetterCase { case upper case lower } /// By default, `camelize` converts strings to UpperCamelCase. /// /// "os_version".camelize #=> "OsVersion" /// "os_version_ten".camelize #=> "OsVersionTen" /// "os_version_TEn".camelize #=> "OsVersionTen" /// /// If the argument to camelize is set to `.lower` then camelize produces lowerCamelCase. /// /// "os_version".camelize(.lower) #=> "osVersion" /// /// - Parameter firstLetter: A flag to control result between UpperCamelCase(.upper) and lowerCamelCase(.lower), See also LetterCase /// - Returns: A string converts to camel case /// - SeeAlso: LetterCase func camelize(_ firstLetter: LetterCase = .upper) -> String { let source = gsub("[-_]", " ") if source.characters.contains(" ") { var first = source.substring(to: 1) first = firstLetter == .upper ? first.upcase : first.downcase let camel = source.capitalized.gsub(" ", "") let rest = String(camel.characters.dropFirst()) return "\(first)\(rest)" } else { var first = source.substring(to: 1) first = firstLetter == .upper ? first.upcase : first.downcase let rest = String(source.characters.dropFirst()) return "\(first)\(rest)" } } /// Creates a foreign key name from a class name. /// /// "people".foreignKey #=> "people_id" /// "people".foreignKey #=> "people_id" /// "MessageQueue".foreignKey #=> "message_queue_id" /// /// Separate flag sets whether the method should put '_' between the name and 'id'. /// /// "MessageQueue".foreignKey(false) #=> "message_queueid" /// /// - Parameter separate: A bool value sets whether the method should put '_' between the name and 'id' /// - Returns: A foreign key name string func foreignKey(_ separate: Bool = true) -> String { if separate { return underscore + "_id" } else { return underscore + "id" } } /// Converts strings to UpperCamelCase. /// /// "os_version".camelize #=> "OsVersion" /// "os_version_ten".camelize #=> "OsVersionTen" /// "os_version_TEn".camelize #=> "OsVersionTen" /// /// - See Also: `String#camelize(firstLetter:)` var camelize: String { return camelize() } /// Returns the plural form of the word in the string. var pluralize: String { return inflector.pluralize(string: self) } /// Returns the plural form of the word in the string. /// /// "person".pluralize #=> "people" /// "monkey".pluralize #=> "monkeys" /// "user".pluralize #=> "users" /// "man".pluralize #=> "men" /// /// If the parameter count is specified, the singular form will be returned if count == 1. /// /// "men".pluralize(1) #=> "man" /// /// For any other value of count the plural will be returned. /// /// - Parameter count: If specified, the singular form will be returned if count == 1 /// - Returns: A string in plural form of the word func pluralize(_ count: Int = 2) -> String { if count == 1 { return singularize } return pluralize } /// The reverse of `pluralize`, returns the singular form of a word in a string. /// /// "people".singularize #=> "person" /// "monkeys".singularize #=> "monkey" /// "users".singularize #=> "user" /// "men".singularize #=> "man" /// var singularize: String { return inflector.singularize(string: self) } /// The reverse of `camelize`. Makes an underscored, lowercase form from the expression in the string. /// /// "OsVersionTen".underscore #=> "os_version_ten" /// "osVersionTen".underscore #=> "os_version_ten" /// "osVerSionTen".underscore #=> "os_ver_sion_ten" /// var underscore: String { var word = self.gsub("([A-Z\\d]+)([A-Z][a-z])", "$1_$2") word.gsubed("([a-z\\d])([A-Z])", "$1_$2") // word.tr("-".freeze, "_".freeze) word.downcased() return word } /// Creates the name of a table. /// This method uses the `String#pluralize` method on the last word in the string. /// /// "RawScaledScorer".tableize #=> "raw_scaled_scorers" /// "egg_and_ham".tableize #=> "egg_and_hams" /// "fancyCategory".tableize #=> "fancy_categories" /// var tableize: String { return underscore.pluralize } /// Creates a foreign key name from a class name. /// /// "people".foreignKey #=> "people_id" /// "people".foreignKey #=> "people_id" /// "MessageQueue".foreignKey #=> "message_queue_id" /// var foreignKey: String { return foreignKey() } }
mit
DzinVision/weather-app
Weather App/AppDelegate.swift
1
714
// // AppDelegate.swift // Weather App // // Created by Vid Drobnič on 6/13/16. // Copyright © 2016 Vid Drobnic. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { DataGetter.sharedDataGetter.refresh() return true } func applicationDidEnterBackground(application: UIApplication) { DataGetter.sharedDataGetter.save() } func applicationWillEnterForeground(application: UIApplication) { DataGetter.sharedDataGetter.refresh() } }
mit
pietgk/EuropeanaApp
EuropeanaApp/ArtWhisperSwiftTests/BeaconMonitorOperationTest.swift
1
1313
// // BeaconMonitorOperationTest.swift // EuropeanaApp // // Created by W.J. Groot Kormelink on 05/11/15. // Copyright © 2015 Phluxus. All rights reserved. // import XCTest import EuropeanaApp class BeaconMonitorOperationTest: 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 testOperation() { // let exp = expectationWithDescription("testOperation") // // let queue = OperationQueue() // // let operation = BeaconMonitorOperation(); // // let observer = BlockObserver { _, errors in // exp.fulfill() // } // // operation.addObserver(observer) // queue.addOperation(operation) // // waitForExpectationsWithTimeout(2.0) { error in // exp.fulfill() // } // // } }
mit
dcunited001/SpectraNu
SpectraTests/MeshGenerators/RandomMeshGeneratorsSpec.swift
1
523
// // RandomMeshGenerators.swift // // // Created by David Conner on 3/5/16. // // @testable import Spectra import Quick import Nimble import Swinject class RandomMeshGeneratorsSpec: QuickSpec { func containerGet<T>(container: Container, key: String) -> T? { return container.resolve(T.self, name: key) } override func spec() { // read xsd // read xml // ... //TODO: describe("Random2DMeshGen") {} //TODO: describe("Random3DMeshGen") {} } }
mit
griotspeak/PathMath
Sources/PathMath/Font.swift
1
320
// // Font.swift // PathMath // // Created by TJ Usiyan on 20/2/11. // Copyright © 2020 Buttons and Lights LLC. All rights reserved. // import Foundation #if os(OSX) import AppKit public typealias PlatformFont = NSFont #endif #if os(iOS) import UIKit public typealias PlatformFont = UIFont #endif
mit
VigaasVentures/iOSWoocommerceClient
WoocommerceClient/models/CouponLine.swift
1
558
// // CouponLine.swift // WoocommerceClient // // Created by Damandeep Singh on 20/02/17. // Copyright © 2017 Damandeep Singh. All rights reserved. // import UIKit import ObjectMapper class CouponLine: Mappable { var id:Int? var code:String? var discount:String? var discountTax:String? public required init?(map: Map) { } public func mapping(map: Map) { id <- map["id"] code <- map["code"] discount <- map["discount"] discountTax <- map["discount_tax"] } }
mit
ReactiveX/RxSwift
RxTest/Schedulers/TestScheduler.swift
1
7463
// // TestScheduler.swift // RxTest // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /// Virtual time scheduler used for testing applications and libraries built using RxSwift. public class TestScheduler : VirtualTimeScheduler<TestSchedulerVirtualTimeConverter> { /// Default values of scheduler times. public struct Defaults { /// Default absolute time when to create tested observable sequence. public static let created = 100 /// Default absolute time when to subscribe to tested observable sequence. public static let subscribed = 200 /// Default absolute time when to dispose subscription to tested observable sequence. public static let disposed = 1000 } private let simulateProcessingDelay: Bool /** Creates a new test scheduler. - parameter initialClock: Initial value for the clock. - parameter resolution: Real time [NSTimeInterval] = ticks * resolution - parameter simulateProcessingDelay: When true, if something is scheduled right `now`, it will be scheduled to `now + 1` in virtual time. */ public init(initialClock: TestTime, resolution: Double = 1.0, simulateProcessingDelay: Bool = true) { self.simulateProcessingDelay = simulateProcessingDelay super.init(initialClock: initialClock, converter: TestSchedulerVirtualTimeConverter(resolution: resolution)) } /** Creates a hot observable using the specified timestamped events. - parameter events: Events to surface through the created sequence at their specified absolute virtual times. - returns: Hot observable sequence that can be used to assert the timing of subscriptions and events. */ public func createHotObservable<Element>(_ events: [Recorded<Event<Element>>]) -> TestableObservable<Element> { HotObservable(testScheduler: self as AnyObject as! TestScheduler, recordedEvents: events) } /** Creates a cold observable using the specified timestamped events. - parameter events: Events to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. - returns: Cold observable sequence that can be used to assert the timing of subscriptions and events. */ public func createColdObservable<Element>(_ events: [Recorded<Event<Element>>]) -> TestableObservable<Element> { ColdObservable(testScheduler: self as AnyObject as! TestScheduler, recordedEvents: events) } /** Creates an observer that records received events and timestamps those. - parameter type: Optional type hint of the observed sequence elements. - returns: Observer that can be used to assert the timing of events. */ public func createObserver<Element>(_ type: Element.Type) -> TestableObserver<Element> { TestableObserver(scheduler: self as AnyObject as! TestScheduler) } /** Schedules an action to be executed at the specified virtual time. - parameter time: Absolute virtual time at which to execute the action. */ public func scheduleAt(_ time: TestTime, action: @escaping () -> Void) { _ = self.scheduleAbsoluteVirtual((), time: time, action: { _ -> Disposable in action() return Disposables.create() }) } /** Adjusts time of scheduling before adding item to schedule queue. If scheduled time is `<= clock`, then it is scheduled at `clock + 1` */ override public func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { time <= self.clock ? self.clock + (self.simulateProcessingDelay ? 1 : 0) : time } /** Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. - parameter created: Virtual time at which to invoke the factory to create an observable sequence. - parameter subscribed: Virtual time at which to subscribe to the created observable sequence. - parameter disposed: Virtual time at which to dispose the subscription. - parameter create: Factory method to create an observable convertible sequence. - returns: Observer with timestamped recordings of events that were received during the virtual time window when the subscription to the source sequence was active. */ public func start<Element, OutputSequence: ObservableConvertibleType>(created: TestTime, subscribed: TestTime, disposed: TestTime, create: @escaping () -> OutputSequence) -> TestableObserver<Element> where OutputSequence.Element == Element { var source: Observable<Element>? var subscription: Disposable? let observer = self.createObserver(Element.self) _ = self.scheduleAbsoluteVirtual((), time: created) { _ in source = create().asObservable() return Disposables.create() } _ = self.scheduleAbsoluteVirtual((), time: subscribed) { _ in subscription = source!.subscribe(observer) return Disposables.create() } _ = self.scheduleAbsoluteVirtual((), time: disposed) { _ in subscription!.dispose() return Disposables.create() } self.start() return observer } /** Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. Observable sequence will be: * created at virtual time `Defaults.created` -> 100 * subscribed to at virtual time `Defaults.subscribed` -> 200 - parameter disposed: Virtual time at which to dispose the subscription. - parameter create: Factory method to create an observable convertible sequence. - returns: Observer with timestamped recordings of events that were received during the virtual time window when the subscription to the source sequence was active. */ public func start<Element, OutputSequence: ObservableConvertibleType>(disposed: TestTime, create: @escaping () -> OutputSequence) -> TestableObserver<Element> where OutputSequence.Element == Element { self.start(created: Defaults.created, subscribed: Defaults.subscribed, disposed: disposed, create: create) } /** Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. Observable sequence will be: * created at virtual time `Defaults.created` -> 100 * subscribed to at virtual time `Defaults.subscribed` -> 200 * subscription will be disposed at `Defaults.disposed` -> 1000 - parameter create: Factory method to create an observable convertible sequence. - returns: Observer with timestamped recordings of events that were received during the virtual time window when the subscription to the source sequence was active. */ public func start<Element, OutputSequence: ObservableConvertibleType>(_ create: @escaping () -> OutputSequence) -> TestableObserver<Element> where OutputSequence.Element == Element { self.start(created: Defaults.created, subscribed: Defaults.subscribed, disposed: Defaults.disposed, create: create) } }
mit
dankogai/swift-bignum
macOS.playground/Pages/Synopsis.xcplaygroundpage/Contents.swift
1
738
//: [Previous](@previous) import BigNum BigInt(+1).over(+2) BigInt(+1).over(-2) BigInt(-1).over(+2) BigInt(-1).over(-2) let q:BigRat = 1 let qpi = BigRat(Double.pi) BigRat.cos(4).asDouble qpi.asMixed (qpi % 1.0).asDouble BigRat.E(precision:128) BigRat.E(precision:-128) BigRat.E() BigRat(3, 1).sign BigRat(3, 1).exponent BigRat(3, 1).significand BigRat(-1, 3).sign BigRat(-1, 3).exponent BigRat(-1, 3).significand IntRat(-1, 3).sign IntRat(-1, 3).exponent IntRat(-1, 3).significand import Foundation let encoder = JSONEncoder() String(data:try encoder.encode(qpi), encoding:.utf8) String(data:try encoder.encode(IntRat(1).over(3)), encoding:.utf8) String(data:try encoder.encode([Int.max]), encoding:.utf8) //: [Next](@next)
mit
monisun/yowl
Yelp/FilterTitleCell.swift
1
1159
// // FilterTitleCell.swift // Yelp // // Created by Monica Sun on 5/16/15. // Copyright (c) 2015 Monica Sun. All rights reserved. // import UIKit @objc protocol FilterTitleCellDelegate { optional func filterTitleCell(filterTitleCell: FilterTitleCell, didChangeValue value: Int) } class FilterTitleCell: UITableViewCell { @IBOutlet weak var filterTitleLabel: UILabel! @IBOutlet weak var categorySegment: UISegmentedControl! weak var delegate: FilterTitleCellDelegate? override func awakeFromNib() { super.awakeFromNib() // default to food categorySegment.selectedSegmentIndex = 0 categorySegment.addTarget(self, action: "segmentValueChanged", forControlEvents: UIControlEvents.ValueChanged) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func segmentValueChanged() { println("segment value changed") delegate?.filterTitleCell?(self, didChangeValue: categorySegment.selectedSegmentIndex) } }
mit
raulriera/Bike-Compass
App/Carthage/Checkouts/Decodable/Sources/RawRepresentableDecodable.swift
1
943
// // RawRepresentableDecodable.swift // Decodable // // Created by Daniel Garbień on 06/11/15. // Copyright © 2015 anviking. All rights reserved. // /** * Extends all RawRepresentables (enums) which are also Decodable with decode implementation. * * I could not find a way to implicitly declare RawRepresentable conforming to Decodable, what would make all enums Decodable automatically. * Because of that for an enum to be compatible with Decodable operators it must be declared as implementing Decodable protocol. */ public extension RawRepresentable where RawValue: Decodable, Self: Decodable { static func decode(_ json: AnyObject) throws -> Self { let rawValue = try RawValue.decode(json) guard let rawRepresentable = Self(rawValue: rawValue) else { throw RawRepresentableInitializationError(type: self, rawValue: rawValue, object: json) } return rawRepresentable } }
mit
OneBestWay/EasyCode
iOS10/SpeechDemo/SpeechDemo/AppDelegate.swift
1
2161
// // AppDelegate.swift // SpeechDemo // // Created by GK on 2017/7/11. // Copyright © 2017年 GK. 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
milseman/swift
test/SILGen/casts.swift
14
3663
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class B { } class D : B { } // CHECK-LABEL: sil hidden @_T05casts6upcast{{[_0-9a-zA-Z]*}}F func upcast(d: D) -> B { // CHECK: {{%.*}} = upcast return d } // CHECK-LABEL: sil hidden @_T05casts8downcast{{[_0-9a-zA-Z]*}}F func downcast(b: B) -> D { // CHECK: {{%.*}} = unconditional_checked_cast return b as! D } // CHECK-LABEL: sil hidden @_T05casts3isa{{[_0-9a-zA-Z]*}}F func isa(b: B) -> Bool { // CHECK: bb0([[ARG:%.*]] : $B): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPIED_BORROWED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: checked_cast_br [[COPIED_BORROWED_ARG]] : $B to $D, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // // CHECK: [[YES]]([[CASTED_VALUE:%.*]] : $D): // CHECK: integer_literal {{.*}} -1 // CHECK: destroy_value [[CASTED_VALUE]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $B): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: integer_literal {{.*}} 0 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] return b is D } // CHECK-LABEL: sil hidden @_T05casts16upcast_archetype{{[_0-9a-zA-Z]*}}F func upcast_archetype<T : B>(t: T) -> B { // CHECK: {{%.*}} = upcast return t } // CHECK-LABEL: sil hidden @_T05casts25upcast_archetype_metatype{{[_0-9a-zA-Z]*}}F func upcast_archetype_metatype<T : B>(t: T.Type) -> B.Type { // CHECK: {{%.*}} = upcast return t } // CHECK-LABEL: sil hidden @_T05casts18downcast_archetype{{[_0-9a-zA-Z]*}}F func downcast_archetype<T : B>(b: B) -> T { // CHECK: {{%.*}} = unconditional_checked_cast return b as! T } // This is making sure that we do not have the default propagating behavior in // the address case. // // CHECK-LABEL: sil hidden @_T05casts12is_archetype{{[_0-9a-zA-Z]*}}F func is_archetype<T : B>(b: B, _: T) -> Bool { // CHECK: bb0([[ARG1:%.*]] : $B, [[ARG2:%.*]] : $T): // CHECK: checked_cast_br {{%.*}}, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]([[CASTED_ARG:%.*]] : $T): // CHECK: integer_literal {{.*}} -1 // CHECK: destroy_value [[CASTED_ARG]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : $B): // CHCEK: destroy_value [[CASTED_ARG]] // CHECK: integer_literal {{.*}} 0 return b is T } // CHECK: } // end sil function '_T05casts12is_archetype{{[_0-9a-zA-Z]*}}F' // CHECK: sil hidden @_T05casts20downcast_conditional{{[_0-9a-zA-Z]*}}F // CHECK: checked_cast_br {{%.*}} : $B to $D // CHECK: bb{{[0-9]+}}({{.*}} : $Optional<D>) func downcast_conditional(b: B) -> D? { return b as? D } protocol P {} struct S : P {} // CHECK: sil hidden @_T05casts32downcast_existential_conditional{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[IN:%.*]] : $*P): // CHECK: [[COPY:%.*]] = alloc_stack $P // CHECK: copy_addr [[IN]] to [initialization] [[COPY]] // CHECK: [[TMP:%.*]] = alloc_stack $S // CHECK: checked_cast_addr_br take_always P in [[COPY]] : $*P to S in [[TMP]] : $*S, bb1, bb2 // Success block. // CHECK: bb1: // CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*S // CHECK: [[T1:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, [[T0]] : $S // CHECK: dealloc_stack [[TMP]] // CHECK: br bb3([[T1]] : $Optional<S>) // Failure block. // CHECK: bb2: // CHECK: [[T0:%.*]] = enum $Optional<S>, #Optional.none!enumelt // CHECK: dealloc_stack [[TMP]] // CHECK: br bb3([[T0]] : $Optional<S>) // Continuation block. // CHECK: bb3([[RESULT:%.*]] : $Optional<S>): // CHECK: dealloc_stack [[COPY]] // CHECK: destroy_addr [[IN]] : $*P // CHECK: return [[RESULT]] func downcast_existential_conditional(p: P) -> S? { return p as? S }
apache-2.0
Aghassi/swift_learning
TableViewDemo/TableViewDemo/ViewController.swift
1
3339
// // ViewController.swift // TableViewDemo // // Created by David Aghassi on 5/18/15. // Copyright (c) 2015 David Aghassi. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { let devCourses = [ ("iOS App Dev with Swift Essential Training","Simon Allardice"), ("iOS 8 SDK New Features","Lee Brimelow"), ("Data Visualization with D3.js","Ray Villalobos"), ("Swift Essential Training","Simon Allardice"), ("Up and Running with AngularJS","Ray Villalobos"), ("MySQL Essential Training","Bill Weinman"), ("Building Adaptive Android Apps with Fragments","David Gassner"), ("Advanced Unity 3D Game Programming","Michael House"), ("Up and Running with Ubuntu Desktop Linux","Scott Simpson"), ("Up and Running with C","Dan Gookin") ] let webCourses = [ ("HTML Essential Training","James Williamson"), ("Building a Responsive Single-Page Design","Ray Villalobos"), ("Muse Essential Training","Justin Seeley"), ("WordPress Essential Training","Morten Rand-Hendriksen"), ("Installing and Running Joomla! 3: Local and Web-Hosted Sites","Jen Kramer"), ("Managing Records in SharePoint","Toni Saddler-French"), ("Design the Web: SVG Rollovers with CSS","Chris Converse"), ("Up and Running with Ember.js","Kai Gittens"), ("HTML5 Game Development with Phaser","Joseph Labrecque"), ("Responsive Media","Christopher Schmitt") ] func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return devCourses.count } else { return webCourses.count } } //Returns the contents of each row. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //Best paractice var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell if (indexPath == 0) { let (courseTitle, courseAuthor) = devCourses[indexPath.row] cell.textLabel?.text = courseTitle cell.detailTextLabel?.text = courseAuthor } else { let (courseTitle, courseAuthor) = devCourses[indexPath.row] cell.textLabel?.text = courseTitle cell.detailTextLabel?.text = courseAuthor } //Retrieve an image var image = UIImage(named: "Star") //Name from images.xcassets, case sensitive cell.imageView?.image = image return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return "Developer Courses" } else { return "Web Courses" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
tamilarasan08/ICare
iCare/iCare/SignUpViewController.swift
1
4349
// // LoginViewController.swift // iCare // // Created by Aishwarya on 09/12/15. // Copyright (c) 2015 Aishwarya. All rights reserved. // import UIKit class SignUpViewController: UIViewController ,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! var imageData:NSData! var imagePath:NSURL! @IBAction func uploadPhotoAction(sender: UIButton) { picker!.allowsEditing = false picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary presentViewController(picker!, animated: true, completion: nil) } var picker:UIImagePickerController?=UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() picker?.delegate=self } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var chosenImage = info[UIImagePickerControllerOriginalImage] as UIImage photoImageView.contentMode = .ScaleAspectFit photoImageView.image = chosenImage dismissViewControllerAnimated(true, completion: nil) imageData=UIImagePNGRepresentation(chosenImage) imagePath=info[UIImagePickerControllerReferenceURL] as NSURL } @IBAction func submitButtonAction(sender: UIButton) { var userName=userNameTextField.text; var password=passwordTextField.text; var confirmPassword=confirmPasswordTextField.text if(password==confirmPassword) { var nl:NetworkLayer=NetworkLayer() var returnData:NSData!=nl.connectToURL(signUpURL, postBody: ["name":userName,"password":password,"category":"user"], multipartFiles:[imagePath:imageData])// [String: String]())! var error:NSError? = nil if returnData != nil { if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(returnData, options: nil, error:&error) { if let dict = jsonObject as? NSDictionary { println(dict) var error_code: NSNumber?=dict.objectForKey("error_code") as? NSNumber var message:NSString=dict.objectForKey("error_message") as NSString; if (error_code?.integerValue==0) { println("show donator screen"); var userDonations:DonateViewController=DonateViewController() userDonations.username=userName self.navigationController!.pushViewController(userDonations, animated: true) } else { var alert:UIAlertView=UIAlertView(title: "Error", message:message , delegate: nil, cancelButtonTitle: "OK") alert.show() } } } else { println("Could not parse JSON: \(error!)") } } else { var alert:UIAlertView=UIAlertView(title: "Error", message: "Error while connecting to server", delegate: nil, cancelButtonTitle: "OK") alert.show() } } else { var alert:UIAlertView=UIAlertView(title: "Error", message: "The passwords do not match", delegate: nil, cancelButtonTitle: "OK") alert.show() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: NSSet, withEvent event: UIEvent?){ view.endEditing(true) super.touchesBegan(touches, withEvent: event!) } }
mit
llv22/wwdc2015
watchOS/216_layout_and_animation_techniques_for_watchkit/WKRecipes/WKRecipesUITests/WKRecipesUITests.swift
1
1070
// // WKRecipesUITests.swift // WKRecipesUITests // // Created by llv23 on 6/30/15. // Copyright © 2015 llv23. All rights reserved. // import Foundation import XCTest class WKRecipesUITests: 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() } 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. } }
apache-2.0
Alliants/ALAccordion
Example/ALAccordion Example/Views/Headers/ALRemovableHeaderView.swift
1
3069
// // ALRemovableHeaderView.swift // ALAccordion Example // // Created by Sam Williams on 14/02/2016. // Copyright © 2016 Alliants Ltd. All rights reserved. // import UIKit class ALRemovableHeaderView: UIView { // // MARK: - Properties // let topSeparator: ALSeparatorView = { let view = ALSeparatorView() view.separatorColor = UIColor.white.withAlphaComponent(0.5) view.translatesAutoresizingMaskIntoConstraints = false return view }() let bottomSeparator: ALSeparatorView = { let view = ALSeparatorView() view.separatorColor = UIColor.white.withAlphaComponent(0.5) view.translatesAutoresizingMaskIntoConstraints = false return view }() let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 17.0) label.textColor = UIColor.white label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false return label }() let closeButton: UIButton = { let button = UIButton(type: .system) button.tintColor = UIColor.white button.setTitle("X", for: UIControlState()) button.translatesAutoresizingMaskIntoConstraints = false return button }() // // MARK: - Initialisers // required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } override func awakeFromNib() { super.awakeFromNib() self.commonInit() } func commonInit() { // Create and setup views self.addSubview(self.topSeparator) self.addSubview(self.titleLabel) self.addSubview(self.bottomSeparator) self.addSubview(self.closeButton) // Setup constraints let views = ["topSeparator": self.topSeparator, "titleLabel": self.titleLabel, "bottomSeparator": self.bottomSeparator, "closeButton": self.closeButton] let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[topSeparator(1)]-(15)-[titleLabel]-(15)-[bottomSeparator(1)]|", options: [], metrics: nil, views: views) let horizontal_topSeparator = NSLayoutConstraint.constraints(withVisualFormat: "H:|[topSeparator]|", options: [], metrics: nil, views: views) let horizontal_titleLabel = NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[titleLabel]-15-[closeButton]-15-|", options: [], metrics: nil, views: views) let horizontal_bottomSeparator = NSLayoutConstraint.constraints(withVisualFormat: "H:|[bottomSeparator]|", options: [], metrics: nil, views: views) let closeCenterY = NSLayoutConstraint(item: self.closeButton, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0) self.addConstraints(vertical + horizontal_topSeparator + horizontal_titleLabel + horizontal_bottomSeparator + [closeCenterY]) } }
mit
sora0077/SimpleObserver
SimpleObserverTests/ObservingTests.swift
1
9257
// // ObservingTests.swift // SimpleObserver // // Created by 林達也 on 2015/02/11. // Copyright (c) 2015年 spika.co.jp. All rights reserved. // import UIKit import XCTest let when = { sec in dispatch_time(DISPATCH_TIME_NOW, Int64(sec * Double(NSEC_PER_SEC))) } extension XCTestCase { typealias DoneStatement = () -> Void func wait(till num: Int = 1, message: String = __FUNCTION__, _ block: (() -> Void) -> (() -> Void)) { self.wait(till: num, message: message, timeout: 1, block) } func wait(till num: Int, message: String = __FUNCTION__, timeout: NSTimeInterval, _ block: (() -> Void) -> (() -> Void)) { let expectation = self.expectationWithDescription(message) let queue = dispatch_queue_create("XCTestCase.wait", nil) var living = num var completion: (() -> Void)! let done: DoneStatement = { dispatch_async(queue) { //シングルキューで必ず順番に処理する living-- if living == 0 { completion?() expectation.fulfill() } } } completion = block(done) self.waitForExpectationsWithTimeout(timeout) { (error) -> Void in completion?() return } } } class MockObserver: NSObject { } class Hoge { var id: Int = 0 } class ObservingTests: 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 test_基本的な動作() { // This is an example of a functional test case. wait { done in var cnt = 0 let hoge = Observing(false, ==) let counter = { ++cnt } hoge.watch(self) { (e, _) in XCTAssertTrue(e.newValue, "") XCTAssertFalse(e.oldValue, "") XCTAssertEqual(1, counter(), "") done() } hoge.value = true return { XCTAssertEqual(1, cnt, "") } } } func test_基本的な動作_それぞれの呼び出し順序() { wait { done in var cnt = 0 let hoge = Observing(false, ==) let counter = { ++cnt } hoge.watch(self) { e in XCTAssertEqual(2, counter(), "") done() } hoge.value = true XCTAssertEqual(1, counter(), "") return { XCTAssertEqual(2, cnt, "") } } } func test_基本的な動作_複数での監視() { wait(till: 2) { done in var cnt = 0 let counter = { ++cnt } let hoge = Observing(false, ==) hoge.watch(self) { (e, _) in XCTAssertTrue(e.newValue, "") XCTAssertFalse(e.oldValue, "") XCTAssertEqual(2, counter(), "") done() } hoge.watch(self) { (e, _) in XCTAssertTrue(e.newValue, "") XCTAssertFalse(e.oldValue, "") XCTAssertEqual(1, counter(), "") done() } hoge.value = true return { XCTAssertEqual(2, cnt, "") } } } func test_デフォルトキューの設定() { let hoge = Observing(false, ==) XCTAssertEqual(hoge.default_queue, dispatch_get_main_queue(), "") let queue = dispatch_queue_create("", nil) let fuga = Observing(false, ==, queue: queue) XCTAssertEqual(fuga.default_queue, queue, "") } func test_unwatchされたら通知されない() { var cnt = 0 let counter = { ++cnt } let hoge = Observing(false, ==) wait { done in hoge.watch(self) { _ in counter() done() } dispatch_after(when(0.5), dispatch_get_main_queue()) { done() } hoge.unwatch(self) hoge.value = true return { XCTAssertEqual(0, cnt, "") } } } func test_Arrayを監視() { var cnt = 0 let counter = { ++cnt } let hoge = Observing<NSArray>([1], ==) wait { done in hoge.watch(self) { (e, _) in XCTAssertEqual([1], e.oldValue, "") XCTAssertEqual([2, 1], e.newValue, "") counter() done() } hoge.value = [2, 1] return { XCTAssertEqual(1, cnt, "") } } } func test_Arrayに独自クラスを入れた場合() { var cnt = 0 let counter = { ++cnt } let hoge = Observing<NSArray>([Hoge()], ==) wait { done in hoge.watch(self) { (e, _) in XCTAssertEqual(0, (e.newValue[0] as! Hoge).id, "") counter() done() } hoge.value = [Hoge(), Hoge()] return { XCTAssertEqual(1, cnt, "") } } } func test_配列の中身が同じ場合呼び出されない() { var cnt = 0 let counter = { ++cnt } let expected = Hoge() let hoge = Observing<NSArray>([expected], ==) wait { done in hoge.watch(self) { (e, _) in XCTAssertEqual([expected], e.oldValue, "") counter() } hoge.value = [expected] done() return { XCTAssertEqual(0, cnt, "") } } } func test_基本的な動作_変更を複数回行う() { wait(till: 2) { done in var cnt = 0 let counter = { ++cnt } let hoge = Observing(false, ==) var expected: Bool = true var call_1st = false var call_2nd = false let queue = dispatch_queue_create("", nil) hoge.watch(self, queue) { (e, _) in switch counter() { case 1: XCTAssertEqual(true, e.newValue, "") XCTAssertEqual(false, e.oldValue, "") call_1st = true done() case 2: XCTAssertEqual(false, e.newValue, "") XCTAssertEqual(true, e.oldValue, "") call_2nd = true done() default: break } } hoge.value = expected expected = !expected hoge.value = expected expected = !expected return { XCTAssertEqual(false, hoge.value, "") XCTAssertEqual(2, cnt, "") XCTAssertTrue(call_1st, "") XCTAssertTrue(call_2nd, "") } } } func test_正常な呼び出し回数_監視対象のオブジェクトがクリアされた時は呼び出されない() { wait { done in var cnt = 0 let hoge = Observing(false, ==) let counter = { ++cnt } autoreleasepool { let mock = MockObserver() hoge.watch(mock) { (e, o) in XCTAssertNotNil(o.description, "") XCTAssertFalse(true, "") counter() } hoge.watch(mock) { _ in XCTAssertFalse(true, "") counter() } } hoge.watch(self) { vv in XCTAssertEqual(1, counter(), "") done() } XCTAssertEqual(3, hoge.observers.count, "") hoge.value = true XCTAssertEqual(0, cnt, "インクリメント前") XCTAssertEqual(1, hoge.observers.count, "") return { XCTAssertEqual(1, cnt, "cntは一回のみ") } } } }
mit
dirk/Roost
Roost/Roostfile/TestTarget.swift
1
97
import Foundation extension Roostfile { class TestTarget { var sources = [String]() } }
bsd-3-clause
Electrode-iOS/ELHybridWeb
Source/JS API/HybridAPI+Logging.swift
2
399
// // HybridAPI+Logging.swift // ELHybridWeb // // Created by Angelo Di Paolo on 5/11/15. // Copyright (c) 2015 WalmartLabs. All rights reserved. // import Foundation import JavaScriptCore @objc protocol HybridLoggingJSExport: JSExport { func log(_ value: AnyObject) } extension HybridAPI { func log(_ value: AnyObject) { ELHybridWeb.log(.info, "HybridAPI: \(value)") } }
mit
danielloureda/congenial-sniffle
Project12/Project10/ViewController.swift
1
3617
// // ViewController.swift // Project10 // // Created by Daniel Loureda Arteaga on 13/6/17. // Copyright © 2017 Dano. All rights reserved. // import UIKit class ViewController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var people = [Person]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewPerson)) let defaults = UserDefaults.standard if let savedPeople = defaults.object(forKey: "people") as? Data { people = NSKeyedUnarchiver.unarchiveObject(with: savedPeople) as! [Person] } } func addNewPerson(){ let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self present(picker, animated: true) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return people.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Person", for: indexPath) as! PersonCell let path = getDocumentsDirectory().appendingPathComponent(people[indexPath.row].image) cell.name.text = people[indexPath.row].name cell.imageView.image = UIImage(contentsOfFile: path.path) cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor cell.imageView.layer.borderWidth = 2 cell.imageView.layer.cornerRadius = 3 cell.layer.cornerRadius = 7 return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let alert = UIAlertController(title: "Who is?", message: "Please, enter the name", preferredStyle: .alert) alert.addTextField() alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) alert.addAction(UIAlertAction(title: "Save", style: .default, handler: { [unowned self, alert] _ in let person = self.people[indexPath.row] let newName = alert.textFields![0] person.name = newName.text! self.collectionView?.reloadData() self.save() })) present(alert, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return } let imageName = UUID().uuidString let imagePath = getDocumentsDirectory().appendingPathComponent(imageName) if let jpegData = UIImageJPEGRepresentation(image, 80) { try? jpegData.write(to: imagePath) } let person = Person(name: "Unknown", image: imageName) people.append(person) collectionView?.reloadData() dismiss(animated: true) self.save() } func getDocumentsDirectory() -> URL{ let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } func save() { let savedData = NSKeyedArchiver.archivedData(withRootObject: people) let defaults = UserDefaults.standard defaults.set(savedData, forKey: "people") } }
apache-2.0
dirk/Roost
Roost/Package.Module.swift
1
528
import Foundation extension Package { class Module { var module: Roostfile.Module var parent: Package var sourceFiles: [String] = [] var lastModificationDate: NSDate = NSDate() var name: String { get { return module.name } } init(_ m: Roostfile.Module, parent p: Package) { module = m parent = p sourceFiles = parent.scanSourcesDirectories(module.sources) lastModificationDate = parent.computeLastModificationDate(sourceFiles) } }// class Module }
bsd-3-clause
sora0077/Nata
NataTests/DefaultNamespaceXPathTests.swift
1
2097
// // DefaultNamespaceXPathTests.swift // Nata // // Created by 林達也 on 2015/12/31. // Copyright © 2015年 jp.sora0077. All rights reserved. // import XCTest import Nata class DefaultNamespaceXPathTests: XCTestCase { private var document: XMLDocument! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. let filePath = NSBundle(forClass: self.dynamicType).pathForResource("ocf", ofType: "xml") document = try? XMLDocument(data: NSData(contentsOfFile: filePath!)!) XCTAssertNotNil(document, "Document should not be nil") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAbsoluteXPathWithDefaultNamespace() { document.definePrefix("ocf", forDefaultNamespace: "urn:oasis:names:tc:opendocument:xmlns:container") let XPath = "/ocf:container/ocf:rootfiles/ocf:rootfile" var count = 0 for element in document.XPath(XPath) { XCTAssertEqual("rootfile", element.tag, "tag should be `rootfile`") count += 1 } XCTAssertEqual(1, count, "Element should be found at XPath '\(XPath)'") } func testRelativeXPathWithDefaultNamespace() { document.definePrefix("ocf", forDefaultNamespace: "urn:oasis:names:tc:opendocument:xmlns:container") let absoluteXPath = "/ocf:container/ocf:rootfiles" let relativeXPath = "./ocf:rootfile" var count = 0 for absoluteElement in document.XPath(absoluteXPath) { for relativeElement in absoluteElement.XPath(relativeXPath) { XCTAssertEqual("rootfile", relativeElement.tag, "tag should be `rootfile`") count += 1 } } XCTAssertEqual(1, count, "Element should be found at XPath '\(relativeXPath)' relative to XPath '\(absoluteXPath)'") } }
mit
AcerFeng/SwiftProject
PlayLocalVideo/PlayLocalVideoUITests/PlayLocalVideoUITests.swift
1
1261
// // PlayLocalVideoUITests.swift // PlayLocalVideoUITests // // Created by lanfeng on 16/11/14. // Copyright © 2016年 lanfeng. All rights reserved. // import XCTest class PlayLocalVideoUITests: 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. } }
apache-2.0
johndpope/ClangWrapper.Swift
ClangWrapper/CXXAccessSpecifier.swift
1
1383
// // CXXAccessSpecifier.swift // ClangWrapper // // Created by Hoon H. on 2015/01/21. // Copyright (c) 2015 Eonil. All rights reserved. // public enum CXXAccessSpecifier { case InvalidAccessSpecifier case Public case Protected case Private } extension CXXAccessSpecifier: Printable { public var description:String { get { switch self { case .InvalidAccessSpecifier: return "InvalidAccessSpecifier" case .Public: return "Public" case .Protected: return "Protected" case .Private: return "Private" } } } } internal extension CXXAccessSpecifier { init(raw: CX_CXXAccessSpecifier) { self = select(raw) } var raw:CX_CXXAccessSpecifier { get { switch self { case InvalidAccessSpecifier: return CX_CXXInvalidAccessSpecifier case Public: return CX_CXXPublic case Protected: return CX_CXXProtected case Private: return CX_CXXPrivate } } } } private func select(v:CX_CXXAccessSpecifier) -> CXXAccessSpecifier { switch v.value { case CX_CXXInvalidAccessSpecifier.value: return CXXAccessSpecifier.InvalidAccessSpecifier case CX_CXXPublic.value: return CXXAccessSpecifier.Public case CX_CXXProtected.value: return CXXAccessSpecifier.Protected case CX_CXXPrivate.value: return CXXAccessSpecifier.Private default: fatalError("Unknown value for `CX_CXXAccessSpecifier` enum.") } }
mit
tad-iizuka/swift-sdk
Source/SpeechToTextV1/SpeechToTextSocket.swift
3
9676
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit internal class SpeechToTextSocket: WebSocketDelegate { private(set) internal var results = SpeechRecognitionResults() private(set) internal var state: SpeechToTextState = .Disconnected internal var onConnect: ((Void) -> Void)? = nil internal var onListening: ((Void) -> Void)? = nil internal var onResults: ((SpeechRecognitionResults) -> Void)? = nil internal var onError: ((Error) -> Void)? = nil internal var onDisconnect: ((Void) -> Void)? = nil private let socket: WebSocket private let queue = OperationQueue() private let restToken: RestToken private var tokenRefreshes = 0 private let maxTokenRefreshes = 1 private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1" internal init( username: String, password: String, model: String?, customizationID: String?, learningOptOut: Bool?, serviceURL: String, tokenURL: String, websocketsURL: String, defaultHeaders: [String: String]) { // initialize authentication token let tokenURL = tokenURL + "?url=" + serviceURL restToken = RestToken(tokenURL: tokenURL, username: username, password: password) // build url with options let url = SpeechToTextSocket.buildURL( url: websocketsURL, model: model, customizationID: customizationID, learningOptOut: learningOptOut )! // initialize socket socket = WebSocket(url: url) socket.delegate = self // set default headers for (key, value) in defaultHeaders { socket.headers[key] = value } // configure operation queue queue.maxConcurrentOperationCount = 1 queue.isSuspended = true } internal func connect() { // ensure the socket is not already connected guard state == .Disconnected || state == .Connecting else { return } // flush operation queue if state == .Disconnected { queue.cancelAllOperations() } // update state state = .Connecting // restrict the number of retries guard tokenRefreshes <= maxTokenRefreshes else { let failureReason = "Invalid HTTP upgrade. Check credentials?" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "WebSocket", code: 400, userInfo: userInfo) onError?(error) return } // refresh token, if necessary guard let token = restToken.token else { restToken.refreshToken(failure: onError) { self.tokenRefreshes += 1 self.connect() } return } // connect with token socket.headers["X-Watson-Authorization-Token"] = token socket.headers["User-Agent"] = RestRequest.userAgent socket.connect() } internal func writeStart(settings: RecognitionSettings) { guard state != .Disconnected else { return } guard let start = try? settings.toJSON().serializeString() else { return } queue.addOperation { self.socket.write(string: start) self.results = SpeechRecognitionResults() if self.state != .Disconnected { self.state = .Listening self.onListening?() } } } internal func writeAudio(audio: Data) { guard state != .Disconnected else { return } queue.addOperation { self.socket.write(data: audio) if self.state == .Listening { self.state = .SentAudio } } } internal func writeStop() { guard state != .Disconnected else { return } guard let stop = try? RecognitionStop().toJSON().serializeString() else { return } queue.addOperation { self.socket.write(string: stop) } } internal func writeNop() { guard state != .Disconnected else { return } let nop = "{\"action\": \"no-op\"}" queue.addOperation { self.socket.write(string: nop) } } internal func waitForResults() { queue.addOperation { switch self.state { case .Connecting, .Connected, .Listening, .Disconnected: return // no results to wait for case .SentAudio, .Transcribing: self.queue.isSuspended = true let onListeningCache = self.onListening self.onListening = { self.onListening = onListeningCache self.queue.isSuspended = false } } } } internal func disconnect(forceTimeout: TimeInterval? = nil) { queue.addOperation { self.queue.isSuspended = true self.queue.cancelAllOperations() self.socket.disconnect(forceTimeout: forceTimeout) } } private static func buildURL(url: String, model: String?, customizationID: String?, learningOptOut: Bool?) -> URL? { var queryParameters = [URLQueryItem]() if let model = model { queryParameters.append(URLQueryItem(name: "model", value: model)) } if let customizationID = customizationID { queryParameters.append(URLQueryItem(name: "customization_id", value: customizationID)) } if let learningOptOut = learningOptOut { let value = "\(learningOptOut)" queryParameters.append(URLQueryItem(name: "x-watson-learning-opt-out", value: value)) } var urlComponents = URLComponents(string: url) urlComponents?.queryItems = queryParameters return urlComponents?.url } private func onStateMessage(state: RecognitionState) { if state.state == "listening" && self.state == .Transcribing { self.state = .Listening onListening?() } } private func onResultsMessage(wrapper: SpeechRecognitionEvent) { state = .Transcribing results.addResults(wrapper: wrapper) onResults?(results) } private func onErrorMessage(error: String) { let failureReason = error let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: domain, code: 0, userInfo: userInfo) onError?(error) } private func isAuthenticationFailure(error: Error) -> Bool { let error = error as NSError guard let description = error.userInfo[NSLocalizedDescriptionKey] as? String else { return false } let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 400) let matchesDescription = (description == "Invalid HTTP upgrade") if matchesDomain && matchesCode && matchesDescription { return true } return false } private func isNormalDisconnect(error: Error) -> Bool { let error = error as NSError let matchesDomain = (error.domain == "WebSocket") let matchesCode = (error.code == 1000) if matchesDomain && matchesCode { return true } return false } internal func websocketDidConnect(socket: WebSocket) { state = .Connected tokenRefreshes = 0 queue.isSuspended = false results = SpeechRecognitionResults() onConnect?() } internal func websocketDidReceiveData(socket: WebSocket, data: Data) { return // should not receive any binary data from the service } internal func websocketDidReceiveMessage(socket: WebSocket, text: String) { guard let json = try? JSON(string: text) else { return } if let state = try? json.decode(type: RecognitionState.self) { onStateMessage(state: state) } if let results = try? json.decode(type: SpeechRecognitionEvent.self) { onResultsMessage(wrapper: results) } if let error = try? json.getString(at: "error") { onErrorMessage(error: error) } } internal func websocketDidDisconnect(socket: WebSocket, error: NSError?) { state = .Disconnected queue.isSuspended = true guard let error = error else { onDisconnect?() return } if isNormalDisconnect(error: error) { onDisconnect?() return } if isAuthenticationFailure(error: error) { restToken.refreshToken(failure: onError) { self.tokenRefreshes += 1 self.connect() } return } onError?(error) onDisconnect?() } }
apache-2.0
TonnyTao/Acornote
Acornote_iOS/Pods/Cache/Source/iOS/UIImage+Extensions.swift
1
662
import UIKit /// Helper UIImage extension. extension UIImage { /// Checks if image has alpha component var hasAlpha: Bool { let result: Bool guard let alpha = cgImage?.alphaInfo else { return false } switch alpha { case .none, .noneSkipFirst, .noneSkipLast: result = false default: result = true } return result } /// Convert to data func cache_toData() -> Data? { #if swift(>=4.2) return hasAlpha ? pngData() : jpegData(compressionQuality: 1.0) #else return hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, 1.0) #endif } }
apache-2.0
gnatsel/GRCoreDataUtilsSwift
SampleGRCoreDataUtils/SampleGRCoreDataUtils/models/entities/User.swift
1
348
// // User.swift // SampleGRCoreDataUtils // // Created by Gnatsel Revilo on 17/08/2015. // Copyright (c) 2015 Gnatsel Reivilo. All rights reserved. // import Foundation import CoreData @objc(User) class User: NSManagedObject { @NSManaged var firstname: String? @NSManaged var lastname: String? @NSManaged var userId: String? }
mit
ryanseys/h2o
h2oTests/h2oTests.swift
1
874
// // h2oTests.swift // h2oTests // // Created by Ryan Seys on 2014-07-03. // Copyright (c) 2014 Ryan Seys. All rights reserved. // import XCTest class h2oTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
nathawes/swift
test/IRGen/autolink-runtime-compatibility.swift
7
3308
// REQUIRES: OS=macosx,CPU=x86_64 // Doesn't autolink compatibility library because autolinking is disabled // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -target %target-cpu-apple-macosx10.9 -disable-autolinking-runtime-compatibility -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version 5.0 -disable-autolinking-runtime-compatibility -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because runtime compatibility library is disabled // RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because target OS doesn't need it // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Only autolinks 5.1 compatibility library because target OS has 5.1 // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.15 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // Autolinks because compatibility library was explicitly asked for // RUN: %target-swift-frontend -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.24 -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s public func foo() {} // NO-FORCE-LOAD-NOT: FORCE_LOAD // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility50"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility51"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibilityDynamicReplacements"} // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility50"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibility51"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibilityDynamicReplacements"} // FORCE-LOAD-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility51" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility51"} // FORCE-LOAD-51-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements"
apache-2.0
sschiau/swift
stdlib/public/Darwin/Accelerate/vDSP_Reduction.swift
8
20114
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Maximum /// Returns vector maximum value; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The maximum value in `vector`. @inlinable public static func maximum<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_maxv(v.baseAddress!, 1, &output, n) } return output } /// Returns vector maximum value; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The maximum value in `vector`. @inlinable public static func maximum<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_maxvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Maximum magnitude /// Returns vector maximum magnitude; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The maximum magnitude in `vector`. @inlinable public static func maximumMagnitude<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_maxmgv(v.baseAddress!, 1, &output, n) } return output } /// Returns vector maximum magnitude; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: The maximum magnitude in `vector`. @inlinable public static func maximumMagnitude<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_maxmgvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Minimum /// Returns vector minimum value; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The minimum value in `vector`. @inlinable public static func minimum<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_minv(v.baseAddress!, 1, &output, n) } return output } /// Returns vector minimum value; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The minimum value in `vector`. @inlinable public static func minimum<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_minvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Summation /// Returns vector sum; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of values in `vector`. @inlinable public static func sum<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_sve(v.baseAddress!, 1, &output, n) } return output } /// Returns vector sum; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of values in `vector`. @inlinable public static func sum<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_sveD(v.baseAddress!, 1, &output, n) } return output } /// Returns vector sum of squares; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of squares in `vector`. @inlinable public static func sumOfSquares<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_svesq(v.baseAddress!, 1, &output, n) } return output } /// Returns vector sum of squares; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of squares in `vector`. @inlinable public static func sumOfSquares<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_svesqD(v.baseAddress!, 1, &output, n) } return output } /// Returns sum of elements and sum of elements' squares; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of values and the sum of squares in `vector`. @inlinable public static func sumAndSumOfSquares<U>(_ vector: U) -> (elementsSum: Float, squaresSum: Float) where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var sum = Float.nan var sumOfSquares = Float.nan vector.withUnsafeBufferPointer { v in vDSP_sve_svesq(v.baseAddress!, 1, &sum, &sumOfSquares, n) } return (elementsSum: sum, squaresSum: sumOfSquares) } /// Returns sum of elements and sum of elements' squares; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of values and the sum of squares in `vector`. @inlinable public static func sumAndSumOfSquares<U>(_ vector: U) -> (elementsSum: Double, squaresSum: Double) where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var sum = Double.nan var sumOfSquares = Double.nan vector.withUnsafeBufferPointer { v in vDSP_sve_svesqD(v.baseAddress!, 1, &sum, &sumOfSquares, n) } return (elementsSum: sum, squaresSum: sumOfSquares) } /// Returns vector sum of magnitudes; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of magnitudes in `vector`. @inlinable public static func sumOfMagnitudes<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_svemg(v.baseAddress!, 1, &output, n) } return output } /// Returns vector sum of magnitudes; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: The sum of magnitudes in `vector`. @inlinable public static func sumOfMagnitudes<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_svemgD(v.baseAddress!, 1, &output, n) } return output } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Maximum with index /// Returns vector maximum with index; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the maximum value and its index. @inlinable public static func indexOfMaximum<U>(_ vector: U) -> (UInt, Float) where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_maxvi(v.baseAddress!, 1, &output, &index, n) } return (index, output) } /// Returns vector maximum with index; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the maximum value and its index. @inlinable public static func indexOfMaximum<U>(_ vector: U) -> (UInt, Double) where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_maxviD(v.baseAddress!, 1, &output, &index, n) } return (index, output) } // MARK: Maximum magnitude with index /// Returns vector maximum magnitude with index; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the maximum magnitude and its index. @inlinable public static func indexOfMaximumMagnitude<U>(_ vector: U) -> (UInt, Float) where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_maxmgvi(v.baseAddress!, 1, &output, &index, n) } return (index, output) } /// Returns vector maximum magnitude with index; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the maximum magnitude and its index. @inlinable public static func indexOfMaximumMagnitude<U>(_ vector: U) -> (UInt, Double) where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_maxmgviD(v.baseAddress!, 1, &output, &index, n) } return (index, output) } // MARK: Minimum with index /// Returns vector minimum with index; single-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the minimum value and its index. @inlinable public static func indexOfMinimum<U>(_ vector: U) -> (UInt, Float) where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_minvi(v.baseAddress!, 1, &output, &index, n) } return (index, output) } /// Returns vector minimum with index; double-precision. /// /// - Parameter vector: The input vector. /// - Returns: A tuple containing the minimum value and its index. @inlinable public static func indexOfMinimum<U>(_ vector: U) -> (UInt, Double) where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan var index: vDSP_Length = 0 vector.withUnsafeBufferPointer { v in vDSP_minviD(v.baseAddress!, 1, &output, &index, n) } return (index, output) } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Mean Square (vDSP_measqv) /// Returns the mean square of the supplied single-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func meanSquare<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_measqv(v.baseAddress!, 1, &output, n) } return output } /// Returns the mean square of the supplied double-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func meanSquare<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_measqvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Mean Magnitude /// Returns the mean magnitude of the supplied single-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func meanMagnitude<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_meamgv(v.baseAddress!, 1, &output, n) } return output } /// Returns the mean magnitude of the supplied double-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func meanMagnitude<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_meamgvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Mean /// Returns the mean magnitude of the supplied single-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func mean<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_meanv(v.baseAddress!, 1, &output, n) } return output } /// Returns the mean of the supplied double-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func mean<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_meanvD(v.baseAddress!, 1, &output, n) } return output } // MARK: Root Mean Square /// Returns the root-mean-square of the supplied single-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func rootMeanSquare<U>(_ vector: U) -> Float where U: AccelerateBuffer, U.Element == Float { let n = vDSP_Length(vector.count) var output = Float.nan vector.withUnsafeBufferPointer { v in vDSP_rmsqv(v.baseAddress!, 1, &output, n) } return output } /// Returns the root-mean-square of the supplied double-precision vector. /// /// - Parameter vector: The input vector. @inlinable public static func rootMeanSquare<U>(_ vector: U) -> Double where U: AccelerateBuffer, U.Element == Double { let n = vDSP_Length(vector.count) var output = Double.nan vector.withUnsafeBufferPointer { v in vDSP_rmsqvD(v.baseAddress!, 1, &output, n) } return output } }
apache-2.0
sschiau/swift
stdlib/public/Darwin/Foundation/NSStringAPI.swift
2
77974
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Important Note // ============== // // This file is shared between two projects: // // 1. https://github.com/apple/swift/tree/master/stdlib/public/Darwin/Foundation // 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation // // If you change this file, you must update it in both places. #if !DEPLOYMENT_RUNTIME_SWIFT @_exported import Foundation // Clang module #endif // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } #if !DEPLOYMENT_RUNTIME_SWIFT // We only need this for UnsafeMutablePointer, but there's not currently a way // to write that constraint. extension Optional { /// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the /// address of `object` to `body`. /// /// This is intended for use with Foundation APIs that return an Objective-C /// type via out-parameter where it is important to be able to *ignore* that /// parameter by passing `nil`. (For some APIs, this may allow the /// implementation to avoid some work.) /// /// In most cases it would be simpler to just write this code inline, but if /// `body` is complicated than that results in unnecessarily repeated code. internal func _withNilOrAddress<NSType : AnyObject, ResultType>( of object: inout NSType?, _ body: (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } #endif /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. internal func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let cString = p else { return nil } let len = UTF8._nullCodeUnitOffset(in: cString) var result = [CChar](repeating: 0, count: len + 1) for i in 0..<len { result[i] = cString[i] } return result } extension String { //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// An array of the encodings that strings support in the application's /// environment. public static var availableStringEncodings: [Encoding] { var result = [Encoding]() var p = NSString.availableStringEncodings while p.pointee != 0 { result.append(Encoding(rawValue: p.pointee)) p += 1 } return result } // @property (class) NSStringEncoding defaultCStringEncoding; /// The C-string encoding assumed for any method accepting a C string as an /// argument. public static var defaultCStringEncoding: Encoding { return Encoding(rawValue: NSString.defaultCStringEncoding) } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of the specified encoding. /// /// - Parameter encoding: A string encoding. For possible values, see /// `String.Encoding`. /// - Returns: A human-readable string giving the name of `encoding` in the /// current locale. public static func localizedName( of encoding: Encoding ) -> String { return NSString.localizedName(of: encoding.rawValue) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. public static func localizedStringWithFormat( _ format: String, _ arguments: CVarArg... ) -> String { return String(format: format, locale: Locale.current, arguments: arguments) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Creates a string by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let str = String(validatingUTF8: bytes) { self = str return } if let ns = NSString(utf8String: bytes) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } } extension String { //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Creates a new string equivalent to the given bytes interpreted in the /// specified encoding. /// /// - Parameters: /// - bytes: A sequence of bytes to interpret using `encoding`. /// - encoding: The ecoding to use to interpret `bytes`. public init?<S: Sequence>(bytes: __shared S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if encoding == .utf8, let str = byteArray.withUnsafeBufferPointer({ String._tryFromUTF8($0) }) { self = str return } if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of bytes from the /// given buffer, interpreted in the specified encoding, and optionally /// frees the buffer. /// /// - Warning: This initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Creates a new string that contains the specified number of characters /// from the given C array of Unicode characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count)) } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of characters /// from the given C array of UTF-16 code units. public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = String._unconditionallyBridgeFromObjectiveC(NSString( charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)) } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: __shared String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: __shared String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOfFile path: __shared String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOf url: __shared URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOf url: __shared URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOf url: __shared URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( cString: UnsafePointer<CChar>, encoding enc: Encoding ) { if enc == .utf8, let str = String(validatingUTF8: cString) { self = str return } if let ns = NSString(cString: cString, encoding: enc.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: __shared Data, encoding: Encoding) { if encoding == .utf8, let str = data.withUnsafeBytes({ String._tryFromUTF8($0.bindMemory(to: UInt8.self)) }) { self = str return } guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = String._unconditionallyBridgeFromObjectiveC(s) } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: __shared String, _ arguments: CVarArg...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user's default locale. public init(format: __shared String, arguments: __shared [CVarArg]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, _ args: CVarArg...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: __shared String, locale: __shared Locale?, arguments: __shared [CVarArg]) { #if DEPLOYMENT_RUNTIME_SWIFT self = withVaList(arguments) { String._unconditionallyBridgeFromObjectiveC( NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0) ) } #else self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } #endif } } extension StringProtocol where Index == String.Index { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. // FIXME(strings): There is probably a better way to bridge Self to NSString var _ns: NSString { return self._ephemeralString._bridgeToObjectiveC() } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _toIndex(_ utf16Index: Int) -> Index { return self._toUTF16Index(utf16Index) } /// Return the UTF-16 code unit offset corresponding to an Index func _toOffset(_ idx: String.Index) -> Int { return self._toUTF16Offset(idx) } @inlinable internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange(self._toUTF16Offsets(r)) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _toRange(_ r: NSRange) -> Range<Index> { return self._toUTF16Indices(Range(r)!) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. func _optionalRange(_ r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return nil } return _toRange(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( _ index: UnsafeMutablePointer<Index>?, _ body: (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = _toIndex(utf16Index) return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( _ range: UnsafeMutablePointer<Range<Index>>?, _ body: (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._toRange(nsRange) return result } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the string can be /// converted to the specified encoding without loss of information. /// /// - Parameter encoding: A string encoding. /// - Returns: `true` if the string can be encoded in `encoding` without loss /// of information; otherwise, `false`. public func canBeConverted(to encoding: String.Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// A copy of the string with each word changed to its corresponding /// capitalized spelling. /// /// This property performs the canonical (non-localized) mapping. It is /// suitable for programming operations that require stable results not /// depending on the current locale. /// /// A capitalized string is a string with the first character in each word /// changed to its corresponding uppercase value, and all remaining /// characters set to their corresponding lowercase values. A "word" is any /// sequence of characters delimited by spaces, tabs, or line terminators. /// Some common word delimiting punctuation isn't considered, so this /// property may not generally produce the desired results for multiword /// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for /// additional information. /// /// Case transformations aren’t guaranteed to be symmetrical or to produce /// strings of the same lengths as the originals. public var capitalized: String { return _ns.capitalized as String } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the string that is produced /// using the current locale. @available(macOS 10.11, iOS 9.0, *) public var localizedCapitalized: String { return _ns.localizedCapitalized } // - (NSString *)capitalizedStringWithLocale:(Locale *)locale /// Returns a capitalized representation of the string /// using the specified locale. public func capitalized(with locale: Locale?) -> String { return _ns.capitalized(with: locale) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString._ephemeralString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(StringCompareOptions)mask /// Returns a string containing characters this string and the /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix< T : StringProtocol >(with aString: T, options: String.CompareOptions = []) -> String { return _ns.commonPrefix(with: aString._ephemeralString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. public func compare<T : StringProtocol>( _ aString: T, options mask: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil ) -> ComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. let aString = aString._ephemeralString return locale != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange( range ?? startIndex..<endIndex ), locale: locale?._bridgeToObjectiveC() ) : range != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange(range!) ) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the string as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the string. /// /// - Returns: The actual number of matching paths. public func completePath( into outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { #if DEPLOYMENT_RUNTIME_SWIFT var outputNamePlaceholder: String? var outputArrayPlaceholder = [String]() let res = self._ns.completePath( into: &outputNamePlaceholder, caseSensitive: caseSensitive, matchesInto: &outputArrayPlaceholder, filterTypes: filterTypes ) if let n = outputNamePlaceholder { outputName?.pointee = n } else { outputName?.pointee = "" } outputArray?.pointee = outputArrayPlaceholder return res #else // DEPLOYMENT_RUNTIME_SWIFT var nsMatches: NSArray? var nsOutputName: NSString? let result: Int = outputName._withNilOrAddress(of: &nsOutputName) { outputName in outputArray._withNilOrAddress(of: &nsMatches) { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 let outputNonOptionalName = unsafeBitCast( outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self) let outputNonOptionalArray = unsafeBitCast( outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, matchesInto: outputNonOptionalArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion outputArray?.pointee = matches as! [String] } if let n = nsOutputName { outputName?.pointee = n as String } return result #endif // DEPLOYMENT_RUNTIME_SWIFT } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the string /// that have been divided by characters in the given set. public func components(separatedBy separator: CharacterSet) -> [String] { return _ns.components(separatedBy: separator) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the string that have been /// divided by the given separator. /// /// The substrings in the resulting array appear in the same order as the /// original string. Adjacent occurrences of the separator string produce /// empty strings in the result. Similarly, if the string begins or ends /// with the separator, the first or last substring, respectively, is empty. /// The following example shows this behavior: /// /// let list1 = "Karin, Carrie, David" /// let items1 = list1.components(separatedBy: ", ") /// // ["Karin", "Carrie", "David"] /// /// // Beginning with the separator: /// let list2 = ", Norman, Stanley, Fletcher" /// let items2 = list2.components(separatedBy: ", ") /// // ["", "Norman", "Stanley", "Fletcher" /// /// If the list has no separators, the array contains only the original /// string itself. /// /// let name = "Karin" /// let list = name.components(separatedBy: ", ") /// // ["Karin"] /// /// - Parameter separator: The separator string. /// - Returns: An array containing substrings that have been divided from the /// string using `separator`. // FIXME(strings): now when String conforms to Collection, this can be // replaced by split(separator:maxSplits:omittingEmptySubsequences:) public func components< T : StringProtocol >(separatedBy separator: T) -> [String] { return _ns.components(separatedBy: separator._ephemeralString) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the string as a C string /// using a given encoding. public func cString(using encoding: String.Encoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cString(using: encoding.rawValue)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns a `Data` containing a representation of /// the `String` encoded using a given encoding. public func data( using encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { switch encoding { case .utf8: return Data(self.utf8) default: return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } } // @property NSString* decomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines( invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void ) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line, &stop_) if stop_ { stop.pointee = true } } } // @property NSStringEncoding fastestEncoding; /// The fastest encoding to which the string can be converted without loss /// of information. public var fastestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.fastestEncoding) } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`'s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( _ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: Swift.min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and the given string using a case-insensitive, /// localized, comparison. public func localizedCaseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and the given string using a localized comparison. public func localizedCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCompare(aString._ephemeralString) } /// Compares the string and the given string as sorted by the Finder. public func localizedStandardCompare< T : StringProtocol >(_ string: T) -> ComparisonResult { return _ns.localizedStandardCompare(string._ephemeralString) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedLowercase: String { return _ns.localizedLowercase } // - (NSString *)lowercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. public func lowercased(with locale: Locale?) -> String { return _ns.lowercased(with: locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. public func maximumLengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // @property NSString* precomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } #if !DEPLOYMENT_RUNTIME_SWIFT // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. public func propertyList() -> Any { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:] } #endif // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns a Boolean value indicating whether the string contains the given /// string, taking the current locale into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardContains< T : StringProtocol >(_ string: T) -> Bool { return _ns.localizedStandardContains(string._ephemeralString) } // @property NSStringEncoding smallestEncoding; /// The smallest encoding to which the string can be converted without /// loss of information. public var smallestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.smallestEncoding) } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string created by replacing all characters in the string /// not in the specified set with percent encoded characters. public func addingPercentEncoding( withAllowedCharacters allowedCharacters: CharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.addingPercentEncoding(withAllowedCharacters: allowedCharacters ) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string created by appending a string constructed from a given /// format string and the following arguments. public func appendingFormat< T : StringProtocol >( _ format: T, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format._ephemeralString, arguments: arguments)) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string created by appending the given string. // FIXME(strings): shouldn't it be deprecated in favor of `+`? public func appending< T : StringProtocol >(_ aString: T) -> String { return _ns.appending(aString._ephemeralString) } /// Returns a string with the given character folding options /// applied. public func folding( options: String.CompareOptions = [], locale: Locale? ) -> String { return _ns.folding(options: options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. public func padding< T : StringProtocol >( toLength newLength: Int, withPad padString: T, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString._ephemeralString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// A new string made from the string by replacing all percent encoded /// sequences with the matching UTF-8 characters. public var removingPercentEncoding: String? { return _ns.removingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. public func replacingCharacters< T : StringProtocol, R : RangeExpression >(in range: R, with replacement: T) -> String where R.Bound == Index { return _ns.replacingCharacters( in: _toRelativeNSRange(range.relative(to: self)), with: replacement._ephemeralString) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(StringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the string are replaced by /// another given string. public func replacingOccurrences< Target : StringProtocol, Replacement : StringProtocol >( of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { let target = target._ephemeralString let replacement = replacement._ephemeralString return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } #endif // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. public func trimmingCharacters(in set: CharacterSet) -> String { return _ns.trimmingCharacters(in: set) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase as String } // - (NSString *)uppercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. public func uppercased(with locale: Locale?) -> String { return _ns.uppercased(with: locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func write< T : StringProtocol >( toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( toFile: path._ephemeralString, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func write( to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); #if !DEPLOYMENT_RUNTIME_SWIFT /// Perform string transliteration. @available(macOS 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, invoking body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) where R.Bound == Index { let range = range.relative(to: self) _ns.enumerateLinguisticTags( in: _toRelativeNSRange(range), scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString), options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0!.rawValue, self._toRange($1), self._toRange($2), &stop_) if stop_ { $3.pointee = true } } } #endif // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the specified range of /// the string. /// /// Mutation of a string value while enumerating its substrings is not /// supported. If you need to mutate a string from within `body`, convert /// your string to an `NSMutableString` instance and then call the /// `enumerateSubstrings(in:options:using:)` method. /// /// - Parameters: /// - range: The range within the string to enumerate substrings. /// - opts: Options specifying types of substrings and enumeration styles. /// If `opts` is omitted or empty, `body` is called a single time with /// the range of the string specified by `range`. /// - body: The closure executed for each substring in the enumeration. The /// closure takes four arguments: /// - The enumerated substring. If `substringNotRequired` is included in /// `opts`, this parameter is `nil` for every execution of the /// closure. /// - The range of the enumerated substring in the string that /// `enumerate(in:options:_:)` was called on. /// - The range that includes the substring as well as any separator or /// filler characters that follow. For instance, for lines, /// `enclosingRange` contains the line terminators. The enclosing /// range for the first string enumerated also contains any characters /// that occur before the string. Consecutive enclosing ranges are /// guaranteed not to overlap, and every single character in the /// enumerated range is included in one and only one enclosing range. /// - An `inout` Boolean value that the closure can use to stop the /// enumeration by setting `stop = true`. public func enumerateSubstrings< R : RangeExpression >( in range: R, options opts: String.EnumerationOptions = [], _ body: @escaping ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) where R.Bound == Index { _ns.enumerateSubstrings( in: _toRelativeNSRange(range.relative(to: self)), options: opts) { var stop_ = false body($0, self._toRange($1), self._toRange($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(StringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver's contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` if some characters were converted, `false` otherwise. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes< R : RangeExpression >( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: R, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool where R.Bound == Index { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: Swift.min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toRelativeNSRange(range.relative(to: self)), remaining: $0) } } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _toRange(_ns.lineRange( for: _toRelativeNSRange(aRange.relative(to: self)))) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. public func linguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] where R.Bound == Index { var nsTokenRanges: NSArray? let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toRelativeNSRange(range.relative(to: self)), scheme: NSLinguisticTagScheme(rawValue: tagScheme._ephemeralString), options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if let nsTokenRanges = nsTokenRanges { tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map { self._toRange($0.rangeValue) } } return result as! [String] } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _toRange( _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self)))) } #endif // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. public func rangeOfCharacter( from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toRelativeNSRange( aRange ?? startIndex..<endIndex ) ) ) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. public func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> { return _toRange( _ns.rangeOfComposedCharacterSequence(at: _toOffset(anIndex))) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences< R : RangeExpression >( for range: R ) -> Range<Index> where R.Bound == Index { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _toRange( _ns.rangeOfComposedCharacterSequences( for: _toRelativeNSRange(range.relative(to: self)))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(StringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)searchRange // locale:(Locale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. public func range< T : StringProtocol >( of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { let aString = aString._ephemeralString return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardRange< T : StringProtocol >(of string: T) -> Range<Index>? { return _optionalRange( _ns.localizedStandardRange(of: string._ephemeralString)) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func addingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } #endif //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` if `other` is non-empty and contained within `self` by /// case-sensitive, non-literal search. Otherwise, returns `false`. /// /// Equivalent to `self.rangeOfString(other) != nil` public func contains<T : StringProtocol>(_ other: T) -> Bool { let r = self.range(of: other) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.contains(other._ephemeralString)) } return r } /// Returns a Boolean value indicating whether the given string is non-empty /// and contained within this string by case-insensitive, non-literal /// search, taking into account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, can be /// achieved by calling `range(of:options:range:locale:)`. /// /// Equivalent to: /// /// range(of: other, options: .caseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains< T : StringProtocol >(_ other: T) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(macOS 10.10, iOS 8.0, *) { assert(r == _ns.localizedCaseInsensitiveContains(other._ephemeralString)) } return r } } // Deprecated slicing extension StringProtocol where Index == String.Index { // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range from' operator.") public func substring(from index: Index) -> String { return _ns.substring(from: _toOffset(index)) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range upto' operator.") public func substring(to index: Index) -> String { return _ns.substring(to: _toOffset(index)) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript.") public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toRelativeNSRange(aRange)) } } extension StringProtocol { // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { fatalError("unavailable function can't be called") } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public func getFileSystemRepresentation( _ buffer: inout [CChar], maxLength: Int) -> Bool { fatalError("unavailable function can't be called") } //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message: "Use lastPathComponent on URL instead.") public var lastPathComponent: String { fatalError("unavailable function can't be called") } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { fatalError("unavailable function can't be called") } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message: "Use pathComponents on URL instead.") public var pathComponents: [String] { fatalError("unavailable function can't be called") } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`'s extension, if any. @available(*, unavailable, message: "Use pathExtension on URL instead.") public var pathExtension: String { fatalError("unavailable function can't be called") } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.") public var abbreviatingWithTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message: "Use appendingPathComponent on URL instead.") public func appendingPathComponent(_ aString: String) -> String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message: "Use appendingPathExtension on URL instead.") public func appendingPathExtension(_ ext: String) -> String? { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.") public var deletingLastPathComponent: String { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message: "Use deletingPathExtension on URL instead.") public var deletingPathExtension: String { fatalError("unavailable function can't be called") } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.") public var expandingTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: String.CompareOptions = [], locale: Locale? ) -> String { fatalError("unavailable function can't be called") } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.") public var resolvingSymlinksInPath: String { fatalError("unavailable property") } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message: "Use standardizingPath on URL instead.") public var standardizingPath: String { fatalError("unavailable function can't be called") } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in a given array. @available(*, unavailable, message: "Map over paths with appendingPathComponent instead.") public func strings(byAppendingPaths paths: [String]) -> [String] { fatalError("unavailable function can't be called") } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: String.Encoding ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func pathWithComponents(_ components: [String]) -> String { fatalError("unavailable function can't be called") } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func path(withComponents components: [String]) -> String { fatalError("unavailable function can't be called") } } extension StringProtocol { @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "capitalizedString(with:)") public func capitalizedStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "commonPrefix(with:options:)") public func commonPrefixWith( _ aString: String, options: String.CompareOptions) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)") public func completePathInto( _ outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedByCharactersIn( _ separator: CharacterSet ) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)") public func enumerateLinguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: String.EnumerationOptions = [], _ body: ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") public func getBytes( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)") public func getLineStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)") public func getParagraphStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lengthOfBytes(using:)") public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lineRange(for:)") public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)") public func linguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil ) -> [String] { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "lowercased(with:)") public func lowercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "maximumLengthOfBytes(using:)") public func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "paragraphRange(for:)") public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)") public func rangeOfCharacterFrom( _ aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)") public func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)") public func rangeOfComposedCharacterSequencesFor( _ range: Range<Index> ) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "range(of:options:range:locale:)") public func rangeOf( _ aString: String, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "localizedStandardRange(of:)") public func localizedStandardRangeOf(_ string: String) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)") public func addingPercentEncodingWithAllowedCharacters( _ allowedCharacters: CharacterSet ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEscapes(using:)") public func addingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "appendingFormat") public func stringByAppendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "padding(toLength:with:startingAt:)") public func byPaddingToLength( _ newLength: Int, withString padString: String, startingAt padIndex: Int ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingCharacters(in:with:)") public func replacingCharactersIn( _ range: Range<Index>, withString replacement: String ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)") public func replacingOccurrencesOf( _ target: String, withString replacement: String, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "trimmingCharacters(in:)") public func byTrimmingCharactersIn(_ set: CharacterSet) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "strings(byAppendingPaths:)") public func stringsByAppendingPaths(_ paths: [String]) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(from:)") public func substringFrom(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(to:)") public func substringTo(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(with:)") public func substringWith(_ aRange: Range<Index>) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased(with:)") public func uppercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(toFile:atomically:encoding:)") public func writeToFile( _ path: String, atomically useAuxiliaryFile:Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(to:atomically:encoding:)") public func writeToURL( _ url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } }
apache-2.0
belkevich/DTModelStorage
DTModelStorage/Utilities/MemoryStorage+UpdateWithoutAnimations.swift
1
2050
// // MemoryStorage+UpdateWithoutAnimations.swift // DTModelStorageTests // // Created by Denys Telezhkin on 11.07.15. // Copyright (c) 2015 Denys Telezhkin. 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. extension MemoryStorage { /// This method allows multiple simultaneous changes to memory storage without any notifications for delegate. /// /// You can think of this as a way of "manual" management for memory storage. Typical usage would be multiple insertions/deletions etc., if you don't need any animations. You can batch any changes in block, and call reloadData on your UI component after this method was call. /// - Note: You must call reloadData after calling this method, or you will get NSInternalInconsistencyException runtime, thrown by either UITableView or UICollectionView. public func updateWithoutAnimations(block: () -> Void) { let delegate = self.delegate self.delegate = nil block() self.delegate = delegate } }
mit
pguth/OccupyHdM
ios/app/occupyhdm/occupyhdmUITests/occupyhdmUITests.swift
1
426
// // occupyhdmUITests.swift // occupyhdmUITests // // Created by Fabian Kugler on 15.03.16. // Copyright © 2016 occupyhdm. All rights reserved. // import XCTest class OccupyhdmUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testExample() {} }
mit
Sergtsaeb/DribbbleCollection
DribbbleCollection/DribbbleCollection/Keys.swift
1
352
// // Keys.swift // DribbbleCollection // // Created by Sergelenbaatar Tsogtbaatar on 6/20/17. // Copyright © 2017 Serg Tsogtbaatar. All rights reserved. // import Foundation let kClientID = "f08f587c2beffc39e8ea5fb87a45a794f37d2c9cb62042070d099a88e976d7d9" let kClientSecret = "d28d89ef71c981f577b83de7750a540b902870e94acf8bd802c8314305408806"
mit
pennlabs/penn-mobile-ios
PennMobile/Home/Cells/Post/Post.swift
1
388
// // Post.swift // PennMobile // // Created by Josh Doman on 3/1/19. // Copyright © 2019 PennLabs. All rights reserved. // import Foundation struct Post: Codable { let id: Int let title: String? let subtitle: String? let postUrl: String? let imageUrl: String let createdDate: Date let startDate: Date let expireDate: Date let source: String? }
mit
montehurd/apps-ios-wikipedia
Wikipedia/Code/ArticlePlaceView.swift
1
22913
import UIKit import WMF #if OSM import Mapbox #else import MapKit #endif protocol ArticlePlaceViewDelegate: NSObjectProtocol { func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) } class ArticlePlaceView: MapAnnotationView { static let smallDotImage = #imageLiteral(resourceName: "places-dot-small") static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium") static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque") static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium") static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque") static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium") static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque") static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large") static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque") static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ") static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium") static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large") static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium") static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large") public weak var delegate: ArticlePlaceViewDelegate? var imageView: UIView! private var imageImageView: UIImageView! private var imageImagePlaceholderView: UIImageView! private var imageOutlineView: UIView! private var imageBackgroundView: UIView! private var selectedImageView: UIView! private var selectedImageImageView: UIImageView! private var selectedImageImagePlaceholderView: UIImageView! private var selectedImageOutlineView: UIView! private var selectedImageBackgroundView: UIView! private var dotView: UIView! private var groupView: UIView! private var countLabel: UILabel! private var dimension: CGFloat! private var collapsedDimension: CGFloat! var groupDimension: CGFloat! var imageDimension: CGFloat! var selectedImageButton: UIButton! private var alwaysShowImage = false private let selectionAnimationDuration = 0.3 private let springDamping: CGFloat = 0.5 private let crossFadeRelativeHalfDuration: TimeInterval = 0.1 private let alwaysRasterize = true // set this or rasterize on animations, not both private let rasterizeOnAnimations = false override func setup() { selectedImageView = UIView() imageView = UIView() selectedImageImageView = UIImageView() imageImageView = UIImageView() selectedImageImageView.accessibilityIgnoresInvertColors = true imageImageView.accessibilityIgnoresInvertColors = true countLabel = UILabel() dotView = UIView() groupView = UIView() imageOutlineView = UIView() selectedImageOutlineView = UIView() imageBackgroundView = UIView() selectedImageBackgroundView = UIView() selectedImageButton = UIButton() imageImagePlaceholderView = UIImageView() selectedImageImagePlaceholderView = UIImageView() let scale = ArticlePlaceView.mediumDotImage.scale let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage collapsedDimension = ArticlePlaceView.smallDotImage.size.width groupDimension = ArticlePlaceView.mediumDotImage.size.width dimension = largeOpaqueDotOutlineImage.size.width imageDimension = mediumOpaqueDotOutlineImage.size.width let gravity = CALayerContentsGravity.bottomRight isPlaceholderHidden = false frame = CGRect(x: 0, y: 0, width: dimension, height: dimension) dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension) dotView.layer.contentsGravity = gravity dotView.layer.contentsScale = scale dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) addSubview(dotView) groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension) groupView.layer.contentsGravity = gravity groupView.layer.contentsScale = scale groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage addSubview(groupView) imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension) imageView.layer.rasterizationScale = scale addSubview(imageView) imageBackgroundView.frame = imageView.bounds imageBackgroundView.layer.contentsGravity = gravity imageBackgroundView.layer.contentsScale = scale imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage imageView.addSubview(imageBackgroundView) imageImagePlaceholderView.frame = imageView.bounds imageImagePlaceholderView.contentMode = .center imageImagePlaceholderView.image = mediumPlaceholderImage imageView.addSubview(imageImagePlaceholderView) var inset: CGFloat = 3.5 var imageViewFrame = imageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) imageImageView.frame = imageViewFrame imageImageView.contentMode = .scaleAspectFill imageImageView.layer.masksToBounds = true imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5 imageImageView.backgroundColor = UIColor.white imageView.addSubview(imageImageView) imageOutlineView.frame = imageView.bounds imageOutlineView.layer.contentsGravity = gravity imageOutlineView.layer.contentsScale = scale imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage imageView.addSubview(imageOutlineView) selectedImageView.bounds = bounds selectedImageView.layer.rasterizationScale = scale addSubview(selectedImageView) selectedImageBackgroundView.frame = selectedImageView.bounds selectedImageBackgroundView.layer.contentsGravity = gravity selectedImageBackgroundView.layer.contentsScale = scale selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage selectedImageView.addSubview(selectedImageBackgroundView) selectedImageImagePlaceholderView.frame = selectedImageView.bounds selectedImageImagePlaceholderView.contentMode = .center selectedImageImagePlaceholderView.image = largePlaceholderImage selectedImageView.addSubview(selectedImageImagePlaceholderView) inset = imageDimension > 40 ? 3.5 : 5.5 imageViewFrame = selectedImageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) selectedImageImageView.frame = imageViewFrame selectedImageImageView.contentMode = .scaleAspectFill selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5 selectedImageImageView.layer.masksToBounds = true selectedImageImageView.backgroundColor = UIColor.white selectedImageView.addSubview(selectedImageImageView) selectedImageOutlineView.frame = selectedImageView.bounds selectedImageOutlineView.layer.contentsGravity = gravity selectedImageOutlineView.layer.contentsScale = scale selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage selectedImageView.addSubview(selectedImageOutlineView) selectedImageButton.frame = selectedImageView.bounds selectedImageButton.accessibilityTraits = UIAccessibilityTraits.none selectedImageView.addSubview(selectedImageButton) countLabel.frame = groupView.bounds countLabel.textColor = UIColor.white countLabel.textAlignment = .center countLabel.font = UIFont.boldSystemFont(ofSize: 16) groupView.addSubview(countLabel) prepareForReuse() super.setup() updateLayout() update(withArticlePlace: annotation as? ArticlePlace) } func set(alwaysShowImage: Bool, animated: Bool) { self.alwaysShowImage = alwaysShowImage let scale = collapsedDimension/imageDimension let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale) if alwaysShowImage { loadImage() imageView.alpha = 0 imageView.isHidden = false dotView.alpha = 1 dotView.isHidden = false imageView.transform = imageViewScaleDownTransform dotView.transform = CGAffineTransform.identity } else { dotView.transform = dotViewScaleUpTransform imageView.transform = CGAffineTransform.identity imageView.alpha = 1 imageView.isHidden = false dotView.alpha = 0 dotView.isHidden = false } let transforms = { if alwaysShowImage { self.imageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform } else { self.imageView.transform = imageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity } } let fadesIn = { if alwaysShowImage { self.imageView.alpha = 1 } else { self.dotView.alpha = 1 } } let fadesOut = { if alwaysShowImage { self.dotView.alpha = 0 } else { self.imageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = false } guard let articlePlace = self.annotation as? ArticlePlace else { return } self.updateDotAndImageHiddenState(with: articlePlace.articles.count) } if animated { if alwaysShowImage { UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } override func didMoveToSuperview() { super.didMoveToSuperview() guard superview != nil else { selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) return } selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) } @objc func selectedImageViewWasTapped(_ sender: UIButton) { delegate?.articlePlaceViewWasTapped(self) } var zPosition: CGFloat = 1 { didSet { guard !isSelected else { return } layer.zPosition = zPosition } } var isPlaceholderHidden: Bool = true { didSet { selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden imageImagePlaceholderView.isHidden = isPlaceholderHidden imageImageView.isHidden = !isPlaceholderHidden selectedImageImageView.isHidden = !isPlaceholderHidden } } private var shouldRasterize = false { didSet { imageView.layer.shouldRasterize = shouldRasterize selectedImageView.layer.shouldRasterize = shouldRasterize } } private var isImageLoaded = false func loadImage() { guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else { return } if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = true let article = articlePlace.articles[0] if let thumbnailURL = article.thumbnailURL { imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in if self.alwaysRasterize { self.shouldRasterize = true } }, success: { self.selectedImageImageView.image = self.imageImageView.image self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect self.isPlaceholderHidden = true if self.alwaysRasterize { self.shouldRasterize = true } }) } } func update(withArticlePlace articlePlace: ArticlePlace?) { let articleCount = articlePlace?.articles.count ?? 1 switch articleCount { case 0: zPosition = 1 isPlaceholderHidden = false imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more") accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles") case 1: zPosition = 1 isImageLoaded = false if isSelected || alwaysShowImage { loadImage() } accessibilityLabel = articlePlace?.articles.first?.displayTitle default: zPosition = 2 let countString = "\(articleCount)" countLabel.text = countString accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group {{Identical|Article}}"), countString) } updateDotAndImageHiddenState(with: articleCount) } func updateDotAndImageHiddenState(with articleCount: Int) { switch articleCount { case 0: fallthrough case 1: imageView.isHidden = !alwaysShowImage dotView.isHidden = alwaysShowImage groupView.isHidden = true default: imageView.isHidden = true dotView.isHidden = true groupView.isHidden = false } } #if OSM override var annotation: MGLAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #else override var annotation: MKAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #endif override func prepareForReuse() { super.prepareForReuse() if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = false delegate = nil imageImageView.wmf_reset() selectedImageImageView.wmf_reset() countLabel.text = nil set(alwaysShowImage: false, animated: false) setSelected(false, animated: false) alpha = 1 transform = CGAffineTransform.identity } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) guard let place = annotation as? ArticlePlace, place.articles.count == 1 else { selectedImageView.alpha = 0 return } let dotScale = collapsedDimension/dimension let imageViewScale = imageDimension/dimension let scale = alwaysShowImage ? imageViewScale : dotScale let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale) let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale) layer.zPosition = 3 if selected { loadImage() selectedImageView.transform = selectedImageViewScaleDownTransform dotView.transform = CGAffineTransform.identity imageView.transform = CGAffineTransform.identity selectedImageView.alpha = 0 imageView.alpha = 1 dotView.alpha = 1 } else { selectedImageView.transform = CGAffineTransform.identity dotView.transform = dotViewScaleUpTransform imageView.transform = imageViewScaleUpTransform selectedImageView.alpha = 1 imageView.alpha = 0 dotView.alpha = 0 } let transforms = { if selected { self.selectedImageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform self.imageView.transform = imageViewScaleUpTransform } else { self.selectedImageView.transform = selectedImageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity self.imageView.transform = CGAffineTransform.identity } } let fadesIn = { if selected { self.selectedImageView.alpha = 1 } else { self.imageView.alpha = 1 self.dotView.alpha = 1 } } let fadesOut = { if selected { self.imageView.alpha = 0 self.dotView.alpha = 0 } else { self.selectedImageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.shouldRasterize = false } if !selected { self.layer.zPosition = self.zPosition } } if animated { let duration = 2*selectionAnimationDuration if selected { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } func updateLayout() { let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) selectedImageView.center = center imageView.center = center dotView.center = center groupView.center = center } override var frame: CGRect { didSet { guard isSetup else { return } updateLayout() } } override var bounds: CGRect { didSet { guard isSetup else { return } updateLayout() } } }
mit
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/AssetPriceView/DashboardAsset/DashboardAssetValuePresentation.swift
1
6588
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import PlatformKit extension DashboardAsset.Value.Presentation { /// The presentation model for `AssetPriceView` public struct AssetPrice: CustomDebugStringConvertible { private typealias AccessibilityId = Accessibility.Identifier.Dashboard.AssetCell /// Descriptors that allows customized content and style public struct Descriptors { /// Options to display content struct ContentOptions: OptionSet { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } /// Includes fiat price change static let fiat = ContentOptions(rawValue: 1 << 0) /// Includes percentage price change static let percentage = ContentOptions(rawValue: 2 << 0) } let contentOptions: ContentOptions let priceFont: UIFont let changeFont: UIFont let accessibilityIdSuffix: String } // MARK: - Properties /// The price of the asset let price: LabelContent /// The change let change: NSAttributedString let changeAccessibility: Accessibility public var debugDescription: String { price.text + " " + change.string } // MARK: - Setup public init(with value: DashboardAsset.Value.Interaction.AssetPrice, descriptors: Descriptors) { let fiatPrice = value.currentPrice.toDisplayString(includeSymbol: true) changeAccessibility = .id("\(AccessibilityId.changeLabelFormat)\(descriptors.accessibilityIdSuffix)") price = LabelContent( text: fiatPrice, font: descriptors.priceFont, color: .dashboardAssetTitle, accessibility: .id("\(AccessibilityId.marketFiatBalanceLabelFormat)\(descriptors.accessibilityIdSuffix)") ) change = value.historicalPrice .flatMap { historicalPrice in Self.changeAttributeString(with: historicalPrice, descriptors: descriptors) } ?? NSAttributedString() } private static func changeAttributeString( with historicalPrice: DashboardAsset.Value.Interaction.AssetPrice.HistoricalPrice, descriptors: Descriptors ) -> NSAttributedString { let fiatTintColor: UIColor var deltaTintColor: UIColor let sign: String if historicalPrice.priceChange.isPositive { sign = "+" fiatTintColor = .positivePrice } else if historicalPrice.priceChange.isNegative { sign = "" fiatTintColor = .negativePrice } else { sign = "" fiatTintColor = .mutedText } deltaTintColor = historicalPrice.changePercentage > 0 ? .positivePrice : .negativePrice deltaTintColor = historicalPrice.changePercentage.isZero ? .mutedText : deltaTintColor let fiatChange: NSAttributedString if descriptors.contentOptions.contains(.fiat) { let fiat = historicalPrice.priceChange.toDisplayString(includeSymbol: true) let suffix = descriptors.contentOptions.contains(.percentage) ? " " : "" fiatChange = NSAttributedString( LabelContent( text: "\(sign)\(fiat)\(suffix)", font: descriptors.changeFont, color: fiatTintColor ) ) } else { fiatChange = NSAttributedString() } let percentageChange: NSAttributedString if descriptors.contentOptions.contains(.percentage) { let prefix: String let suffix: String if descriptors.contentOptions.contains(.fiat) { prefix = "(" suffix = ")" } else { prefix = "" suffix = "" } let percentage = historicalPrice.changePercentage * 100 let percentageString = percentage.string(with: 2) percentageChange = NSAttributedString( LabelContent( text: "\(prefix)\(percentageString)%\(suffix)", font: descriptors.changeFont, color: deltaTintColor ) ) } else { percentageChange = NSAttributedString() } let period = NSAttributedString( LabelContent( text: historicalPrice.time.string, font: descriptors.changeFont, color: .mutedText ) ) return fiatChange + percentageChange + period } } } extension DashboardAsset.Value.Presentation.AssetPrice.Descriptors { /// Returns a descriptor for dashboard total balance public static var balance: DashboardAsset.Value.Presentation.AssetPrice.Descriptors { .init( contentOptions: [.fiat, .percentage], priceFont: .main(.semibold, 24.0), changeFont: .main(.medium, 14.0), accessibilityIdSuffix: Accessibility.Identifier.Dashboard.TotalBalanceCell.valueLabelSuffix ) } /// Returns a descriptor for dashboard asset price public static func assetPrice( accessibilityIdSuffix: String, priceFontSize: CGFloat = 16.0, changeFontSize: CGFloat = 14.0 ) -> DashboardAsset.Value.Presentation.AssetPrice.Descriptors { .init( contentOptions: [.percentage], priceFont: .main(.semibold, priceFontSize), changeFont: .main(.medium, changeFontSize), accessibilityIdSuffix: accessibilityIdSuffix ) } /// Returns a descriptor for widget asset price public static func widget(accessibilityIdSuffix: String) -> DashboardAsset.Value.Presentation.AssetPrice.Descriptors { .init( contentOptions: [.fiat], priceFont: .systemFont(ofSize: 16.0, weight: .semibold), changeFont: .systemFont(ofSize: 12.0, weight: .semibold), accessibilityIdSuffix: accessibilityIdSuffix ) } }
lgpl-3.0
groue/RxGRDB
Tests/RxGRDBTests/DatabaseReaderReadTests.swift
1
8507
import GRDB import RxBlocking import RxGRDB import RxSwift import XCTest private struct Player: Codable, FetchableRecord, PersistableRecord { var id: Int64 var name: String var score: Int? static func createTable(_ db: Database) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() t.column("score", .integer) } } } class DatabaseReaderReadTests : XCTestCase { func testRxJoiner() { // Make sure `rx` joiner is available in various contexts func f1(_ reader: DatabasePool) { _ = reader.rx.read(value: { db in }) } func f2(_ reader: DatabaseQueue) { _ = reader.rx.read(value: { db in }) } func f3(_ reader: DatabaseSnapshot) { _ = reader.rx.read(value: { db in }) } func f4<Reader: DatabaseReader>(_ reader: Reader) { _ = reader.rx.read(value: { db in }) } func f5(_ reader: DatabaseReader) { _ = reader.rx.read(value: { db in }) } } // MARK: - func testReadObservable() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(reader: DatabaseReader) throws { let single = reader.rx.read(value: { db in try Player.fetchCount(db) }) let value = try single.toBlocking(timeout: 1).single() XCTAssertEqual(value, 0) } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - func testReadObservableError() throws { func test(reader: DatabaseReader) throws { let single = reader.rx.read(value: { db in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } } try Test(test) .run { DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } // MARK: - func testReadObservableIsAsynchronous() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(reader: DatabaseReader) throws { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) reader.rx .read(value: { db in try Player.fetchCount(db) }) .subscribe( onSuccess: { _ in semaphore.wait() expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) semaphore.signal() waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - func testReadObservableDefaultScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(reader: DatabaseReader) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let expectation = self.expectation(description: "") reader.rx .read(value: { db in try Player.fetchCount(db) }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(.main)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } } // MARK: - func testReadObservableCustomScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(reader: DatabaseReader) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") reader.rx .read( observeOn: SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: "test"), value: { db in try Player.fetchCount(db) }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(queue)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } } // MARK: - func testReadObservableIsReadonly() throws { func test(reader: DatabaseReader) throws { let single = reader.rx.read(value: { db in try Player.createTable(db) }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_READONLY) } } try Test(test) .run { DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } }
mit
xivol/Swift-CS333
playgrounds/uiKit/uiKitCatalog/UIKitCatalog/SearchShowResultsInSourceViewController.swift
3
1372
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to show search results from a search controller within the source view controller (in this case, in the table view's header view). */ import UIKit class SearchShowResultsInSourceViewController: SearchResultsViewController { // MARK: - Properties // `searchController` is set in `viewDidLoad(_:)`. var searchController: UISearchController! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() /* Create the search controller, but we'll make sure that this `SearchShowResultsInSourceViewController` performs the results updating. */ searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false // Make sure the that the search bar is visible within the navigation bar. searchController.searchBar.sizeToFit() // Include the search controller's search bar within the table's header view. tableView.tableHeaderView = searchController.searchBar definesPresentationContext = true } }
mit
amrap-labs/TeamupKit
Sources/TeamupKit/Model/Membership.swift
1
2525
// // Membership.swift // TeamupKit // // Created by Merrick Sapsford on 20/06/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation public struct Membership: Codable { // MARK: Types /// Status of a membership /// /// - active: Active. /// - cancelled: Cancelled. /// - inactive: Inactive. enum Status: String, Codable { case active = "ACTIVE" case cancelled = "CANCELLED" case inactive = "INACTIVE" } enum CodingKeys: String, CodingKey { case id case name case number = "membership" case expirationDate = "expiration_date" case maximumUsesOnClasses = "maximum_allowed_class_uses" case usesOnClasses = "class_uses" case maximumUsesOnCourses = "maximum_allowed_course_uses" case usesOnCourses = "course_uses" case usageInfo = "usage_info" case status case allowedUses = "allowed_uses" case currentUses = "uses" } // MARK: Properties /// The unique identifier of the membership. let id: Int /// The name of the membership. let name: String /// The membership number. let number: Int /// The expiration date of the membership. let expirationDate: String? /// The maximum number of times that this membership can be used on classes. let maximumUsesOnClasses: Int? /// The number of times this membership has been used on classes. let usesOnClasses: Int /// The maximum number of times that this membership can be used on courses. let maximumUsesOnCourses: Int? /// The number of times this membership has been used on courses. let usesOnCourses: Int /// Description of the usage information for this membership. let usageInfo: String /// The current status of this membership. let status: Status /// The allowed usage of this membership. let allowedUses: UsageInfo /// The current usage of this membership. let currentUses: UsageInfo } public extension Membership { /// Information on membership usage. public struct UsageInfo: Codable { /// Number of usages in a day. let day: Int? /// Number of usages in a week. let week: Int? /// Number of usages in a month. let month: Int? /// Number of usages in a year. let year: Int? /// The number of usages overall. let overall: Int? } }
mit
Jnosh/swift
stdlib/public/core/Print.swift
12
11718
//===--- Print.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Writes the textual representations of the given items into the standard /// output. /// /// You can pass zero or more items to the `print(_:separator:terminator:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a string, /// a closed range of integers, and a group of floating-point values to /// standard output: /// /// print("One two three four five") /// // Prints "One two three four five" /// /// print(1...5) /// // Prints "1...5" /// /// print(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `print(_:separator:terminator:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// for n in 1...5 { /// print(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// /// - SeeAlso: `debugPrint(_:separator:terminator:)`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func print( _ items: Any..., separator: String = " ", terminator: String = "\n" ) { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _print( items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _print( items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items most suitable for /// debugging into the standard output. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:)` function. The textual representation /// for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints the debugging /// representation of a string, a closed range of integers, and a group of /// floating-point values to standard output: /// /// debugPrint("One two three four five") /// // Prints "One two three four five" /// /// debugPrint(1...5) /// // Prints "CountableClosedRange(1...5)" /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0) /// // Prints "1.0 2.0 3.0 4.0 5.0" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ") /// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0" /// /// The output from each call to `debugPrint(_:separator:terminator:)` includes /// a newline by default. To print the items without a trailing newline, pass /// an empty string as `terminator`. /// /// for n in 1...5 { /// debugPrint(n, terminator: "") /// } /// // Prints "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// /// - SeeAlso: `print(_:separator:terminator:)`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func debugPrint( _ items: Any..., separator: String = " ", terminator: String = "\n") { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _debugPrint( items, separator: separator, terminator: terminator, to: &output) hook(output.left) } else { var output = _Stdout() _debugPrint( items, separator: separator, terminator: terminator, to: &output) } } /// Writes the textual representations of the given items into the given output /// stream. /// /// You can pass zero or more items to the `print(_:separator:terminator:to:)` /// function. The textual representation for each item is the same as that /// obtained by calling `String(item)`. The following example prints a closed /// range of integers to a string: /// /// var range = "My range: " /// print(1...5, to: &range) /// // range == "My range: 1...5\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `print(_:separator:terminator:to:)` includes a /// newline by default. To print the items without a trailing newline, pass an /// empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// print(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. /// /// - SeeAlso: `print(_:separator:terminator:)`, /// `debugPrint(_:separator:terminator:to:)`, /// `TextOutputStream`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(__always) public func print<Target : TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _print(items, separator: separator, terminator: terminator, to: &output) } /// Writes the textual representations of the given items most suitable for /// debugging into the given output stream. /// /// You can pass zero or more items to the /// `debugPrint(_:separator:terminator:to:)` function. The textual /// representation for each item is the same as that obtained by calling /// `String(reflecting: item)`. The following example prints a closed range of /// integers to a string: /// /// var range = "My range: " /// debugPrint(1...5, to: &range) /// // range == "My range: CountableClosedRange(1...5)\n" /// /// To print the items separated by something other than a space, pass a string /// as `separator`. /// /// var separated = "" /// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated) /// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n" /// /// The output from each call to `debugPrint(_:separator:terminator:to:)` /// includes a newline by default. To print the items without a trailing /// newline, pass an empty string as `terminator`. /// /// var numbers = "" /// for n in 1...5 { /// debugPrint(n, terminator: "", to: &numbers) /// } /// // numbers == "12345" /// /// - Parameters: /// - items: Zero or more items to print. /// - separator: A string to print between each item. The default is a single /// space (`" "`). /// - terminator: The string to print after all items have been printed. The /// default is a newline (`"\n"`). /// - output: An output stream to receive the text representation of each /// item. /// /// - SeeAlso: `debugPrint(_:separator:terminator:)`, /// `print(_:separator:terminator:to:)`, /// `TextOutputStream`, `TextOutputStreamable`, /// `CustomStringConvertible`, `CustomDebugStringConvertible` @inline(__always) public func debugPrint<Target : TextOutputStream>( _ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target ) { _debugPrint( items, separator: separator, terminator: terminator, to: &output) } @_versioned @inline(never) @_semantics("stdlib_binary_only") internal func _print<Target : TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _print_unlocked(item, &output) prefix = separator } output.write(terminator) } @_versioned @inline(never) @_semantics("stdlib_binary_only") internal func _debugPrint<Target : TextOutputStream>( _ items: [Any], separator: String = " ", terminator: String = "\n", to output: inout Target ) { var prefix = "" output._lock() defer { output._unlock() } for item in items { output.write(prefix) _debugPrint_unlocked(item, &output) prefix = separator } output.write(terminator) } //===----------------------------------------------------------------------===// //===--- Migration Aids ---------------------------------------------------===// @available(*, unavailable, renamed: "print(_:separator:terminator:to:)") public func print<Target : TextOutputStream>( _ items: Any..., separator: String = "", terminator: String = "", toStream output: inout Target ) {} @available(*, unavailable, renamed: "debugPrint(_:separator:terminator:to:)") public func debugPrint<Target : TextOutputStream>( _ items: Any..., separator: String = "", terminator: String = "", toStream output: inout Target ) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'") public func print<T>(_: T, appendNewline: Bool = true) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'") public func debugPrint<T>(_: T, appendNewline: Bool = true) {} @available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'") public func print<T>(_: T, _: inout TextOutputStream) {} @available(*, unavailable, message: "Please use the 'to' label for the target stream: 'debugPrint((...), to: &...))'") public func debugPrint<T>(_: T, _: inout TextOutputStream) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'print((...), terminator: \"\", to: &...)'") public func print<T>(_: T, _: inout TextOutputStream, appendNewline: Bool = true) {} @available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'debugPrint((...), terminator: \"\", to: &...)'") public func debugPrint<T>( _: T, _: inout TextOutputStream, appendNewline: Bool = true ) {} //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
apache-2.0
snazzware/Mergel
HexMatch/Scenes/BankScene.swift
2
3843
// // BankScene.swift // HexMatch // // Created by Josh McKee on 1/30/16. // Copyright © 2016 Josh McKee. All rights reserved. // import SpriteKit import SNZSpriteKitUI class BankScene: SNZScene { override func didMove(to view: SKView) { super.didMove(to: view) self.updateGui() } func close() { self.view?.presentScene(SceneHelper.instance.gameScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4)) } func updateGui() { self.removeAllChildren() self.widgets.removeAll() // Set background self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0) // Create primary header let caption = SKLabelNode(fontNamed: "Avenir-Black") caption.text = "Tap to Spend Points" caption.fontColor = UIColor.white caption.fontSize = 24 caption.horizontalAlignmentMode = .center caption.verticalAlignmentMode = .center caption.position = CGPoint(x: self.size.width / 2, y: self.size.height - 20) caption.ignoreTouches = true self.addChild(caption) // Create sub-header let pointCaption = SKLabelNode(fontNamed: "Avenir-Black") pointCaption.text = "\(HexMapHelper.instance.scoreFormatter.string(from: NSNumber(integerLiteral: GameState.instance!.bankPoints))!) Points Available" pointCaption.fontColor = UIColor.white pointCaption.fontSize = 18 pointCaption.horizontalAlignmentMode = .center pointCaption.verticalAlignmentMode = .center pointCaption.position = CGPoint(x: self.size.width / 2, y: self.size.height - 44) pointCaption.ignoreTouches = true self.addChild(pointCaption) // Create array of buyable button widgets to represent the pieces we have available var buyables: [BuyableButtonWidget] = Array() // Create buttons for buyables for buyablePiece in GameState.instance!.buyablePieces { let buyable = BuyableButtonWidget() let hexPiece = buyablePiece.createPiece() buyable.buyableSprite = hexPiece.createSprite() buyable.caption = hexPiece.getPieceDescription() buyable.points = buyablePiece.currentPrice buyable.bind("tap",{ SceneHelper.instance.gameScene.captureState() SceneHelper.instance.gameScene.spendBankPoints(buyable.points) LevelHelper.instance.pushPiece(GameState.instance!.currentPiece!) SceneHelper.instance.gameScene.setCurrentPiece(hexPiece) buyablePiece.wasPurchased() self.close() }); buyables.append(buyable) } // Position and add the buyable button widgets let verticalStart:CGFloat = self.frame.height - 110 var horizontalOffset:CGFloat = 20 var verticalOffset = verticalStart for buyable in buyables { buyable.position = CGPoint(x: horizontalOffset,y: verticalOffset) self.addWidget(buyable) verticalOffset -= 60 if (verticalOffset < 60) { horizontalOffset += buyable.size.width + 10 verticalOffset = verticalStart } } // Add the close button let closeButton = MergelButtonWidget(parentNode: self) closeButton.anchorPoint = CGPoint(x: 0,y: 0) closeButton.caption = "Back" closeButton.bind("tap",{ self.close() }); self.addWidget(closeButton) // Render the widgets self.renderWidgets() } }
mit
jyhong836/Motion-Port
Motion Port/Motion Port/xValueTableViewCell.swift
1
631
// // xValueTableViewCell.swift // Motion Port // // Created by Junyuan Hong on 15/1/17. // Copyright (c) 2015年 Junyuan Hong. All rights reserved. // import UIKit class xValueTableViewCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var valueText: UILabel! @IBOutlet weak var unitText: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
RomeRock/ios-colortheme
SchemaColor/SchemaColor/MenuViewController.swift
2
1443
// // MenuViewController.swift // SchemaColor // // Created by NDM on 2/25/17. // Copyright © 2017 Rome Rock. All rights reserved. // import UIKit class MenuViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func facebookButtonPressed(_ sender: Any) { UIApplication.shared.open(URL(string:"https://www.facebook.com/337180269970605")!) } @IBAction func twitterButtonPressed(_ sender: Any) { UIApplication.shared.open(URL(string:"https://twitter.com/RomeRock_Apps")!) } @IBAction func githubButtonPressed(_ sender: Any) { UIApplication.shared.open(URL(string:"https://github.com/RomeRock")!) } @IBAction func romerockButtonPressed(_ sender: Any) { UIApplication.shared.open(URL(string:"http://romerock.com")!) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
nanoxd/Rex
Tests/UIKit/UILabelTests.swift
2
624
// // UILabelTests.swift // Rex // // Created by Neil Pankey on 8/20/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit import XCTest class UILabelTests: XCTestCase { weak var _label: UILabel? override func tearDown() { XCTAssert(_label == nil, "Retain cycle detected in UILabel properties") super.tearDown() } func testTextPropertyDoesntCreateRetainCycle() { let label = UILabel(frame: CGRectZero) _label = label label.rex_text <~ SignalProducer(value: "Test") XCTAssert(_label?.text == "Test") } }
mit
HIkaruSato/SimplePhotoViewer
PhotoViewer/ViewController.swift
1
1363
// // ViewController.swift // PhotoViewer // // Created by HikaruSato on 2016/04/10. // Copyright © 2016年 HikaruSato. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "photoViewer" { let navi = segue.destinationViewController as! UINavigationController let pc = navi.topViewController as! PhotoCollectionViewController pc.images = self.getSampleImages() } } private func getSampleImages() -> [UIImage] { var images = [UIImage]() for i in 1...15 { let image = UIImage(named: "cat\(i)")! images.append(image) } return images } }
mit
wangCanHui/weiboSwift
weiboSwift/Classes/Module/Main/View/CZVisitorView.swift
1
9795
// // CZVisitorView.swift // weiboSwift // // Created by 王灿辉 on 15/10/26. // Copyright © 2015年 王灿辉. All rights reserved. // import UIKit // 设置代理协议 protocol CZVisitorViewDelegate: NSObjectProtocol{ func visitorViewRegisterBtnClick() func visitorViewLoginBtnClick() } class CZVisitorView: UIView { // 设置代理属性,是可选的,因为代理方法可实现也可不实现 weak var visitorViewDelegate: CZVisitorViewDelegate? // MARK: - 按钮点击事件 /// 注册 func registBtnClick() { visitorViewDelegate?.visitorViewRegisterBtnClick() } /// 登陆 func loginBtnClick(){ visitorViewDelegate?.visitorViewLoginBtnClick() } // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } func setupVisitorView(imageName:String,message:String){ // 隐藏房子 homeView.hidden = true // 设置图像 iconView.image = UIImage(named: imageName) // 设置显示信息 msgLabel.text = message // 隐藏遮盖 coverView.hidden = true // self.sendSubviewToBack(coverView) //这种方式也可以 } // 转轮动画 func startIconViewAnimitation(){ let animation = CABasicAnimation() // 设置参数 animation.keyPath = "transform.rotation" animation.toValue = M_PI * 2 animation.repeatCount = MAXFLOAT animation.duration = 20 // 完成的时候不移除 animation.removedOnCompletion = false // 开始动画 iconView.layer.addAnimation(animation, forKey: "homeRotation") } /// 暂停旋转 func pauseAnimation() { // 记录暂停时间 let pauseTime = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) // 设置动画速度为0 iconView.layer.speed = 0 // 设置动画偏移时间 iconView.layer.timeOffset = pauseTime } /// 恢复旋转 func resumeAnimation() { // 获取暂停时间 let pauseTime = iconView.layer.timeOffset // 设置动画速度为1 iconView.layer.speed = 1 iconView.layer.timeOffset = 0 iconView.layer.beginTime = 0 let timeSincePause = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pauseTime iconView.layer.beginTime = timeSincePause } // 准备UI func prepareUI(){ // 0. 设置背景 self.backgroundColor = UIColor(white: 237/255.0, alpha: 1) // 1. 添加子控件 addSubview(iconView) addSubview(coverView) //遮盖 addSubview(homeView) addSubview(msgLabel) addSubview(registerBtn) addSubview(loginBtn) // 2. 设置约束 // 2.1 消除autoresizing iconView.translatesAutoresizingMaskIntoConstraints = false coverView.translatesAutoresizingMaskIntoConstraints = false homeView.translatesAutoresizingMaskIntoConstraints = false msgLabel.translatesAutoresizingMaskIntoConstraints = false registerBtn.translatesAutoresizingMaskIntoConstraints = false loginBtn.translatesAutoresizingMaskIntoConstraints = false // 2.2 添加约束 // 2.2.1 转轮 addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -40)) // 2.2.2 小房子 addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) // 2.2.3 消息文字 addConstraint(NSLayoutConstraint(item: msgLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: msgLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) // 2.2.4 注册按钮 addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: msgLabel, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: msgLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)) addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)) // 2.2.5 登陆按钮 addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: msgLabel, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: msgLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)) // 2.2.6 遮盖 addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: registerBtn, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)) } // MARK: - 懒加载 // 1. 转轮 private lazy var iconView:UIImageView = { let iconView = UIImageView() iconView.image = UIImage(named: "visitordiscover_feed_image_smallicon") // 自动匹配大小 iconView.sizeToFit() // self.addSubview(iconView) 在里面添加没有效果 return iconView }() // 2. 小房子,只有首页有 private lazy var homeView:UIImageView = { let homeView = UIImageView() homeView.image = UIImage(named: "visitordiscover_feed_image_house") homeView.sizeToFit() return homeView }() // 3. 消息文字 private lazy var msgLabel:UILabel = { let msg = UILabel() msg.text = "关注一些人,看看有什么惊喜" msg.numberOfLines = 0 msg.preferredMaxLayoutWidth = 240 msg.tintColor = UIColor.lightGrayColor() msg.sizeToFit() return msg }() // 4. 注册按钮 private lazy var registerBtn:UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) btn.setTitle("注册", forState: UIControlState.Normal) btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.sizeToFit() btn.addTarget(self, action: "registBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return btn }() // 5. 登陆按钮 private lazy var loginBtn:UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) btn.setTitle("登陆", forState: UIControlState.Normal) btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal) btn.sizeToFit() btn.addTarget(self, action: "loginBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return btn }() // 6. 遮盖 private lazy var coverView:UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) }
apache-2.0
justindhill/Facets
Facets/Models/OZLModelIssue.swift
1
13020
// // OZLModelIssue.swift // Facets // // Created by Justin Hill on 4/30/16. // Copyright © 2016 Justin Hill. All rights reserved. // import Foundation @objc class OZLModelIssue: NSObject, NSCopying { private static var __once: () = { OZLModelIssue.dateFormatter.dateFormat = "yyyy-MM-dd" }() static let dateFormatter = DateFormatter() @objc var modelDiffingEnabled: Bool = false { didSet(oldValue) { if oldValue != modelDiffingEnabled { self.changeDictionary = modelDiffingEnabled ? [:] : nil } } } @objc fileprivate(set) var changeDictionary: [String: AnyObject]? = nil @objc var tracker: OZLModelTracker? { didSet { if let tracker = tracker, self.modelDiffingEnabled { self.changeDictionary?["tracker_id"] = tracker.trackerId as AnyObject? } } } @objc var author: OZLModelUser? { didSet { if let author = author, self.modelDiffingEnabled { self.changeDictionary?["author_id"] = author.userId as AnyObject? } } } @objc var assignedTo: OZLModelUser? { didSet { if let assignedTo = assignedTo, self.modelDiffingEnabled { self.changeDictionary?["assigned_to_id"] = assignedTo.userId as AnyObject? } } } @objc var priority: OZLModelIssuePriority? { didSet { if let priority = priority, self.modelDiffingEnabled { self.changeDictionary?["priority_id"] = priority.priorityId as AnyObject? } } } @objc var status: OZLModelIssueStatus? { didSet { if let status = status, self.modelDiffingEnabled { self.changeDictionary?["status_id"] = status.statusId as AnyObject? } } } @objc var category: OZLModelIssueCategory? { didSet { if let category = category, self.modelDiffingEnabled { self.changeDictionary?["category_id"] = category.categoryId as AnyObject? } } } @objc var targetVersion: OZLModelVersion? { didSet { if let targetVersion = targetVersion, self.modelDiffingEnabled { self.changeDictionary?["fixed_version_id"] = targetVersion.versionId as AnyObject? } } } @objc var attachments: [OZLModelAttachment]? @objc var journals: [OZLModelJournal]? @objc var customFields: [OZLModelCustomField]? @objc var index: Int = 0 var projectId: Int? { didSet { if let projectId = projectId, self.modelDiffingEnabled { self.changeDictionary?["project_id"] = projectId as AnyObject? } } } var parentIssueId: Int? { didSet { if let parentIssueId = parentIssueId, self.modelDiffingEnabled { self.changeDictionary?["parent_issue_id"] = parentIssueId as AnyObject? } } } @objc var subject: String? { didSet { if let subject = subject, self.modelDiffingEnabled { self.changeDictionary?["subject"] = subject as AnyObject? } } } @objc var issueDescription: String? { didSet { if let issueDescription = issueDescription, self.modelDiffingEnabled { self.changeDictionary?["description"] = issueDescription as AnyObject? } } } @objc var startDate: Date? { didSet { if let startDate = startDate, self.modelDiffingEnabled { self.changeDictionary?["start_date"] = OZLModelIssue.dateFormatter.string(from: startDate) as AnyObject? } } } @objc var dueDate: Date? { didSet { if let dueDate = dueDate, self.modelDiffingEnabled { self.changeDictionary?["due_date"] = OZLModelIssue.dateFormatter.string(from: dueDate) as AnyObject? } } } @objc var createdOn: Date? { didSet { if let createdOn = createdOn, self.modelDiffingEnabled { self.changeDictionary?["created_on"] = OZLModelIssue.dateFormatter.string(from: createdOn) as AnyObject? } } } @objc var updatedOn: Date? { didSet { if let updatedOn = updatedOn, self.modelDiffingEnabled { self.changeDictionary?["updated_on"] = OZLModelIssue.dateFormatter.string(from: updatedOn) as AnyObject? } } } var doneRatio: Float? { didSet { if let doneRatio = doneRatio, self.modelDiffingEnabled { self.changeDictionary?["done_ratio"] = doneRatio as AnyObject? } } } var spentHours: Float? { didSet { if let spentHours = spentHours, self.modelDiffingEnabled { self.changeDictionary?["spent_hours"] = spentHours as AnyObject? } } } var estimatedHours: Float? { didSet { if let estimatedHours = estimatedHours, self.modelDiffingEnabled { self.changeDictionary?["estimated_hours"] = estimatedHours as AnyObject? } } } static var classInitToken = Int() @objc override init() { super.init() setup() } @objc init(dictionary d: [String: AnyObject]) { if let id = d["id"] as? Int { self.index = id } if let project = d["project"] as? [String: AnyObject], let projectId = project["id"] as? Int { self.projectId = projectId } if let parent = d["parent"] as? [String: AnyObject], let parentId = parent["id"] as? Int { self.parentIssueId = parentId } else { self.parentIssueId = -1 } if let tracker = d["tracker"] as? [AnyHashable: Any] { self.tracker = OZLModelTracker(attributeDictionary: tracker) } if let author = d["author"] as? [AnyHashable: Any] { self.author = OZLModelUser(attributeDictionary: author) } if let assignedTo = d["assigned_to"] as? [AnyHashable: Any] { self.assignedTo = OZLModelUser(attributeDictionary: assignedTo) } if let category = d["category"] as? [AnyHashable: Any] { self.category = OZLModelIssueCategory(attributeDictionary: category) } if let priority = d["priority"] as? [AnyHashable: Any] { self.priority = OZLModelIssuePriority(attributeDictionary: priority) } if let status = d["status"] as? [AnyHashable: Any] { self.status = OZLModelIssueStatus(attributeDictionary: status) } if let customFields = d["custom_fields"] as? [[AnyHashable: Any]] { self.customFields = customFields.map({ (field) -> OZLModelCustomField in return OZLModelCustomField(attributeDictionary: field) }) } self.subject = d["subject"] as? String self.issueDescription = d["description"] as? String if let startDate = d["start_date"] as? String { self.startDate = NSDate(iso8601String: startDate) as Date? } if let dueDate = d["due_date"] as? String { self.dueDate = NSDate(iso8601String: dueDate) as Date? } if let createdOn = d["created_on"] as? String { self.createdOn = NSDate(iso8601String: createdOn) as Date? } if let updatedOn = d["updated_on"] as? String { self.updatedOn = NSDate(iso8601String: updatedOn) as Date? } if let doneRatio = d["done_ratio"] as? Float { self.doneRatio = doneRatio } if let targetVersion = d["fixed_version"] as? [AnyHashable: Any] { self.targetVersion = OZLModelVersion(attributeDictionary: targetVersion) } if let spentHours = d["spent_hours"] as? Float { self.spentHours = spentHours } if let estimatedHours = d["estimated_hours"] as? Float { self.estimatedHours = estimatedHours } if let attachments = d["attachments"] as? [[AnyHashable: Any]] { self.attachments = attachments.map({ (attachment) -> OZLModelAttachment in return OZLModelAttachment(dictionary: attachment) }) } if let journals = d["journals"] as? [[String: AnyObject]] { self.journals = journals.map({ (journal) -> OZLModelJournal in return OZLModelJournal(attributes: journal) }) } super.init() setup() } func setup() { _ = OZLModelIssue.__once } @objc func setUpdateComment(_ comment: String) { if self.modelDiffingEnabled { self.changeDictionary?["notes"] = comment as AnyObject? } } @objc func setValueOnDiff(_ value: Any, forCustomFieldId fieldId: Int) { guard value is String || value is Int || value is Float else { fatalError() } if var changeDictionary = self.changeDictionary { if changeDictionary["custom_fields"] == nil { changeDictionary["custom_fields"] = [Int: AnyObject]() as AnyObject? } if var customFields = changeDictionary["custom_fields"] as? [Int: Any], fieldId > 0 { customFields[fieldId] = value changeDictionary["custom_fields"] = customFields as AnyObject } self.changeDictionary = changeDictionary } } @objc func setDateOnDiff(_ date: Date, forCustomFieldId fieldId: Int) { let dateString = OZLModelIssue.dateFormatter.string(from: date) self.setValueOnDiff(dateString, forCustomFieldId: fieldId) } @objc class func displayValueForAttributeName(_ name: String?, attributeId id: Int) -> String? { if let name = name { switch name { case "project_id": return OZLModelProject(forPrimaryKey: id)?.name case "tracker_id": return OZLModelTracker(forPrimaryKey: id)?.name case "fixed_version_id": return OZLModelVersion(forPrimaryKey: id)?.name case "status_id": return OZLModelIssueStatus(forPrimaryKey: id)?.name case "assigned_to_id": return OZLModelUser(forPrimaryKey: String(id))?.name case "category_id": return OZLModelIssueCategory(forPrimaryKey: id)?.name case "priority_id": return OZLModelIssuePriority(forPrimaryKey: id)?.name default: return String(id) } } return nil } @objc class func displayNameForAttributeName(_ name: String?) -> String { if let name = name { switch name { case "author": return "Author" case "project_id": return "Project" case "tracker_id": return "Tracker" case "fixed_version_id": return "Target version" case "status_id": return "Status" case "assigned_to_id": return "Assignee" case "category_id": return "Category" case "priority_id": return "Priority" case "due_date": return "Due date" case "start_date": return "Start date" case "done_ratio": return "Percent complete" case "spent_hours": return "Spent hours" case "estimated_hours": return "Estimated hours" case "description": return "Description" case "subject": return "Subject" default: assertionFailure("We were asked for a display name for an attribute we don't know of!") return name } } return "" } @objc func copy(with zone: NSZone?) -> Any { let copy = OZLModelIssue() copy.index = self.index copy.projectId = self.projectId copy.parentIssueId = self.parentIssueId copy.tracker = self.tracker copy.author = self.author copy.assignedTo = self.assignedTo copy.priority = self.priority copy.status = self.status copy.category = self.category copy.targetVersion = self.targetVersion copy.customFields = self.customFields copy.subject = self.subject copy.issueDescription = self.issueDescription copy.startDate = self.startDate copy.dueDate = self.dueDate copy.createdOn = self.createdOn copy.updatedOn = self.updatedOn copy.doneRatio = self.doneRatio copy.spentHours = self.spentHours copy.estimatedHours = self.estimatedHours copy.attachments = self.attachments copy.journals = self.journals return copy } }
mit
Eonil/Monolith.Swift
Text/Sources/EDXC/EDXC.swift
3
2867
// // EDXC.swift // EDXC // // Created by Hoon H. on 10/14/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation struct EDXC { struct Syntax { struct Characters { static let whitespace = any([" ", "\t", "\n"]) static let listOpener = one("(") static let listCloser = one(")") static let escaper = one("\\") static let escapee = any(["\\", "\"", " ", "(", ")"]) // static let escapee = any(["\\", "\"", " ", "(", ")", "t", "n", "u"]) static let doubleQuote = one("\"") static let nonWhitespace = not(whitespace) static let nonEscaper = not(escaper) static let symbolic = not(or([whitespace, escaper, listOpener, listCloser])) static let quotable = not(or([doubleQuote, escaper])) //// private typealias P = CharacterSubset private static let or = P.or private static let not = P.not private static let any = P.any private static let one = P.one } static let whitespaceStrip = chs(Characters.whitespace) * (1...Int.max) static let maybeWhitespaceStrip = whitespaceStrip * (0...Int.max) // static let whitespaceExpression = sub(whitespaceStrip) static let escapingSequence = lit("\\") + chs(Characters.escapee) static let symbolicUnit = chs(Characters.symbolic) | escapingSequence static let symbolForm = symbolicUnit * (1...Int.max) static let quotableUnit = chs(Characters.quotable) | escapingSequence static let quotationForm = lit("\"") + (quotableUnit * (1...Int.max)) + lit("\"") static let valueExpression = "value-expr" ~~~ symbolForm | quotationForm static let atomExpression = "atom-expr" ~~~ sub(valueExpression) | Lazy.listExpression() static let atomSeparator = whitespaceStrip static let atomWithSeparator = atomSeparator + sub(atomExpression) static let atomList = sub(atomExpression) + atomWithSeparator * (0...Int.max) static let maybeAtomList = atomList * (0...1) static let listExpression = "list-expr" ~~~ mk(lit("(")) + maybeWhitespaceStrip + maybeAtomList + maybeWhitespaceStrip + lit(")") struct Lazy { static func listExpression()(cursor:Cursor) -> Parsing.Stepping { return sub(Syntax.listExpression)(cursor: cursor) } } private typealias Stepping = Parsing.Stepping private typealias Rule = Parsing.Rule private typealias C = Parsing.Rule.Component private static let lit = C.literal private static let chs = C.chars private static let sub = C.subrule private static let mk = C.mark private struct Marks { static let listStarter = Marks.exp("list expression") private static let exp = Marks.exp_ private static func exp_(expectation:String)(composition c1:Rule.Composition)(cursor:Cursor) -> Stepping { return C.expect(composition: c1, expectation: expectation)(cursor: cursor) } } } }
mit