repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bfortunato/aj-framework | platforms/ios/Libs/socket.io-client-swift/Source/SocketPacket.swift | 23 | 6738 | //
// SocketPacket.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
struct SocketPacket {
enum PacketType: Int {
case connect, disconnect, event, ack, error, binaryEvent, binaryAck
}
private let placeholders: Int
private static let logType = "SocketPacket"
let nsp: String
let id: Int
let type: PacketType
var binary: [Data]
var data: [Any]
var args: [Any] {
if type == .event || type == .binaryEvent && data.count != 0 {
return Array(data.dropFirst())
} else {
return data
}
}
var description: String {
return "SocketPacket {type: \(String(type.rawValue)); data: " +
"\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
}
var event: String {
return String(describing: data[0])
}
var packetString: String {
return createPacketString()
}
init(type: PacketType, data: [Any] = [Any](), id: Int = -1, nsp: String, placeholders: Int = 0,
binary: [Data] = [Data]()) {
self.data = data
self.id = id
self.nsp = nsp
self.type = type
self.placeholders = placeholders
self.binary = binary
}
mutating func addData(_ data: Data) -> Bool {
if placeholders == binary.count {
return true
}
binary.append(data)
if placeholders == binary.count {
fillInPlaceholders()
return true
} else {
return false
}
}
private func completeMessage(_ message: String) -> String {
if data.count == 0 {
return message + "[]"
}
guard let jsonSend = try? data.toJSON(), let jsonString = String(data: jsonSend, encoding: .utf8) else {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
return message + "[]"
}
return message + jsonString
}
private func createPacketString() -> String {
let typeString = String(type.rawValue)
// Binary count?
let binaryCountString = typeString + (type == .binaryEvent || type == .binaryAck ? "\(String(binary.count))-" : "")
// Namespace?
let nspString = binaryCountString + (nsp != "/" ? "\(nsp)," : "")
// Ack number?
let idString = nspString + (id != -1 ? String(id) : "")
return completeMessage(idString)
}
// Called when we have all the binary data for a packet
// calls _fillInPlaceholders, which replaces placeholders with the
// corresponding binary
private mutating func fillInPlaceholders() {
data = data.map(_fillInPlaceholders)
}
// Helper method that looks for placeholders
// If object is a collection it will recurse
// Returns the object if it is not a placeholder or the corresponding
// binary data
private func _fillInPlaceholders(_ object: Any) -> Any {
switch object {
case let dict as JSON:
if dict["_placeholder"] as? Bool ?? false {
return binary[dict["num"] as! Int]
} else {
return dict.reduce(JSON(), {cur, keyValue in
var cur = cur
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
return cur
})
}
case let arr as [Any]:
return arr.map(_fillInPlaceholders)
default:
return object
}
}
}
extension SocketPacket {
private static func findType(_ binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return .event
case 0 where ack:
return .ack
case _ where !ack:
return .binaryEvent
case _ where ack:
return .binaryAck
default:
return .error
}
}
static func packetFromEmit(_ items: [Any], id: Int, nsp: String, ack: Bool) -> SocketPacket {
let (parsedData, binary) = deconstructData(items)
let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
id: id, nsp: nsp, binary: binary)
return packet
}
}
private extension SocketPacket {
// Recursive function that looks for NSData in collections
static func shred(_ data: Any, binary: inout [Data]) -> Any {
let placeholder = ["_placeholder": true, "num": binary.count] as JSON
switch data {
case let bin as Data:
binary.append(bin)
return placeholder
case let arr as [Any]:
return arr.map({shred($0, binary: &binary)})
case let dict as JSON:
return dict.reduce(JSON(), {cur, keyValue in
var mutCur = cur
mutCur[keyValue.0] = shred(keyValue.1, binary: &binary)
return mutCur
})
default:
return data
}
}
// Removes binary data from emit data
// Returns a type containing the de-binaryed data and the binary
static func deconstructData(_ data: [Any]) -> ([Any], [Data]) {
var binary = [Data]()
return (data.map({shred($0, binary: &binary)}), binary)
}
}
| apache-2.0 | ac9edf9c3ff2e32a2234b366efce6471 | 31.708738 | 123 | 0.569605 | 4.637302 | false | false | false | false |
tatey/LIFXHTTPKit | Source/Color.swift | 1 | 1295 | //
// Created by Tate Johnson on 22/06/2015.
// Copyright (c) 2015 Tate Johnson. All rights reserved.
//
import Foundation
public struct Color: Equatable, CustomStringConvertible {
static let maxHue: Double = 360.0
static let defaultKelvin: Int = 3500
public let hue: Double
public let saturation: Double
public let kelvin: Int
public init(hue: Double, saturation: Double, kelvin: Int) {
self.hue = hue
self.saturation = saturation
self.kelvin = kelvin
}
public static func color(_ hue: Double, saturation: Double) -> Color {
return Color(hue: hue, saturation: saturation, kelvin: Color.defaultKelvin)
}
public static func white(_ kelvin: Int) -> Color {
return Color(hue: 0.0, saturation: 0.0, kelvin: kelvin)
}
public var isColor: Bool {
return !isWhite
}
public var isWhite: Bool {
return saturation == 0.0
}
func toQueryStringValue() -> String {
if isWhite {
return "kelvin:\(kelvin)"
} else {
return "hue:\(hue) saturation:\(saturation)"
}
}
// MARK: Printable
public var description: String {
return "<Color hue: \(hue), saturation: \(saturation), kelvin: \(kelvin)>"
}
}
public func ==(lhs: Color, rhs: Color) -> Bool {
return lhs.hue == rhs.hue &&
lhs.saturation == rhs.saturation &&
lhs.kelvin == rhs.kelvin
}
| mit | 22f66d2b1d60df2ad0c948bb07971e7d | 21.719298 | 77 | 0.675676 | 3.363636 | false | false | false | false |
uasys/swift | benchmark/single-source/StringEnum.swift | 1 | 5166 | //===--- StringEnum.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
enum TestEnum : String {
case c1 = "Swift"
case c2 = "is"
case c3 = "a"
case c4 = "general-purpose"
case c5 = "programming language"
case c7 = "built"
case c8 = "using"
case c10 = "modern"
case c11 = "approach"
case c12 = "to"
case c13 = "safety,"
case c14 = "performance,"
case c15 = "and"
case c16 = "software"
case c17 = "design"
case c18 = "patterns."
case c19 = ""
case c20 = "The"
case c21 = "goal"
case c22 = "of"
case c23 = "the"
case c25 = "project"
case c28 = "create"
case c30 = "best"
case c31 = "available"
case c33 = "for"
case c34 = "uses"
case c35 = "ranging"
case c36 = "from"
case c37 = "systems"
case c40 = "mobile"
case c42 = "desktop"
case c43 = "apps,"
case c44 = "scaling"
case c45 = "up"
case c47 = "cloud"
case c48 = "services."
case c49 = "Most"
case c50 = "importantly,"
case c53 = "designed"
case c55 = "make"
case c56 = "writing"
case c58 = "maintaining"
case c59 = "correct"
case c60 = "programs"
case c61 = "easier"
case c64 = "developer."
case c65 = "To"
case c66 = "achieve"
case c67 = "this"
case c68 = "goal,"
case c69 = "we"
case c70 = "believe"
case c71 = "that"
case c73 = "most"
case c74 = "obvious"
case c75 = "way"
case c77 = "write"
case c79 = "code"
case c80 = "must"
case c81 = "also"
case c82 = "be:"
case c84 = "Safe."
case c92 = "should"
case c94 = "behave"
case c95 = "in"
case c97 = "safe"
case c98 = "manner."
case c99 = "Undefined"
case c100 = "behavior"
case c103 = "enemy"
case c107 = "developer"
case c108 = "mistakes"
case c110 = "be"
case c111 = "caught"
case c112 = "before"
case c116 = "production."
case c117 = "Opting"
case c119 = "safety"
case c120 = "sometimes"
case c121 = "means"
case c123 = "will"
case c124 = "feel"
case c125 = "strict,"
case c126 = "but"
case c130 = "clarity"
case c131 = "saves"
case c132 = "time"
case c135 = "long"
case c136 = "run."
case c138 = "Fast."
case c141 = "intended"
case c142 = "as"
case c144 = "replacement"
case c146 = "C-based"
case c147 = "languages"
case c148 = "(C, C++, Objective-C)."
case c152 = "As"
case c153 = "such,"
case c157 = "comparable"
case c159 = "those"
case c162 = "performance"
case c165 = "tasks."
case c166 = "Performance"
case c170 = "predictable"
case c172 = "consistent,"
case c173 = "not"
case c174 = "just"
case c175 = "fast"
case c177 = "short"
case c178 = "bursts"
case c180 = "require"
case c181 = "clean-up"
case c182 = "later."
case c183 = "There"
case c184 = "are"
case c185 = "lots"
case c188 = "with"
case c189 = "novel"
case c190 = "features"
case c191 = "—"
case c192 = "being"
case c195 = "rare."
case c197 = "Expressive."
case c199 = "benefits"
case c201 = "decades"
case c203 = "advancement"
case c205 = "computer"
case c206 = "science"
case c208 = "offer"
case c209 = "syntax"
case c213 = "joy"
case c215 = "use,"
case c219 = "developers"
case c220 = "expect."
case c221 = "But"
case c224 = "never"
case c225 = "done."
case c226 = "We"
case c228 = "monitor"
case c230 = "advancements"
case c232 = "embrace"
case c233 = "what"
case c234 = "works,"
case c235 = "continually"
case c236 = "evolving"
case c240 = "even"
case c241 = "better."
case c243 = "Tools"
case c246 = "critical"
case c247 = "part"
case c251 = "ecosystem."
case c253 = "strive"
case c255 = "integrate"
case c256 = "well"
case c257 = "within"
case c259 = "developer’s"
case c260 = "toolset,"
case c262 = "build"
case c263 = "quickly,"
case c265 = "present"
case c266 = "excellent"
case c267 = "diagnostics,"
case c270 = "enable"
case c271 = "interactive"
case c272 = "development"
case c273 = "experiences."
case c275 = "can"
case c278 = "so"
case c279 = "much"
case c280 = "more"
case c281 = "powerful,"
case c282 = "like"
case c283 = "Swift-based"
case c284 = "playgrounds"
case c285 = "do"
case c287 = "Xcode,"
case c288 = "or"
case c290 = "web-based"
case c291 = "REPL"
case c293 = "when"
case c294 = "working"
case c296 = "Linux"
case c297 = "server-side"
case c298 = "code."
}
@inline(never)
func convert(_ s: String) {
blackHole(TestEnum(rawValue: s))
}
@inline(never)
public func run_StringEnumRawValueInitialization(_ N: Int) {
let first = "Swift"
let short = "To"
let long = "(C, C++, Objective-C)."
let last = "code."
for _ in 1...2000*N {
convert(first)
convert(short)
convert(long)
convert(last)
}
}
| apache-2.0 | 71fe185aa18126b65c140b5d9813e7f3 | 22.357466 | 80 | 0.591825 | 2.927964 | false | false | false | false |
cburrows/swift-protobuf | Sources/SwiftProtobuf/AnyMessageStorage.swift | 1 | 18984 | // Sources/SwiftProtobuf/AnyMessageStorage.swift - Custom stroage for Any WKT
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Hand written storage class for Google_Protobuf_Any to support on demand
/// transforms between the formats.
///
// -----------------------------------------------------------------------------
import Foundation
fileprivate func serializeAnyJSON(
for message: Message,
typeURL: String,
options: JSONEncodingOptions
) throws -> String {
var visitor = try JSONEncodingVisitor(type: type(of: message), options: options)
visitor.startObject(message: message)
visitor.encodeField(name: "@type", stringValue: typeURL)
if let m = message as? _CustomJSONCodable {
let value = try m.encodedJSONString(options: options)
visitor.encodeField(name: "value", jsonText: value)
} else {
try message.traverse(visitor: &visitor)
}
visitor.endObject()
return visitor.stringResult
}
fileprivate func emitVerboseTextForm(visitor: inout TextFormatEncodingVisitor, message: Message, typeURL: String) {
let url: String
if typeURL.isEmpty {
url = buildTypeURL(forMessage: message, typePrefix: defaultAnyTypeURLPrefix)
} else {
url = typeURL
}
visitor.visitAnyVerbose(value: message, typeURL: url)
}
fileprivate func asJSONObject(body: Data) -> Data {
let asciiOpenCurlyBracket = UInt8(ascii: "{")
let asciiCloseCurlyBracket = UInt8(ascii: "}")
var result = Data([asciiOpenCurlyBracket])
result.append(body)
result.append(asciiCloseCurlyBracket)
return result
}
fileprivate func unpack(contentJSON: Data,
extensions: ExtensionMap,
options: JSONDecodingOptions,
as messageType: Message.Type) throws -> Message {
guard messageType is _CustomJSONCodable.Type else {
let contentJSONAsObject = asJSONObject(body: contentJSON)
return try messageType.init(jsonUTF8Data: contentJSONAsObject, extensions: extensions, options: options)
}
var value = String()
try contentJSON.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
if body.count > 0 {
// contentJSON will be the valid JSON for inside an object (everything but
// the '{' and '}', so minimal validation is needed.
var scanner = JSONScanner(source: body, options: options, extensions: extensions)
while !scanner.complete {
let key = try scanner.nextQuotedString()
try scanner.skipRequiredColon()
if key == "value" {
value = try scanner.skip()
break
}
if !options.ignoreUnknownFields {
// The only thing within a WKT should be "value".
throw AnyUnpackError.malformedWellKnownTypeJSON
}
let _ = try scanner.skip()
try scanner.skipRequiredComma()
}
if !options.ignoreUnknownFields && !scanner.complete {
// If that wasn't the end, then there was another key, and WKTs should
// only have the one when not skipping unknowns.
throw AnyUnpackError.malformedWellKnownTypeJSON
}
}
}
return try messageType.init(jsonString: value, extensions: extensions, options: options)
}
internal class AnyMessageStorage {
// The two properties generated Google_Protobuf_Any will reference.
var _typeURL = String()
var _value: Data {
// Remapped to the internal `state`.
get {
switch state {
case .binary(let value):
return value
case .message(let message):
do {
return try message.serializedData(partial: true)
} catch {
return Data()
}
case .contentJSON(let contentJSON, let options):
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else {
return Data()
}
do {
let m = try unpack(contentJSON: contentJSON,
extensions: SimpleExtensionMap(),
options: options,
as: messageType)
return try m.serializedData(partial: true)
} catch {
return Data()
}
}
}
set {
state = .binary(newValue)
}
}
enum InternalState {
// a serialized binary
// Note: Unlike contentJSON below, binary does not bother to capture the
// decoding options. This is because the actual binary format is the binary
// blob, i.e. - when decoding from binary, the spec doesn't include decoding
// the binary blob, it is pass through. Instead there is a public api for
// unpacking that takes new options when a developer decides to decode it.
case binary(Data)
// a message
case message(Message)
// parsed JSON with the @type removed and the decoding options.
case contentJSON(Data, JSONDecodingOptions)
}
var state: InternalState = .binary(Data())
static let defaultInstance = AnyMessageStorage()
private init() {}
init(copying source: AnyMessageStorage) {
_typeURL = source._typeURL
state = source.state
}
func isA<M: Message>(_ type: M.Type) -> Bool {
if _typeURL.isEmpty {
return false
}
let encodedType = typeName(fromURL: _typeURL)
return encodedType == M.protoMessageName
}
// This is only ever called with the expectation that target will be fully
// replaced during the unpacking and never as a merge.
func unpackTo<M: Message>(
target: inout M,
extensions: ExtensionMap?,
options: BinaryDecodingOptions
) throws {
guard isA(M.self) else {
throw AnyUnpackError.typeMismatch
}
switch state {
case .binary(let data):
target = try M(serializedData: data, extensions: extensions, partial: true, options: options)
case .message(let msg):
if let message = msg as? M {
// Already right type, copy it over.
target = message
} else {
// Different type, serialize and parse.
let data = try msg.serializedData(partial: true)
target = try M(serializedData: data, extensions: extensions, partial: true)
}
case .contentJSON(let contentJSON, let options):
target = try unpack(contentJSON: contentJSON,
extensions: extensions ?? SimpleExtensionMap(),
options: options,
as: M.self) as! M
}
}
// Called before the message is traversed to do any error preflights.
// Since traverse() will use _value, this is our chance to throw
// when _value can't.
func preTraverse() throws {
switch state {
case .binary:
// Nothing to be checked.
break
case .message:
// When set from a developer provided message, partial support
// is done. Any message that comes in from another format isn't
// checked, and transcoding the isInitialized requirement is
// never inserted.
break
case .contentJSON(let contentJSON, let options):
// contentJSON requires we have the type available for decoding
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else {
throw BinaryEncodingError.anyTranscodeFailure
}
do {
// Decodes the full JSON and then discard the result.
// The regular traversal will decode this again by querying the
// `value` field, but that has no way to fail. As a result,
// we need this to accurately handle decode errors.
_ = try unpack(contentJSON: contentJSON,
extensions: SimpleExtensionMap(),
options: options,
as: messageType)
} catch {
throw BinaryEncodingError.anyTranscodeFailure
}
}
}
}
/// Custom handling for Text format.
extension AnyMessageStorage {
func decodeTextFormat(typeURL url: String, decoder: inout TextFormatDecoder) throws {
// Decoding the verbose form requires knowing the type.
_typeURL = url
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: url) else {
// The type wasn't registered, can't parse it.
throw TextFormatDecodingError.malformedText
}
let terminator = try decoder.scanner.skipObjectStart()
var subDecoder = try TextFormatDecoder(messageType: messageType, scanner: decoder.scanner, terminator: terminator)
if messageType == Google_Protobuf_Any.self {
var any = Google_Protobuf_Any()
try any.decodeTextFormat(decoder: &subDecoder)
state = .message(any)
} else {
var m = messageType.init()
try m.decodeMessage(decoder: &subDecoder)
state = .message(m)
}
decoder.scanner = subDecoder.scanner
if try decoder.nextFieldNumber() != nil {
// Verbose any can never have additional keys.
throw TextFormatDecodingError.malformedText
}
}
// Specialized traverse for writing out a Text form of the Any.
// This prefers the more-legible "verbose" format if it can
// use it, otherwise will fall back to simpler forms.
internal func textTraverse(visitor: inout TextFormatEncodingVisitor) {
switch state {
case .binary(let valueData):
if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) {
// If we can decode it, we can write the readable verbose form:
do {
let m = try messageType.init(serializedData: valueData, partial: true)
emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL)
return
} catch {
// Fall through to just print the type and raw binary data
}
}
if !_typeURL.isEmpty {
try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1)
}
if !valueData.isEmpty {
try! visitor.visitSingularBytesField(value: valueData, fieldNumber: 2)
}
case .message(let msg):
emitVerboseTextForm(visitor: &visitor, message: msg, typeURL: _typeURL)
case .contentJSON(let contentJSON, let options):
// If we can decode it, we can write the readable verbose form:
if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) {
do {
let m = try unpack(contentJSON: contentJSON,
extensions: SimpleExtensionMap(),
options: options,
as: messageType)
emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL)
return
} catch {
// Fall through to just print the raw JSON data
}
}
if !_typeURL.isEmpty {
try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1)
}
// Build a readable form of the JSON:
let contentJSONAsObject = asJSONObject(body: contentJSON)
visitor.visitAnyJSONDataField(value: contentJSONAsObject)
}
}
}
/// The obvious goal for Hashable/Equatable conformance would be for
/// hash and equality to behave as if we always decoded the inner
/// object and hashed or compared that. Unfortunately, Any typically
/// stores serialized contents and we don't always have the ability to
/// deserialize it. Since none of our supported serializations are
/// fully deterministic, we can't even ensure that equality will
/// behave this way when the Any contents are in the same
/// serialization.
///
/// As a result, we can only really perform a "best effort" equality
/// test. Of course, regardless of the above, we must guarantee that
/// hashValue is compatible with equality.
extension AnyMessageStorage {
// Can't use _valueData for a few reasons:
// 1. Since decode is done on demand, two objects could be equal
// but created differently (one from JSON, one for Message, etc.),
// and the hash values have to be equal even if we don't have data
// yet.
// 2. map<> serialization order is undefined. At the time of writing
// the Swift, Objective-C, and Go runtimes all tend to have random
// orders, so the messages could be identical, but in binary form
// they could differ.
public func hash(into hasher: inout Hasher) {
if !_typeURL.isEmpty {
hasher.combine(_typeURL)
}
}
func isEqualTo(other: AnyMessageStorage) -> Bool {
if (_typeURL != other._typeURL) {
return false
}
// Since the library does lazy Any decode, equality is a very hard problem.
// It things exactly match, that's pretty easy, otherwise, one ends up having
// to error on saying they aren't equal.
//
// The best option would be to have Message forms and compare those, as that
// removes issues like map<> serialization order, some other protocol buffer
// implementation details/bugs around serialized form order, etc.; but that
// would also greatly slow down equality tests.
//
// Do our best to compare what is present have...
// If both have messages, check if they are the same.
if case .message(let myMsg) = state, case .message(let otherMsg) = other.state, type(of: myMsg) == type(of: otherMsg) {
// Since the messages are known to be same type, we can claim both equal and
// not equal based on the equality comparison.
return myMsg.isEqualTo(message: otherMsg)
}
// If both have serialized data, and they exactly match; the messages are equal.
// Because there could be map in the message, the fact that the data isn't the
// same doesn't always mean the messages aren't equal. Likewise, the binary could
// have been created by a library that doesn't order the fields, or the binary was
// created using the appending ability in of the binary format.
if case .binary(let myValue) = state, case .binary(let otherValue) = other.state, myValue == otherValue {
return true
}
// If both have contentJSON, and they exactly match; the messages are equal.
// Because there could be map in the message (or the JSON could just be in a different
// order), the fact that the JSON isn't the same doesn't always mean the messages
// aren't equal.
if case .contentJSON(let myJSON, _) = state,
case .contentJSON(let otherJSON, _) = other.state,
myJSON == otherJSON {
return true
}
// Out of options. To do more compares, the states conversions would have to be
// done to do comparisions; and since equality can be used somewhat removed from
// a developer (if they put protos in a Set, use them as keys to a Dictionary, etc),
// the conversion cost might be to high for those uses. Give up and say they aren't equal.
return false
}
}
// _CustomJSONCodable support for Google_Protobuf_Any
extension AnyMessageStorage {
// Override the traversal-based JSON encoding
// This builds an Any JSON representation from one of:
// * The message we were initialized with,
// * The JSON fields we last deserialized, or
// * The protobuf field we were deserialized from.
// The last case requires locating the type, deserializing
// into an object, then reserializing back to JSON.
func encodedJSONString(options: JSONEncodingOptions) throws -> String {
switch state {
case .binary(let valueData):
// Follow the C++ protostream_objectsource.cc's
// ProtoStreamObjectSource::RenderAny() special casing of an empty value.
guard !valueData.isEmpty else {
if _typeURL.isEmpty {
return "{}"
}
var jsonEncoder = JSONEncoder()
jsonEncoder.startField(name: "@type")
jsonEncoder.putStringValue(value: _typeURL)
jsonEncoder.endObject()
return jsonEncoder.stringResult
}
// Transcode by decoding the binary data to a message object
// and then recode back into JSON.
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else {
// If we don't have the type available, we can't decode the
// binary value, so we're stuck. (The Google spec does not
// provide a way to just package the binary value for someone
// else to decode later.)
throw JSONEncodingError.anyTranscodeFailure
}
let m = try messageType.init(serializedData: valueData, partial: true)
return try serializeAnyJSON(for: m, typeURL: _typeURL, options: options)
case .message(let msg):
// We should have been initialized with a typeURL, but
// ensure it wasn't cleared.
let url = !_typeURL.isEmpty ? _typeURL : buildTypeURL(forMessage: msg, typePrefix: defaultAnyTypeURLPrefix)
return try serializeAnyJSON(for: msg, typeURL: url, options: options)
case .contentJSON(let contentJSON, _):
var jsonEncoder = JSONEncoder()
jsonEncoder.startObject()
jsonEncoder.startField(name: "@type")
jsonEncoder.putStringValue(value: _typeURL)
if !contentJSON.isEmpty {
jsonEncoder.append(staticText: ",")
// NOTE: This doesn't really take `options` into account since it is
// just reflecting out what was taken in originally.
jsonEncoder.append(utf8Data: contentJSON)
}
jsonEncoder.endObject()
return jsonEncoder.stringResult
}
}
// TODO: If the type is well-known or has already been registered,
// we should consider decoding eagerly. Eager decoding would
// catch certain errors earlier (good) but would probably be
// a performance hit if the Any contents were never accessed (bad).
// Of course, we can't always decode eagerly (we don't always have the
// message type available), so the deferred logic here is still needed.
func decodeJSON(from decoder: inout JSONDecoder) throws {
try decoder.scanner.skipRequiredObjectStart()
// Reset state
_typeURL = String()
state = .binary(Data())
if decoder.scanner.skipOptionalObjectEnd() {
return
}
var jsonEncoder = JSONEncoder()
while true {
let key = try decoder.scanner.nextQuotedString()
try decoder.scanner.skipRequiredColon()
if key == "@type" {
_typeURL = try decoder.scanner.nextQuotedString()
} else {
jsonEncoder.startField(name: key)
let keyValueJSON = try decoder.scanner.skip()
jsonEncoder.append(text: keyValueJSON)
}
if decoder.scanner.skipOptionalObjectEnd() {
// Capture the options, but set the messageDepthLimit to be what
// was left right now, as that is the limit when the JSON is finally
// parsed.
var updatedOptions = decoder.options
updatedOptions.messageDepthLimit = decoder.scanner.recursionBudget
state = .contentJSON(jsonEncoder.dataResult, updatedOptions)
return
}
try decoder.scanner.skipRequiredComma()
}
}
}
| apache-2.0 | 4f459db32c81c1d509eb8a7daeea48c7 | 38.385892 | 123 | 0.66161 | 4.626858 | false | false | false | false |
SpiciedCrab/MGRxKitchen | MGRxKitchen/Classes/RxMogoForTableView/RxMogo+CellReuse.swift | 1 | 1354 | //
// RxMogo+CellReuse.swift
// MGRxKitchen
//
// Created by Harly on 2017/12/30.
//
import UIKit
import RxCocoa
import RxSwift
private var prepareForReuseBag: Int8 = 0
@objc public protocol Reusable: class {
func prepareForReuse()
}
extension UITableViewCell: Reusable {}
extension UICollectionViewCell: Reusable {}
extension UITableViewHeaderFooterView: Reusable {}
extension UICollectionReusableView: Reusable {}
extension Reactive where Base: Reusable {
var prepareForReuse: Observable<Void> {
return Observable.of(sentMessage(#selector(Base.prepareForReuse)).map { _ in }, deallocated).merge()
}
var reuseBag: DisposeBag {
MainScheduler.ensureExecutingOnScheduler()
if let bag = objc_getAssociatedObject(base, &prepareForReuseBag) as? DisposeBag {
return bag
}
let bag = DisposeBag()
objc_setAssociatedObject(base, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
_ = sentMessage(#selector(Base.prepareForReuse))
.subscribe(onNext: { [weak base] _ in
guard let `base` = base else { return }
let newBag = DisposeBag()
objc_setAssociatedObject(base, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
})
return bag
}
}
| mit | 09f5f286b297a2912a3a30cb67042104 | 27.808511 | 123 | 0.680945 | 4.767606 | false | false | false | false |
lorentey/swift | test/SILOptimizer/infinite_recursion.swift | 5 | 4171 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify -enable-ownership-stripping-after-serialization
func a() { // expected-warning {{all paths through this function will call itself}}
a()
}
func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
if x != 0 {
b(x)
} else {
b(x+1)
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
if x != 0 {
x += 1
}
return d(x)
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() { // expected-warning {{all paths through this function will call itself}}
while true { // expected-note {{condition always evaluates to true}}
g()
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
while (x < 5) {
x -= 1
}
i(0)
}
func j() -> Int { // expected-warning {{all paths through this function will call itself}}
return 5 + j()
}
func k() -> Any { // expected-warning {{all paths through this function will call itself}}
return type(of: k())
}
@_silgen_name("exit") func exit(_: Int32) -> Never
func l() {
guard Bool.random() else {
exit(0) // no warning; calling 'exit' terminates the program
}
l()
}
func m() { // expected-warning {{all paths through this function will call itself}}
guard Bool.random() else {
fatalError() // we _do_ warn here, because fatalError is a programtermination_point
}
m()
}
enum MyNever {}
func blackHole() -> MyNever { // expected-warning {{all paths through this function will call itself}}
blackHole()
}
@_semantics("programtermination_point")
func terminateMe() -> MyNever {
terminateMe() // no warning; terminateMe is a programtermination_point
}
func n() -> MyNever {
if Bool.random() {
blackHole() // no warning; blackHole() will terminate the program
}
n()
}
func o() -> MyNever {
if Bool.random() {
o()
}
blackHole() // no warning; blackHole() will terminate the program
}
func mayHaveSideEffects() {}
func p() { // expected-warning {{all paths through this function will call itself}}
if Bool.random() {
mayHaveSideEffects() // presence of side-effects doesn't alter the check for the programtermination_point apply
fatalError()
}
p()
}
class S {
convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}}
self.init(a: a)
}
init(a: Int?) {}
static func a() { // expected-warning {{all paths through this function will call itself}}
return a()
}
func b() { // expected-warning {{all paths through this function will call itself}}
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
var bar: String = "hi!"
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
override var bar: String {
get {
return super.bar
}
set { // expected-warning {{all paths through this function will call itself}}
self.bar = newValue
}
}
}
func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}}
if l == nil && r == nil { return true }
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}}
return lhs == rhs
}
func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}}
return (n != 0) ? factorial(n - 1) * n : factorial(1)
}
func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}}
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
}
| apache-2.0 | bad7ae270c846ae58b00506985f6dd00 | 23.109827 | 149 | 0.621913 | 3.499161 | false | false | false | false |
alblue/swift-corelibs-foundation | Foundation/DateInterval.swift | 1 | 8496 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start: Date
/// The end date.
///
/// - precondition: `end >= start`
public var end: Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration: TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
precondition(end >= start, "Reverse intervals are not allowed")
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
public var hashValue: Int {
var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate))
return withUnsafeMutablePointer(to: &buf) { bufferPtr in
let count = MemoryLayout<UInt>.size * 2
return bufferPtr.withMemoryRebound(to: UInt8.self, capacity: count) { bufferBytes in
return Int(bitPattern: CFHashBytes(bufferBytes, CFIndex(count)))
}
}
}
public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "(Start Date) \(start) + (Duration) \(duration) seconds = (End Date) \(end)"
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "start", value: start))
c.append((label: "end", value: end))
c.append((label: "duration", value: duration))
return Mirror(self, children: c, displayStyle: .struct)
}
}
extension DateInterval : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(NSDateInterval.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 | 86dcf307fe7269c230e75e7c27838cd0 | 37.618182 | 327 | 0.633945 | 5.373814 | false | false | false | false |
alexaubry/BulletinBoard | Example/CustomBulletins/PetValidationBulletinItem.swift | 1 | 4357 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
import BLTNBoard
/**
* A bulletin page that allows the user to validate its selection.
*
* This item demonstrates popping to the previous item, and including a collection view inside the page.
*/
@objc public class PetValidationBLTNItem: FeedbackPageBLTNItem {
let dataSource: CollectionDataSource
let animalType: String
let validationHandler: (BLTNItem) -> Void
let selectionFeedbackGenerator = SelectionFeedbackGenerator()
let successFeedbackGenerator = SuccessFeedbackGenerator()
init(dataSource: CollectionDataSource, animalType: String, validationHandler: @escaping (BLTNItem) -> Void) {
self.dataSource = dataSource
self.animalType = animalType
self.validationHandler = validationHandler
super.init(title: "Choose your Favorite")
isDismissable = false
descriptionText = "You chose \(animalType) as your favorite animal type. Here are a few examples of posts in this category."
actionButtonTitle = "Validate"
alternativeButtonTitle = "Change"
}
// MARK: - Interface
var collectionView: UICollectionView?
override public func makeViewsUnderDescription(with interfaceBuilder: BLTNInterfaceBuilder) -> [UIView]? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.minimumInteritemSpacing = 1
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
collectionView.backgroundColor = .white
let collectionWrapper = interfaceBuilder.wrapView(collectionView, width: nil, height: 256, position: .pinnedToEdges)
self.collectionView = collectionView
collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.dataSource = self
collectionView.delegate = self
return [collectionWrapper]
}
override public func tearDown() {
super.tearDown()
collectionView?.dataSource = nil
collectionView?.delegate = nil
}
// MARK: - Touch Events
override public func actionButtonTapped(sender: UIButton) {
// > Play Haptic Feedback
selectionFeedbackGenerator.prepare()
selectionFeedbackGenerator.selectionChanged()
// > Display the loading indicator
manager?.displayActivityIndicator()
// > Wait for a "task" to complete before displaying the next item
let delay = DispatchTime.now() + .seconds(2)
DispatchQueue.main.asyncAfter(deadline: delay) {
// Play success haptic feedback
self.successFeedbackGenerator.prepare()
self.successFeedbackGenerator.success()
// Display next item
self.validationHandler(self)
}
}
public override func alternativeButtonTapped(sender: UIButton) {
// Play selection haptic feedback
selectionFeedbackGenerator.prepare()
selectionFeedbackGenerator.selectionChanged()
// Display previous item
manager?.popItem()
}
}
// MARK: - Collection View
extension PetValidationBLTNItem: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageCollectionViewCell
cell.imageView.image = dataSource.image(at: indexPath.row)
cell.imageView.contentMode = .scaleAspectFill
cell.imageView.clipsToBounds = true
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let squareSideLength = (collectionView.frame.width / 3) - 3
return CGSize(width: squareSideLength, height: squareSideLength)
}
}
| mit | 52c57d98b4a07923a9073743420ea783 | 30.345324 | 167 | 0.70599 | 5.593068 | false | false | false | false |
AnthonyMDev/Nimble | Sources/Nimble/DSL+Wait.swift | 46 | 5290 | import Dispatch
import Foundation
private enum ErrorResult {
case exception(NSException)
case error(Error)
case none
}
/// 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.
internal class NMBWait: NSObject {
// About these kind of lines, `@objc` attributes are only required for Objective-C
// support, so that should be conditional on Darwin platforms and normal Xcode builds
// (non-SwiftPM builds).
#if canImport(Darwin) && !SWIFT_PACKAGE
@objc
internal class func until(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) {
return throwableUntil(timeout: timeout, file: file, line: line) { done in
action(done)
}
}
#else
internal class func until(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) {
return throwableUntil(timeout: timeout, file: file, line: line) { done in
action(done)
}
}
#endif
// Using a throwable closure makes this method not objc compatible.
internal class func throwableUntil(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) throws -> Void) {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let leeway = timeout / 2.0
// swiftlint:disable:next line_length
let result = awaiter.performBlock(file: file, line: line) { (done: @escaping (ErrorResult) -> Void) throws -> Void in
DispatchQueue.main.async {
let capture = NMBExceptionCapture(
handler: ({ exception in
done(.exception(exception))
}),
finally: ({ })
)
capture.tryBlock {
do {
try action {
done(.none)
}
} catch let e {
done(.error(e))
}
}
}
}.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line)
switch result {
case .incomplete: internalError("Reached .incomplete state for waitUntil(...).")
case .blockedRunLoop:
fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway),
file: file, line: line)
case .timedOut:
let pluralize = (timeout == 1 ? "" : "s")
fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line)
case let .raisedException(exception):
fail("Unexpected exception raised: \(exception)")
case let .errorThrown(error):
fail("Unexpected error thrown: \(error)")
case .completed(.exception(let exception)):
fail("Unexpected exception raised: \(exception)")
case .completed(.error(let error)):
fail("Unexpected error thrown: \(error)")
case .completed(.none): // success
break
}
}
#if canImport(Darwin) && !SWIFT_PACKAGE
@objc(untilFile:line:action:)
internal class func until(
_ file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) {
until(timeout: 1, file: file, line: line, action: action)
}
#else
internal class func until(
_ file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) {
until(timeout: 1, file: file, line: line, action: action)
}
#endif
}
internal func blockedRunLoopErrorMessageFor(_ fnName: String, leeway: TimeInterval) -> String {
// swiftlint:disable:next line_length
return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
}
/// Wait asynchronously until the done closure is called or the timeout has been reached.
///
/// @discussion
/// Call the done() closure to indicate the waiting has completed.
///
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func waitUntil(timeout: TimeInterval = AsyncDefaults.Timeout, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) {
NMBWait.until(timeout: timeout, file: file, line: line, action: action)
}
| apache-2.0 | 062c927d34bf63ec972c415cbd9c01c7 | 42.360656 | 381 | 0.587713 | 4.813467 | false | false | false | false |
TBXark/Ruler | Ruler/Modules/Ruler/Views/Plane.swift | 1 | 1993 | //
// Plane.swift
// Ruler
//
// Created by Tbxark on 18/09/2017.
// Copyright © 2017 Tbxark. All rights reserved.
//
import Foundation
import ARKit
class Plane: SCNNode {
var anchor: ARPlaneAnchor
var occlusionNode: SCNNode?
let occlusionPlaneVerticalOffset: Float = -0.01
var focusSquare: FocusSquare?
init(_ anchor: ARPlaneAnchor, _ showDebugVisualization: Bool) {
self.anchor = anchor
super.init()
createOcclusionNode()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(_ anchor: ARPlaneAnchor) {
self.anchor = anchor
updateOcclusionNode()
}
func updateOcclusionSetting() {
if occlusionNode == nil {
createOcclusionNode()
}
}
// MARK: Private
private func createOcclusionNode() {
let occlusionPlane = SCNPlane(width: CGFloat(anchor.extent.x - 0.05), height: CGFloat(anchor.extent.z - 0.05))
let material = SCNMaterial()
material.colorBufferWriteMask = []
material.isDoubleSided = true
occlusionPlane.materials = [material]
occlusionNode = SCNNode()
occlusionNode!.geometry = occlusionPlane
occlusionNode!.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0)
occlusionNode!.position = SCNVector3Make(anchor.center.x, occlusionPlaneVerticalOffset, anchor.center.z)
self.addChildNode(occlusionNode!)
}
private func updateOcclusionNode() {
guard let occlusionNode = occlusionNode, let occlusionPlane = occlusionNode.geometry as? SCNPlane else {
return
}
occlusionPlane.width = CGFloat(anchor.extent.x - 0.05)
occlusionPlane.height = CGFloat(anchor.extent.z - 0.05)
occlusionNode.position = SCNVector3Make(anchor.center.x, occlusionPlaneVerticalOffset, anchor.center.z)
}
}
| mit | 8d6e4c2d80f932791a8f3cfa084286a1 | 27.869565 | 118 | 0.64006 | 4.486486 | false | false | false | false |
PumpMagic/ostrich | gameboy/gameboy/Source/CPUs/Instructions/EXX.swift | 1 | 773 | //
// EXX.swift
// ostrich
//
// Created by Ryan Conway on 3/27/16.
// Copyright © 2016 conwarez. All rights reserved.
//
import Foundation
/// Three-way exchange: exchange three specific pairs of registers
struct EXX: Z80Instruction {
let cycleCount = 0
func runOn(_ cpu: Z80) {
let bcValue = cpu.BC.read()
let bcpValue = cpu.BCp.read()
let deValue = cpu.DE.read()
let depValue = cpu.DEp.read()
let hlValue = cpu.HL.read()
let hlpValue = cpu.HLp.read()
cpu.BC.write(bcpValue)
cpu.BCp.write(bcValue)
cpu.DE.write(depValue)
cpu.DEp.write(deValue)
cpu.HL.write(hlpValue)
cpu.HLp.write(hlValue)
// EXX does not modify flags.
}
}
| mit | 80b46fe7e68ef15aa14c470eed5e4218 | 22.393939 | 66 | 0.581606 | 3.216667 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Foundation/Calendar.swift | 8 | 65739 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
/**
`Calendar` encapsulates information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. It provides information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time.
*/
public struct Calendar : Hashable, Equatable, ReferenceConvertible, _MutableBoxing {
public typealias ReferenceType = NSCalendar
private var _autoupdating: Bool
internal var _handle: _MutableHandle<NSCalendar>
/// Calendar supports many different kinds of calendars. Each is identified by an identifier here.
public enum Identifier {
/// The common calendar in Europe, the Western Hemisphere, and elsewhere.
case gregorian
case buddhist
case chinese
case coptic
case ethiopicAmeteMihret
case ethiopicAmeteAlem
case hebrew
case iso8601
case indian
case islamic
case islamicCivil
case japanese
case persian
case republicOfChina
/// A simple tabular Islamic calendar using the astronomical/Thursday epoch of CE 622 July 15
@available(macOS 10.10, iOS 8.0, *)
case islamicTabular
/// The Islamic Umm al-Qura calendar used in Saudi Arabia. This is based on astronomical calculation, instead of tabular behavior.
@available(macOS 10.10, iOS 8.0, *)
case islamicUmmAlQura
}
/// An enumeration for the various components of a calendar date.
///
/// Several `Calendar` APIs use either a single unit or a set of units as input to a search algorithm.
///
/// - seealso: `DateComponents`
public enum Component {
case era
case year
case month
case day
case hour
case minute
case second
case weekday
case weekdayOrdinal
case quarter
case weekOfMonth
case weekOfYear
case yearForWeekOfYear
case nanosecond
case calendar
case timeZone
}
/// Returns the user's current calendar.
///
/// This calendar does not track changes that the user makes to their preferences.
public static var current : Calendar {
return Calendar(adoptingReference: __NSCalendarCurrent() as! NSCalendar, autoupdating: false)
}
/// A Calendar that tracks changes to user's preferred calendar.
///
/// If mutated, this calendar will no longer track the user's preferred calendar.
///
/// - note: The autoupdating Calendar will only compare equal to another autoupdating Calendar.
public static var autoupdatingCurrent : Calendar {
return Calendar(adoptingReference: __NSCalendarAutoupdating() as! NSCalendar, autoupdating: true)
}
// MARK: -
// MARK: init
/// Returns a new Calendar.
///
/// - parameter identifier: The kind of calendar to use.
public init(identifier: __shared Identifier) {
let result = __NSCalendarCreate(Calendar._toNSCalendarIdentifier(identifier))
_handle = _MutableHandle(adoptingReference: result as! NSCalendar)
_autoupdating = false
}
// MARK: -
// MARK: Bridging
fileprivate init(reference : __shared NSCalendar) {
_handle = _MutableHandle(reference: reference)
if __NSCalendarIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSCalendar, autoupdating: Bool) {
_handle = _MutableHandle(adoptingReference: reference)
_autoupdating = autoupdating
}
// MARK: -
//
/// The identifier of the calendar.
public var identifier : Identifier {
return Calendar._fromNSCalendarIdentifier(_handle.map({ $0.calendarIdentifier }))
}
/// The locale of the calendar.
public var locale : Locale? {
get {
return _handle.map { $0.locale }
}
set {
_applyMutation { $0.locale = newValue }
}
}
/// The time zone of the calendar.
public var timeZone : TimeZone {
get {
return _handle.map { $0.timeZone }
}
set {
_applyMutation { $0.timeZone = newValue }
}
}
/// The first weekday of the calendar.
public var firstWeekday : Int {
get {
return _handle.map { $0.firstWeekday }
}
set {
_applyMutation { $0.firstWeekday = newValue }
}
}
/// The number of minimum days in the first week.
public var minimumDaysInFirstWeek : Int {
get {
return _handle.map { $0.minimumDaysInFirstWeek }
}
set {
_applyMutation { $0.minimumDaysInFirstWeek = newValue }
}
}
/// A list of eras in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["BC", "AD"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var eraSymbols: [String] {
return _handle.map { $0.eraSymbols }
}
/// A list of longer-named eras in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Before Christ", "Anno Domini"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var longEraSymbols: [String] {
return _handle.map { $0.longEraSymbols }
}
/// A list of months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var monthSymbols: [String] {
return _handle.map { $0.monthSymbols }
}
/// A list of shorter-named months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortMonthSymbols: [String] {
return _handle.map { $0.shortMonthSymbols }
}
/// A list of very-shortly-named months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var veryShortMonthSymbols: [String] {
return _handle.map { $0.veryShortMonthSymbols }
}
/// A list of standalone months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var standaloneMonthSymbols: [String] {
return _handle.map { $0.standaloneMonthSymbols }
}
/// A list of shorter-named standalone months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortStandaloneMonthSymbols: [String] {
return _handle.map { $0.shortStandaloneMonthSymbols }
}
/// A list of very-shortly-named standalone months in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var veryShortStandaloneMonthSymbols: [String] {
return _handle.map { $0.veryShortStandaloneMonthSymbols }
}
/// A list of weekdays in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var weekdaySymbols: [String] {
return _handle.map { $0.weekdaySymbols }
}
/// A list of shorter-named weekdays in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortWeekdaySymbols: [String] {
return _handle.map { $0.shortWeekdaySymbols }
}
/// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var veryShortWeekdaySymbols: [String] {
return _handle.map { $0.veryShortWeekdaySymbols }
}
/// A list of standalone weekday names in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var standaloneWeekdaySymbols: [String] {
return _handle.map { $0.standaloneWeekdaySymbols }
}
/// A list of shorter-named standalone weekdays in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortStandaloneWeekdaySymbols: [String] {
return _handle.map { $0.shortStandaloneWeekdaySymbols }
}
/// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var veryShortStandaloneWeekdaySymbols: [String] {
return _handle.map { $0.veryShortStandaloneWeekdaySymbols }
}
/// A list of quarter names in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var quarterSymbols: [String] {
return _handle.map { $0.quarterSymbols }
}
/// A list of shorter-named quarters in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortQuarterSymbols: [String] {
return _handle.map { $0.shortQuarterSymbols }
}
/// A list of standalone quarter names in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var standaloneQuarterSymbols: [String] {
return _handle.map { $0.standaloneQuarterSymbols }
}
/// A list of shorter-named standalone quarters in this calendar, localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`.
/// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th").
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var shortStandaloneQuarterSymbols: [String] {
return _handle.map { $0.shortStandaloneQuarterSymbols }
}
/// The symbol used to represent "AM", localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `"AM"`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var amSymbol: String {
return _handle.map { $0.amSymbol }
}
/// The symbol used to represent "PM", localized to the Calendar's `locale`.
///
/// For example, for English in the Gregorian calendar, returns `"PM"`.
///
/// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`.
public var pmSymbol: String {
return _handle.map { $0.pmSymbol }
}
// MARK: -
//
/// Returns the minimum range limits of the values that a given component can take on in the receiver.
///
/// As an example, in the Gregorian calendar the minimum range of values for the Day component is 1-28.
/// - parameter component: A component to calculate a range for.
/// - returns: The range, or nil if it could not be calculated.
public func minimumRange(of component: Component) -> Range<Int>? {
return _handle.map { Range($0.minimumRange(of: Calendar._toCalendarUnit([component]))) }
}
/// The maximum range limits of the values that a given component can take on in the receive
///
/// As an example, in the Gregorian calendar the maximum range of values for the Day component is 1-31.
/// - parameter component: A component to calculate a range for.
/// - returns: The range, or nil if it could not be calculated.
public func maximumRange(of component: Component) -> Range<Int>? {
return _handle.map { Range($0.maximumRange(of: Calendar._toCalendarUnit([component]))) }
}
@available(*, unavailable, message: "use range(of:in:for:) instead")
public func range(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> NSRange {
fatalError()
}
/// Returns the range of absolute time values that a smaller calendar component (such as a day) can take on in a larger calendar component (such as a month) that includes a specified absolute time.
///
/// You can use this method to calculate, for example, the range the `day` component can take on in the `month` in which `date` lies.
/// - parameter smaller: The smaller calendar component.
/// - parameter larger: The larger calendar component.
/// - parameter date: The absolute time for which the calculation is performed.
/// - returns: The range of absolute time values smaller can take on in larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined).
public func range(of smaller: Component, in larger: Component, for date: Date) -> Range<Int>? {
return _handle.map { Range($0.range(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date)) }
}
@available(*, unavailable, message: "use range(of:in:for:) instead")
public func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool {
fatalError()
}
/// Returns, via two inout parameters, the starting time and duration of a given calendar component that contains a given date.
///
/// - seealso: `range(of:for:)`
/// - seealso: `dateInterval(of:for:)`
/// - parameter component: A calendar component.
/// - parameter start: Upon return, the starting time of the calendar component that contains the date.
/// - parameter interval: Upon return, the duration of the calendar component that contains the date.
/// - parameter date: The specified date.
/// - returns: `true` if the starting time and duration of a component could be calculated, otherwise `false`.
public func dateInterval(of component: Component, start: inout Date, interval: inout TimeInterval, for date: Date) -> Bool {
var nsDate : NSDate?
var ti : TimeInterval = 0
if _handle.map({ $0.range(of: Calendar._toCalendarUnit([component]), start: &nsDate, interval: &ti, for: date) }) {
start = nsDate! as Date
interval = ti
return true
} else {
return false
}
}
/// Returns the starting time and duration of a given calendar component that contains a given date.
///
/// - parameter component: A calendar component.
/// - parameter date: The specified date.
/// - returns: A new `DateInterval` if the starting time and duration of a component could be calculated, otherwise `nil`.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public func dateInterval(of component: Component, for date: Date) -> DateInterval? {
var start : Date = Date(timeIntervalSinceReferenceDate: 0)
var interval : TimeInterval = 0
if self.dateInterval(of: component, start: &start, interval: &interval, for: date) {
return DateInterval(start: start, duration: interval)
} else {
return nil
}
}
/// Returns, for a given absolute time, the ordinal number of a smaller calendar component (such as a day) within a specified larger calendar component (such as a week).
///
/// The ordinality is in most cases not the same as the decomposed value of the component. Typically return values are 1 and greater. For example, the time 00:45 is in the first hour of the day, and for components `hour` and `day` respectively, the result would be 1. An exception is the week-in-month calculation, which returns 0 for days before the first week in the month containing the date.
///
/// - note: Some computations can take a relatively long time.
/// - parameter smaller: The smaller calendar component.
/// - parameter larger: The larger calendar component.
/// - parameter date: The absolute time for which the calculation is performed.
/// - returns: The ordinal number of smaller within larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined).
public func ordinality(of smaller: Component, in larger: Component, for date: Date) -> Int? {
let result = _handle.map { $0.ordinality(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date) }
if result == NSNotFound { return nil }
return result
}
// MARK: -
//
@available(*, unavailable, message: "use dateComponents(_:from:) instead")
public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() }
@available(*, unavailable, message: "use dateComponents(_:from:) instead")
public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() }
@available(*, unavailable, message: "use dateComponents(_:from:) instead")
public func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() }
// MARK: -
//
@available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead")
public func date(byAdding unit: NSCalendar.Unit, value: Int, to date: Date, options: NSCalendar.Options = []) -> Date? { fatalError() }
/// Returns a new `Date` representing the date calculated by adding components to a given date.
///
/// - parameter components: A set of values to add to the date.
/// - parameter date: The starting date.
/// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`.
/// - returns: A new date, or nil if a date could not be calculated with the given input.
public func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = false) -> Date? {
return _handle.map { $0.date(byAdding: components, to: date, options: wrappingComponents ? [.wrapComponents] : []) }
}
@available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead")
public func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() }
/// Returns a new `Date` representing the date calculated by adding an amount of a specific component to a given date.
///
/// - parameter component: A single component to add.
/// - parameter value: The value of the specified component to add.
/// - parameter date: The starting date.
/// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`.
/// - returns: A new date, or nil if a date could not be calculated with the given input.
@available(iOS 8.0, *)
public func date(byAdding component: Component, value: Int, to date: Date, wrappingComponents: Bool = false) -> Date? {
return _handle.map { $0.date(byAdding: Calendar._toCalendarUnit([component]), value: value, to: date, options: wrappingComponents ? [.wrapComponents] : []) }
}
/// Returns a date created from the specified components.
///
/// - parameter components: Used as input to the search algorithm for finding a corresponding date.
/// - returns: A new `Date`, or nil if a date could not be found which matches the components.
public func date(from components: DateComponents) -> Date? {
return _handle.map { $0.date(from: components) }
}
@available(*, unavailable, renamed: "dateComponents(_:from:)")
public func components(_ unitFlags: NSCalendar.Unit, from date: Date) -> DateComponents { fatalError() }
/// Returns all the date components of a date, using the calendar time zone.
///
/// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date.
/// - parameter date: The `Date` to use.
/// - returns: The date components of the specified date.
public func dateComponents(_ components: Set<Component>, from date: Date) -> DateComponents {
return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: date) }
}
@available(*, unavailable, renamed: "dateComponents(in:from:)")
public func components(in timezone: TimeZone, from date: Date) -> DateComponents { fatalError() }
/// Returns all the date components of a date, as if in a given time zone (instead of the `Calendar` time zone).
///
/// The time zone overrides the time zone of the `Calendar` for the purposes of this calculation.
/// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date.
/// - parameter timeZone: The `TimeZone` to use.
/// - parameter date: The `Date` to use.
/// - returns: All components, calculated using the `Calendar` and `TimeZone`.
@available(iOS 8.0, *)
public func dateComponents(in timeZone: TimeZone, from date: Date) -> DateComponents {
return _handle.map { $0.components(in: timeZone, from: date) }
}
@available(*, unavailable, renamed: "dateComponents(_:from:to:)")
public func components(_ unitFlags: NSCalendar.Unit, from startingDate: Date, to resultDate: Date, options opts: NSCalendar.Options = []) -> DateComponents { fatalError() }
/// Returns the difference between two dates.
///
/// - parameter components: Which components to compare.
/// - parameter start: The starting date.
/// - parameter end: The ending date.
/// - returns: The result of calculating the difference from start to end.
public func dateComponents(_ components: Set<Component>, from start: Date, to end: Date) -> DateComponents {
return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) }
}
@available(*, unavailable, renamed: "dateComponents(_:from:to:)")
public func components(_ unitFlags: NSCalendar.Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: NSCalendar.Options = []) -> DateComponents { fatalError() }
/// Returns the difference between two dates specified as `DateComponents`.
///
/// For components which are not specified in each `DateComponents`, but required to specify an absolute date, the base value of the component is assumed. For example, for an `DateComponents` with just a `year` and a `month` specified, a `day` of 1, and an `hour`, `minute`, `second`, and `nanosecond` of 0 are assumed.
/// Calendrical calculations with unspecified `year` or `year` value prior to the start of a calendar are not advised.
/// For each `DateComponents`, if its `timeZone` property is set, that time zone is used for it. If the `calendar` property is set, that is used rather than the receiving calendar, and if both the `calendar` and `timeZone` are set, the `timeZone` property value overrides the time zone of the `calendar` property.
///
/// - parameter components: Which components to compare.
/// - parameter start: The starting date components.
/// - parameter end: The ending date components.
/// - returns: The result of calculating the difference from start to end.
@available(iOS 8.0, *)
public func dateComponents(_ components: Set<Component>, from start: DateComponents, to end: DateComponents) -> DateComponents {
return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) }
}
/// Returns the value for one component of a date.
///
/// - parameter component: The component to calculate.
/// - parameter date: The date to use.
/// - returns: The value for the component.
@available(iOS 8.0, *)
public func component(_ component: Component, from date: Date) -> Int {
return _handle.map { $0.component(Calendar._toCalendarUnit([component]), from: date) }
}
@available(*, unavailable, message: "Use date(from:) instead")
public func date(era: Int, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() }
@available(*, unavailable, message: "Use date(from:) instead")
public func date(era: Int, yearForWeekOfYear: Int, weekOfYear: Int, weekday: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() }
/// Returns the first moment of a given Date, as a Date.
///
/// For example, pass in `Date()`, if you want the start of today.
/// If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.
/// - parameter date: The date to search.
/// - returns: The first moment of the given date.
@available(iOS 8.0, *)
public func startOfDay(for date: Date) -> Date {
return _handle.map { $0.startOfDay(for: date) }
}
@available(*, unavailable, renamed: "compare(_:to:toGranularity:)")
public func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> ComparisonResult { fatalError() }
/// Compares the given dates down to the given component, reporting them `orderedSame` if they are the same in the given component and all larger components, otherwise either `orderedAscending` or `orderedDescending`.
///
/// - parameter date1: A date to compare.
/// - parameter date2: A date to compare.
/// - parameter: component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour.
@available(iOS 8.0, *)
public func compare(_ date1: Date, to date2: Date, toGranularity component: Component) -> ComparisonResult {
return _handle.map { $0.compare(date1, to: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) }
}
@available(*, unavailable, renamed: "isDate(_:equalTo:toGranularity:)")
public func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> Bool { fatalError() }
/// Compares the given dates down to the given component, reporting them equal if they are the same in the given component and all larger components.
///
/// - parameter date1: A date to compare.
/// - parameter date2: A date to compare.
/// - parameter component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour.
/// - returns: `true` if the given date is within tomorrow.
@available(iOS 8.0, *)
public func isDate(_ date1: Date, equalTo date2: Date, toGranularity component: Component) -> Bool {
return _handle.map { $0.isDate(date1, equalTo: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) }
}
/// Returns `true` if the given date is within the same day as another date, as defined by the calendar and calendar's locale.
///
/// - parameter date1: A date to check for containment.
/// - parameter date2: A date to check for containment.
/// - returns: `true` if `date1` and `date2` are in the same day.
@available(iOS 8.0, *)
public func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool {
return _handle.map { $0.isDate(date1, inSameDayAs: date2) }
}
/// Returns `true` if the given date is within today, as defined by the calendar and calendar's locale.
///
/// - parameter date: The specified date.
/// - returns: `true` if the given date is within today.
@available(iOS 8.0, *)
public func isDateInToday(_ date: Date) -> Bool {
return _handle.map { $0.isDateInToday(date) }
}
/// Returns `true` if the given date is within yesterday, as defined by the calendar and calendar's locale.
///
/// - parameter date: The specified date.
/// - returns: `true` if the given date is within yesterday.
@available(iOS 8.0, *)
public func isDateInYesterday(_ date: Date) -> Bool {
return _handle.map { $0.isDateInYesterday(date) }
}
/// Returns `true` if the given date is within tomorrow, as defined by the calendar and calendar's locale.
///
/// - parameter date: The specified date.
/// - returns: `true` if the given date is within tomorrow.
@available(iOS 8.0, *)
public func isDateInTomorrow(_ date: Date) -> Bool {
return _handle.map { $0.isDateInTomorrow(date) }
}
/// Returns `true` if the given date is within a weekend period, as defined by the calendar and calendar's locale.
///
/// - parameter date: The specified date.
/// - returns: `true` if the given date is within a weekend.
@available(iOS 8.0, *)
public func isDateInWeekend(_ date: Date) -> Bool {
return _handle.map { $0.isDateInWeekend(date) }
}
@available(*, unavailable, message: "use dateIntervalOfWeekend(containing:start:interval:) instead")
public func range(ofWeekendStart datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, containing date: Date) -> Bool { fatalError() }
/// Find the range of the weekend around the given date, returned via two by-reference parameters.
///
/// Note that a given entire day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales.
/// - seealso: `dateIntervalOfWeekend(containing:)`
/// - parameter date: The date at which to start the search.
/// - parameter start: When the result is `true`, set
/// - returns: `true` if a date range could be found, and `false` if the date is not in a weekend.
@available(iOS 8.0, *)
public func dateIntervalOfWeekend(containing date: Date, start: inout Date, interval: inout TimeInterval) -> Bool {
var nsDate : NSDate?
var ti : TimeInterval = 0
if _handle.map({ $0.range(ofWeekendStart: &nsDate, interval: &ti, containing: date) }) {
start = nsDate! as Date
interval = ti
return true
} else {
return false
}
}
/// Returns a `DateInterval` of the weekend contained by the given date, or nil if the date is not in a weekend.
///
/// - parameter date: The date contained in the weekend.
/// - returns: A `DateInterval`, or nil if the date is not in a weekend.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public func dateIntervalOfWeekend(containing date: Date) -> DateInterval? {
var nsDate : NSDate?
var ti : TimeInterval = 0
if _handle.map({ $0.range(ofWeekendStart: &nsDate, interval: &ti, containing: date) }) {
return DateInterval(start: nsDate! as Date, duration: ti)
} else {
return nil
}
}
@available(*, unavailable, message: "use nextWeekend(startingAfter:start:interval:direction:) instead")
public func nextWeekendStart(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, options: NSCalendar.Options = [], after date: Date) -> Bool { fatalError() }
/// Returns the range of the next weekend via two inout parameters. The weekend starts strictly after the given date.
///
/// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date.
///
/// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales.
/// - parameter date: The date at which to begin the search.
/// - parameter direction: Which direction in time to search. The default value is `.forward`.
/// - returns: A `DateInterval`, or nil if the weekend could not be found.
@available(iOS 8.0, *)
public func nextWeekend(startingAfter date: Date, start: inout Date, interval: inout TimeInterval, direction: SearchDirection = .forward) -> Bool {
// The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all.
var nsDate : NSDate?
var ti : TimeInterval = 0
if _handle.map({ $0.nextWeekendStart(&nsDate, interval: &ti, options: direction == .backward ? [.searchBackwards] : [], after: date) }) {
start = nsDate! as Date
interval = ti
return true
} else {
return false
}
}
/// Returns a `DateInterval` of the next weekend, which starts strictly after the given date.
///
/// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date.
///
/// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales.
/// - parameter date: The date at which to begin the search.
/// - parameter direction: Which direction in time to search. The default value is `.forward`.
/// - returns: A `DateInterval`, or nil if weekends do not exist in the specific calendar or locale.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public func nextWeekend(startingAfter date: Date, direction: SearchDirection = .forward) -> DateInterval? {
// The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all.
var nsDate : NSDate?
var ti : TimeInterval = 0
if _handle.map({ $0.nextWeekendStart(&nsDate, interval: &ti, options: direction == .backward ? [.searchBackwards] : [], after: date) }) {
/// WARNING: searching backwards is totally broken! 26643365
return DateInterval(start: nsDate! as Date, duration: ti)
} else {
return nil
}
}
// MARK: -
// MARK: Searching
/// The direction in time to search.
public enum SearchDirection {
/// Search for a date later in time than the start date.
case forward
/// Search for a date earlier in time than the start date.
case backward
}
/// Determines which result to use when a time is repeated on a day in a calendar (for example, during a daylight saving transition when the times between 2:00am and 3:00am may happen twice).
public enum RepeatedTimePolicy {
/// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the first occurrence.
case first
/// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the last occurrence.
case last
}
/// A hint to the search algorithm to control the method used for searching for dates.
public enum MatchingPolicy {
/// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the next existing time which exists.
///
/// For example, during a daylight saving transition there may be no 2:37am. The result would then be 3:00am, if that does exist.
case nextTime
/// If specified, and there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the method will return the next existing value of the missing component and preserves the lower components' values (e.g., no 2:37am results in 3:37am, if that exists).
case nextTimePreservingSmallerComponents
/// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the previous existing value of the missing component and preserves the lower components' values.
///
/// For example, during a daylight saving transition there may be no 2:37am. The result would then be 1:37am, if that does exist.
case previousTimePreservingSmallerComponents
/// If specified, the algorithm travels as far forward or backward as necessary looking for a match.
///
/// For example, if searching for Feb 29 in the Gregorian calendar, the algorithm may choose March 1 instead (for example, if the year is not a leap year). If you wish to find the next Feb 29 without the algorithm adjusting the next higher component in the specified `DateComponents`, then use the `strict` option.
/// - note: There are ultimately implementation-defined limits in how far distant the search will go.
case strict
}
@available(*, unavailable, message: "use nextWeekend(startingAfter:matching:matchingPolicy:repeatedTimePolicy:direction:using:) instead")
public func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { fatalError() }
/// Computes the dates which match (or most closely match) a given set of components, and calls the closure once for each of them, until the enumeration is stopped.
///
/// There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result.
///
/// If `direction` is set to `.backward`, this method finds the previous match before the given date. The intent is that the same matches as for a `.forward` search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards).
///
/// If an exact match is not possible, and requested with the `strict` option, nil is passed to the closure and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.)
///
/// Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the `DateComponents` matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers).
///
/// The enumeration is stopped by setting `stop` to `true` in the closure and returning. It is not necessary to set `stop` to `false` to keep the enumeration going.
/// - parameter start: The `Date` at which to start the search.
/// - parameter components: The `DateComponents` to use as input to the search algorithm.
/// - parameter matchingPolicy: Determines the behavior of the search algorithm when the input produces an ambiguous result.
/// - parameter repeatedTimePolicy: Determines the behavior of the search algorithm when the input produces a time that occurs twice on a particular day.
/// - parameter direction: Which direction in time to search. The default value is `.forward`, which means later in time.
/// - parameter block: A closure that is called with search results.
@available(iOS 8.0, *)
public func enumerateDates(startingAfter start: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward, using block: (_ result: Date?, _ exactMatch: Bool, _ stop: inout Bool) -> Void) {
_handle.map {
$0.enumerateDates(startingAfter: start, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) { (result, exactMatch, stop) in
var stopv = false
block(result, exactMatch, &stopv)
if stopv {
stop.pointee = true
}
}
}
}
@available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead")
public func nextDate(after date: Date, matching comps: DateComponents, options: NSCalendar.Options = []) -> Date? { fatalError() }
/// Computes the next date which matches (or most closely matches) a given set of components.
///
/// The general semantics follow those of the `enumerateDates` function.
/// To compute a sequence of results, use the `enumerateDates` function, rather than looping and calling this method with the previous loop iteration's result.
/// - parameter date: The starting date.
/// - parameter components: The components to search for.
/// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`.
/// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`.
/// - parameter direction: Specifies the direction in time to search. Default is `.forward`.
/// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found.
@available(iOS 8.0, *)
public func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? {
return _handle.map { $0.nextDate(after: date, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) }
}
@available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead")
public func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: NSCalendar.Options = []) -> Date? { fatalError() }
// MARK: -
//
@available(*, unavailable, renamed: "date(bySetting:value:of:)")
public func date(bySettingUnit unit: NSCalendar.Unit, value v: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() }
/// Returns a new `Date` representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the component already has that value, this may result in a date which is the same as the given date.
///
/// Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well.
/// If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other components to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year.
/// The exact behavior of this method is implementation-defined. For example, if changing the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? The algorithm will try to produce a result which is in the next-larger component to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For more control over the exact behavior, use `nextDate(after:matching:matchingPolicy:behavior:direction:)`.
@available(iOS 8.0, *)
public func date(bySetting component: Component, value: Int, of date: Date) -> Date? {
return _handle.map { $0.date(bySettingUnit: Calendar._toCalendarUnit([component]), value: value, of: date, options: []) }
}
@available(*, unavailable, message: "use date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) instead")
public func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() }
/// Returns a new `Date` representing the date calculated by setting hour, minute, and second to a given time on a specified `Date`.
///
/// If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date).
/// The intent is to return a date on the same day as the original date argument. This may result in a date which is backward than the given date, of course.
/// - parameter hour: A specified hour.
/// - parameter minute: A specified minute.
/// - parameter second: A specified second.
/// - parameter date: The date to start calculation with.
/// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`.
/// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`.
/// - parameter direction: Specifies the direction in time to search. Default is `.forward`.
/// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found.
@available(iOS 8.0, *)
public func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: MatchingPolicy = .nextTime, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? {
return _handle.map { $0.date(bySettingHour: hour, minute: minute, second: second, of: date, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) }
}
/// Determine if the `Date` has all of the specified `DateComponents`.
///
/// It may be useful to test the return value of `nextDate(after:matching:matchingPolicy:behavior:direction:)` to find out if the components were obeyed or if the method had to fudge the result value due to missing time (for example, a daylight saving time transition).
///
/// - returns: `true` if the date matches all of the components, otherwise `false`.
@available(iOS 8.0, *)
public func date(_ date: Date, matchesComponents components: DateComponents) -> Bool {
return _handle.map { $0.date(date, matchesComponents: components) }
}
// MARK: -
public func hash(into hasher: inout Hasher) {
// We need to make sure autoupdating calendars have the same hash
if _autoupdating {
hasher.combine(false)
} else {
hasher.combine(true)
hasher.combine(_handle.map { $0 })
}
}
// MARK: -
// MARK: Conversion Functions
/// Turn our more-specific options into the big bucket option set of NSCalendar
private static func _toCalendarOptions(matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy, direction: SearchDirection) -> NSCalendar.Options {
var result : NSCalendar.Options = []
switch matchingPolicy {
case .nextTime:
result.insert(.matchNextTime)
case .nextTimePreservingSmallerComponents:
result.insert(.matchNextTimePreservingSmallerUnits)
case .previousTimePreservingSmallerComponents:
result.insert(.matchPreviousTimePreservingSmallerUnits)
case .strict:
result.insert(.matchStrictly)
}
switch repeatedTimePolicy {
case .first:
result.insert(.matchFirst)
case .last:
result.insert(.matchLast)
}
switch direction {
case .backward:
result.insert(.searchBackwards)
case .forward:
break
}
return result
}
internal static func _toCalendarUnit(_ units : Set<Component>) -> NSCalendar.Unit {
let unitMap : [Component : NSCalendar.Unit] =
[.era : .era,
.year : .year,
.month : .month,
.day : .day,
.hour : .hour,
.minute : .minute,
.second : .second,
.weekday : .weekday,
.weekdayOrdinal : .weekdayOrdinal,
.quarter : .quarter,
.weekOfMonth : .weekOfMonth,
.weekOfYear : .weekOfYear,
.yearForWeekOfYear : .yearForWeekOfYear,
.nanosecond : .nanosecond,
.calendar : .calendar,
.timeZone : .timeZone]
var result = NSCalendar.Unit()
for u in units {
result.insert(unitMap[u]!)
}
return result
}
internal static func _toNSCalendarIdentifier(_ identifier : Identifier) -> NSCalendar.Identifier {
if #available(macOS 10.10, iOS 8.0, *) {
let identifierMap : [Identifier : NSCalendar.Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.iso8601 : .ISO8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina,
.islamicTabular : .islamicTabular,
.islamicUmmAlQura : .islamicUmmAlQura]
return identifierMap[identifier]!
} else {
let identifierMap : [Identifier : NSCalendar.Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.iso8601 : .ISO8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina]
return identifierMap[identifier]!
}
}
internal static func _fromNSCalendarIdentifier(_ identifier : NSCalendar.Identifier) -> Identifier {
if #available(macOS 10.10, iOS 8.0, *) {
let identifierMap : [NSCalendar.Identifier : Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.ISO8601 : .iso8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina,
.islamicTabular : .islamicTabular,
.islamicUmmAlQura : .islamicUmmAlQura]
return identifierMap[identifier]!
} else {
let identifierMap : [NSCalendar.Identifier : Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.ISO8601 : .iso8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina]
return identifierMap[identifier]!
}
}
public static func ==(lhs: Calendar, rhs: Calendar) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
// NSCalendar's isEqual is broken (27019864) so we must implement this ourselves
return lhs.identifier == rhs.identifier &&
lhs.locale == rhs.locale &&
lhs.timeZone == rhs.timeZone &&
lhs.firstWeekday == rhs.firstWeekday &&
lhs.minimumDaysInFirstWeek == rhs.minimumDaysInFirstWeek
}
}
}
extension Calendar : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
private var _kindDescription : String {
if self == Calendar.autoupdatingCurrent {
return "autoupdatingCurrent"
} else if self == Calendar.current {
return "current"
} else {
return "fixed"
}
}
public var description: String {
return "\(identifier) (\(_kindDescription))"
}
public var debugDescription : String {
return "\(identifier) (\(_kindDescription))"
}
public var customMirror : Mirror {
let c: [(label: String?, value: Any)] = [
("identifier", identifier),
("kind", _kindDescription),
("locale", locale as Any),
("timeZone", timeZone),
("firstWeekday", firstWeekday),
("minimumDaysInFirstWeek", minimumDaysInFirstWeek),
]
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
extension Calendar : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSCalendar {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) -> Bool {
result = Calendar(reference: input)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCalendar?) -> Calendar {
var result: Calendar?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSCalendar : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Calendar)
}
}
extension Calendar : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
case locale
case timeZone
case firstWeekday
case minimumDaysInFirstWeek
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifierString = try container.decode(String.self, forKey: .identifier)
let identifier = Calendar._fromNSCalendarIdentifier(NSCalendar.Identifier(rawValue: identifierString))
self.init(identifier: identifier)
self.locale = try container.decodeIfPresent(Locale.self, forKey: .locale)
self.timeZone = try container.decode(TimeZone.self, forKey: .timeZone)
self.firstWeekday = try container.decode(Int.self, forKey: .firstWeekday)
self.minimumDaysInFirstWeek = try container.decode(Int.self, forKey: .minimumDaysInFirstWeek)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let identifier = Calendar._toNSCalendarIdentifier(self.identifier).rawValue
try container.encode(identifier, forKey: .identifier)
try container.encode(self.locale, forKey: .locale)
try container.encode(self.timeZone, forKey: .timeZone)
try container.encode(self.firstWeekday, forKey: .firstWeekday)
try container.encode(self.minimumDaysInFirstWeek, forKey: .minimumDaysInFirstWeek)
}
}
| apache-2.0 | 52dbccd7cb0e3baad9254b0c7dbb7d36 | 55.476804 | 874 | 0.662651 | 4.687607 | false | false | false | false |
luosheng/OpenSim | OpenSim/DirectoryWatcher.swift | 1 | 2686 | //
// DirectoryWatcher.swift
// Markdown
//
// Created by Luo Sheng on 15/10/31.
// Copyright © 2015年 Pop Tap. All rights reserved.
//
import Foundation
public class DirectoryWatcher {
enum IOError: Error {
case cannotOpenPath
}
public typealias CompletionCallback = () -> ()
var watchedURL: URL
let eventMask: DispatchSource.FileSystemEvent
public var completionCallback: CompletionCallback?
private var source: DispatchSourceFileSystemObject?
private var directoryChanging = false
private var oldDirectoryInfo = [FileInfo?]()
init(in watchedURL: URL, eventMask: DispatchSource.FileSystemEvent = .write) {
self.watchedURL = watchedURL
self.eventMask = eventMask
}
deinit {
self.stop()
}
public func start() throws {
guard source == nil else {
return
}
let path = watchedURL.path
let fd = open((path as NSString).fileSystemRepresentation, O_EVTONLY)
guard fd >= 0 else {
throw IOError.cannotOpenPath
}
source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: eventMask)
source?.setEventHandler { [weak self] in
self?.waitForDirectoryToFinishChanging()
}
source?.setCancelHandler {
close(fd)
}
source?.resume()
}
public func stop() {
source?.cancel()
source = nil
}
private func waitForDirectoryToFinishChanging() {
if (!directoryChanging) {
directoryChanging = true
oldDirectoryInfo = self.directoryInfo()
let timer = Timer(timeInterval: 0.5, target: self, selector: #selector(checkDirectoryInfo(_:)), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
}
private func directoryInfo() -> [FileInfo?] {
let contents = try? FileManager.default.contentsOfDirectory(at: watchedURL, includingPropertiesForKeys: FileInfo.prefetchedProperties, options: .skipsSubdirectoryDescendants)
return contents?.map { FileInfo(URL: $0) } ?? []
}
@objc private func checkDirectoryInfo(_ timer: Timer) {
let directoryInfo = self.directoryInfo()
directoryChanging = directoryInfo != oldDirectoryInfo
if directoryChanging {
oldDirectoryInfo = directoryInfo
} else {
timer.invalidate()
if let completion = completionCallback {
completion()
}
}
}
}
| mit | eae76038330a6157a5836abbaabc89a8 | 28.163043 | 182 | 0.604174 | 5.149712 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/NotificationTopicItem.swift | 2 | 1144 | //
// NotificationTopicItem.swift
// WSDOT
//
// Copyright (c) 2018 Washington State Department of Transportation
//
// 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 RealmSwift
class NotificationTopicItem: Object {
@objc dynamic var topic: String = ""
@objc dynamic var title: String = ""
@objc dynamic var category: String = ""
@objc dynamic var subscribed: Bool = false
@objc dynamic var delete: Bool = false
override static func primaryKey() -> String? {
return "topic"
}
}
| gpl-3.0 | 9374bc0c2be745368dd635e11700c2b1 | 32.647059 | 72 | 0.703671 | 4.16 | false | false | false | false |
artyom-stv/TextInputKit | TextInputKit/TextInputKit/Code/TextInputFormat/TextInputFormat+Formatter.swift | 1 | 8451 | //
// TextInputFormat+Formatter.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 24/11/2016.
// Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
#endif
public struct FormatterOptions {
#if os(macOS)
/// On macOS, the `tracksCurrentEditorSelection` option enables a better quality of text input formatting for
/// a `Formatter` being binded to an `NSTextField`.
/// (the same quality as it is provided by `TextInputFormat.bind(to:)` on iOS by default).
///
/// On iOS and tvOS, a `Formatter` isn't used to format text input in a `UITextField`.
/// On macOS, to format text input in an `NSTextField`, a `Formatter` is created.
/// `Formatter` API doesn't allow us to distinguish the deleting of a selected character from pressing
/// "Backspace"/"Delete" key without any selection.
/// For example, it doesn't allow to distinguish the following two cases for "1234 5678" text:
/// 1. Pressing a "Backspace" key when the cursor is standing before the character "5";
/// 2. Pressing a "Backspace" key when the character " " is selected.
///
/// If the `tracksCurrentEditorSelection` option is `true`, a `Formatter` created by
/// `TextInputFormat.toFormatter(_:)` finds the current editor (an instance of `NSTextView`) and extracts
/// the `selectedRange` from it.
var tracksCurrentEditorSelection: Bool = false
#endif
public static func `default`() -> FormatterOptions {
return .init()
}
}
public extension TextInputFormat {
/// Creates a `Formatter` with the object type `FormatterObjectValue<Value>`.
///
/// The `FormatterObjectValue<Value>` is used to wrap a `Value` (if it's present) or a string (if no value is
/// deserialized from that string).
///
/// The reason to use a `FormatterObjectValue<Value>` wrapper is the following `Formatter` and `NSTextField`
/// standard behavior:
/// - if we return `false` from the `getObjectValue(_:for:errorDescription:)` method, the `""` value is set to
/// the text field;
/// - if we set the `objectPtr` to `nil` and return `true` from the `getObjectValue(_:for:errorDescription:)`
/// method, the text in the text input is reset.
///
/// Both variants conflict with the desired behavior of the corresponding `TextInputBinding`. So, we have to set
/// the `objectPtr` to a non-nil value and return `true` from the `getObjectValue(_:for:errorDescription:)` method,
/// even if there is no `Value` representing the text in the text input.
///
/// - Returns: The created `Formatter`.
func toFormatter(_ options: FormatterOptions = .default()) -> Formatter {
return FormatterAdapter(self, options)
}
}
private final class FormatterAdapter<Value: Equatable> : Formatter {
init(_ format: TextInputFormat<Value>, _ options: FormatterOptions) {
self.format = format
self.options = options
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
override func string(for object: Any?) -> String? {
guard let object = object else {
return nil
}
guard let objectValue = object as? FormatterObjectValue<Value> else {
fatalError("Unexpected type of an object passed to Formatter.string(for:) (expected: \(String(describing: FormatterObjectValue<Value>.self)), actual: \(String(describing: type(of: object))))")
}
if let value = objectValue.value {
return format.serializer.string(for: value)
}
else {
return objectValue.text
}
}
override func getObjectValue(
_ objectPtr: AutoreleasingUnsafeMutablePointer<AnyObject?>?,
for string: String,
errorDescription errorDescriptionPtr: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
let objectValue: FormatterObjectValue<Value>
do {
let value = try format.serializer.value(for: string)
objectValue = .init(value: value, text: string)
} catch let error {
objectValue = .init(value: nil, text: string)
if let errorDescriptionPtr = errorDescriptionPtr {
errorDescriptionPtr.pointee = (error as CustomStringConvertible).description as NSString
}
}
if let objectPtr = objectPtr {
objectPtr.pointee = objectValue as AnyObject
}
return true
}
override func isPartialStringValid(
_ partialString: String,
newEditingString newStringPtr: AutoreleasingUnsafeMutablePointer<NSString?>?,
errorDescription errorDescriptionPtr: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
fatalError("\(#function) isn't implemented. It is not supported by a `Formatter` created by `TextInputFormat`.")
}
override func isPartialStringValid(
_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>,
proposedSelectedRange proposedSelectedNSRangePtr: NSRangePointer?,
originalString: String,
originalSelectedRange editedNSRange: NSRange,
errorDescription errorDescriptionPtr: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
let editedRange: Range<String.Index> = Range(editedNSRange)!
.sameRange(in: originalString.utf16)
.sameRange(in: originalString)
let originalSelectedRange: Range<String.Index> = {
#if os(macOS)
if options.tracksCurrentEditorSelection {
if let editor: NSText = NSApplication.shared.keyWindow?.currentEditor {
return editor.selectedIndexRange!
}
}
#endif
return editedRange
}()
let editedString = partialStringPtr.pointee as String
let resultingSelectedRange: Range<String.Index> = {
if let proposedSelectedNSRangePtr = proposedSelectedNSRangePtr {
return Range(proposedSelectedNSRangePtr.pointee)!
.sameRange(in: editedString.utf16)
.sameRange(in: editedString)
}
let resultingCursorIndex: String.Index = {
let numberOfCharactersAfterEditedRange: Int = originalString.distance(from: editedRange.upperBound, to: originalString.endIndex)
return editedString.index(editedString.endIndex, offsetBy: -numberOfCharactersAfterEditedRange)
}()
return resultingCursorIndex..<resultingCursorIndex
}()
assert(resultingSelectedRange.isEmpty,
"The proposed selected range after editing text should be empty (a blinking cursor).")
assert(originalString[..<editedRange.lowerBound] == editedString[..<editedRange.lowerBound],
"The strings before and after the editing should have a common prefix.")
assert(originalString[editedRange.upperBound...] == editedString[resultingSelectedRange.lowerBound...],
"The strings before and after the editing should have a common suffix.")
let replacementString: String = {
let editedRangeLowerBoundInEditedString = (editedRange.lowerBound == originalString.startIndex)
? editedString.startIndex
: editedString.index(after: originalString.index(before: editedRange.lowerBound))
return String(editedString[editedRangeLowerBoundInEditedString..<resultingSelectedRange.lowerBound])
}()
let validationResult = format.formatter.validate(
editing: originalString,
withSelection: originalSelectedRange,
replacing: replacementString,
at: editedRange)
switch validationResult {
case .accepted:
return true
case .changed(let newEditedString, let newSelectedRange):
partialStringPtr.pointee = newEditedString as NSString
proposedSelectedNSRangePtr?.pointee = NSRange(newSelectedRange
.sameRange(in: newEditedString.utf16)!
.sameIntRange(in: newEditedString.utf16))
return false
case .rejected:
return false
}
}
private let format: TextInputFormat<Value>
private let options: FormatterOptions
}
| mit | c545f42a7b6a92f51ce235aef2e993e8 | 39.821256 | 204 | 0.65929 | 5.02677 | false | false | false | false |
Esri/arcgis-runtime-tutorials-ios | Basemap Tutorial/swift/MyFirstMapApp/ViewController.swift | 4 | 3130 | /*
Copyright 2014 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import ArcGIS
let kBasemapLayerName = "Basemap Tiled Layer"
class ViewController: UIViewController, AGSMapViewLayerDelegate {
@IBOutlet weak var mapView: AGSMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Add a basemap tiled layer
let url = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer")
let tiledLayer = AGSTiledMapServiceLayer(URL: url)
self.mapView.addMapLayer(tiledLayer, withName: kBasemapLayerName)
//Set the map view's layer delegate
self.mapView.layerDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//MARK: map view layer delegate methods
func mapViewDidLoad(mapView: AGSMapView!) {
//do something now that the map is loaded
//for example, show the current location on the map
mapView.locationDisplay.startDataSource()
}
//MARK: actions
@IBAction func basemapChanged(sender: UISegmentedControl) {
var basemapURL:NSURL!
switch sender.selectedSegmentIndex {
case 0: //gray
basemapURL = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer")
case 1: //oceans
basemapURL = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer")
case 2: //nat geo
basemapURL = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer")
case 3: //topo
basemapURL = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer")
default: //sat
basemapURL = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer")
}
//remove the existing basemap layer
self.mapView.removeMapLayerWithName(kBasemapLayerName)
//add new Layer
let newBasemapLayer = AGSTiledMapServiceLayer(URL: basemapURL)
self.mapView.insertMapLayer(newBasemapLayer, withName: kBasemapLayerName, atIndex: 0);
}
}
| apache-2.0 | f880c74ef017d231a6796da9be8bc364 | 36.710843 | 138 | 0.670927 | 4.650817 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Views/Maps Tab/Map/Map Location Button/MapLocationButtonNib.swift | 1 | 5586 | //
// MapLocationButtonNib.swift
// MEGameTracker
//
// Created by Emily Ivie on 1/15/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import UIKit
final public class MapLocationButtonNib: UIView {
private let minSize = CGSize(width: 25.0, height: 25.0)
private let minVisibleSize = CGSize(width: 7.0, height: 7.0)
@IBOutlet public weak var title: UILabel?
@IBOutlet public weak var titleWidthConstraint: NSLayoutConstraint?
@IBOutlet public weak var button: MapLocationButton?
@IBOutlet public weak var buttonWidthConstraint: NSLayoutConstraint?
@IBOutlet public weak var buttonHeightConstraint: NSLayoutConstraint?
// @IBAction func buttonClicked(_ sender: MapLocationButton) {
// onClick?(self)
// }
private var centerXConstraint: NSLayoutConstraint?
private var centerYConstraint: NSLayoutConstraint?
private var visibleView: UIView?
private var visibleWidthConstraint: NSLayoutConstraint?
private var visibleHeightConstraint: NSLayoutConstraint?
public var mapLocationPoint: MapLocationPoint?
public var sizedMapLocationPoint: MapLocationPoint?
public var pinColor = UIColor.clear
private let unavailablePinColor = UIColor.systemGray
// public var onClick: ((MapLocationButtonNib) -> Void)?
public var isShowPin = false {
didSet { setVisible() }
}
public var zoomScale: CGFloat = 1.0 {
didSet { size() }
}
public override func didMoveToSuperview() {
size()
}
public func set(location: MapLocationable, isShowPin: Bool = false) {
mapLocationPoint = location.mapLocationPoint
title?.text = location.mapLocationType == .map ? location.name : nil
if let mission = location as? Mission, !mission.isAvailableAndParentAvailable
&& (pinColor == UIColor.clear || pinColor == unavailablePinColor) {
pinColor = unavailablePinColor
} else {
pinColor = (location as? Item)?.itemDisplayType?.color ?? MEGameTrackerColor.renegade
}
self.isShowPin = isShowPin
}
public func size(isForce: Bool = false) {
guard let wrapper = superview, let mapLocationPoint = self.sizedMapLocationPoint else { return }
translatesAutoresizingMaskIntoConstraints = false
if isForce {
centerXConstraint?.isActive = false
centerXConstraint = nil
centerYConstraint?.isActive = false
centerYConstraint = nil
}
if centerXConstraint == nil && centerYConstraint == nil {
centerXConstraint = centerXAnchor.constraint(equalTo: wrapper.leftAnchor, constant: mapLocationPoint.x)
centerXConstraint?.isActive = true
centerYConstraint = centerYAnchor.constraint(equalTo: wrapper.topAnchor, constant: mapLocationPoint.y)
centerYConstraint?.isActive = true
}
let useZoomScale: CGFloat = max(zoomScale, 1.0)
// only scale if we are drawing the shape, otherwise stick to map dimensions given.
let baseWidth = mapLocationPoint.width
let useWidth = max(minSize.width / max(useZoomScale, 1.0), baseWidth)
if buttonWidthConstraint == nil {
buttonWidthConstraint = widthAnchor.constraint(equalToConstant: useWidth)
buttonWidthConstraint?.isActive = true
} else {
buttonWidthConstraint?.constant = useWidth
}
let baseHeight = mapLocationPoint.height
let useHeight = max(minSize.height / max(useZoomScale, 1.0), baseHeight)
if buttonHeightConstraint == nil {
buttonHeightConstraint = heightAnchor.constraint(equalToConstant: useHeight)
buttonHeightConstraint?.isActive = true
} else {
buttonHeightConstraint?.constant = useHeight
}
if isShowPin {
if mapLocationPoint.radius != nil {
// don't scale the visible button size - keep original map-scaled size
let diameter = max(minVisibleSize.width, mapLocationPoint.width)
visibleWidthConstraint?.constant = diameter
visibleHeightConstraint?.constant = diameter
visibleView?.layer.cornerRadius = diameter / 2
buttonWidthConstraint?.constant = max(useWidth, diameter)
buttonHeightConstraint?.constant = max(useHeight, diameter)
} else {
visibleWidthConstraint?.constant = bounds.width
visibleHeightConstraint?.constant = bounds.height
}
}
layoutIfNeeded()
}
private func addVisibleView() {
if visibleView == nil, let button = self.button {
let visibleView = UIView()
button.addSubview(visibleView)
visibleView.frame = bounds
visibleView.translatesAutoresizingMaskIntoConstraints = false
visibleView.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
visibleView.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
visibleWidthConstraint = visibleView.widthAnchor.constraint(equalToConstant: bounds.width)
visibleWidthConstraint?.isActive = true
visibleHeightConstraint = visibleView.heightAnchor.constraint(equalToConstant: bounds.height)
visibleHeightConstraint?.isActive = true
self.visibleView = visibleView
}
visibleView?.layer.backgroundColor = pinColor.cgColor
visibleView?.isHidden = false
size()
}
/// Some buttons have a marker on the map already - others need an explicit bg color to show them.
private func setVisible() {
if isShowPin && visibleView == nil {
addVisibleView()
} else if !isShowPin && visibleView != nil {
visibleView?.isHidden = true
}
}
}
extension MapLocationButtonNib {
public class func loadNib(key: MapLocationPointKey) -> MapLocationButtonNib? {
let bundle = Bundle(for: MapLocationButtonNib.self)
if let view = bundle.loadNibNamed("MapLocationButtonNib", owner: self, options: nil)?.first as? MapLocationButtonNib {
view.button?.key = key
return view
}
return nil
}
}
| mit | 64b0b4c4aeb0606b765bc07b7720dd16 | 35.266234 | 120 | 0.750761 | 4.296154 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/Map/MapLocationPoint.swift | 1 | 4794 | //
// MapLocationPoint.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/26/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
public typealias MapLocationPointKey = Duplet<CGFloat, CGFloat>
/// Defines a scalable location marker on a map, either square or circular.
public struct MapLocationPoint: Codable {
enum CodingKeys: String, CodingKey {
case x
case y
case radius
case width
case height
}
// MARK: Properties
public var x: CGFloat
public var y: CGFloat
public var radius: CGFloat?
public var width: CGFloat
public var height: CGFloat
// x, y is altered for rectangles to locate center, so keep original values for encode:
private var _x: CGFloat?
private var _y: CGFloat?
// MARK: Computed Properties
public var cgRect: CGRect { return CGRect(x: x, y: y, width: width, height: height) }
public var cgPoint: CGPoint { return CGPoint(x: x, y: y) }
public var key: MapLocationPointKey { return MapLocationPointKey(x, y) }
// MARK: Initialization
public init(x: CGFloat, y: CGFloat, radius: CGFloat) {
self.x = x
self.y = y
self.radius = radius
self.width = radius * 2
self.height = radius * 2
}
public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.x = x
self.y = y
self.radius = nil
self.width = width
self.height = height
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let x = try container.decode(CGFloat.self, forKey: .x)
let y = try container.decode(CGFloat.self, forKey: .y)
if let radius = try container.decodeIfPresent(CGFloat.self, forKey: .radius) {
self.init(x: x, y: y, radius: radius)
} else {
let width = try container.decode(CGFloat.self, forKey: .width)
let height = try container.decode(CGFloat.self, forKey: .height)
self.init(x: x + width/2, y: y + height/2, width: width, height: height)
self._x = x
self._y = y
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_x ?? x, forKey: .x)
try container.encode(_y ?? y, forKey: .y)
if let radius = self.radius {
try container.encode(radius, forKey: .radius)
} else {
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
}
}
// MARK: Basic Actions
extension MapLocationPoint {
/// Converts a map location point from where it is on a base size map to where it is on an adjusted size map.
public func fromSize(_ oldSize: CGSize, toSize newSize: CGSize) -> MapLocationPoint {
let ratio = newSize.width / oldSize.width
let x = self.x * ratio
let y = self.y * ratio
if let radius = radius {
let r = radius * ratio
return MapLocationPoint(x: x, y: y, radius: r)
} else {
let w = width * ratio
let h = height * ratio
return MapLocationPoint(x: x, y: y, width: w, height: h)
}
}
}
//// MARK: SerializedDataStorable
//extension MapLocationPoint: SerializedDataStorable {
//
// public func getData() -> SerializableData {
// var list: [String: SerializedDataStorable?] = [:]
// if let radius = self.radius {
// list["x"] = "\(x)"
// list["y"] = "\(y)"
// list["radius"] = "\(radius)"
// } else {
// // rect uses top left; convert from center
// list["x"] = "\(x - (width / 2))"
// list["y"] = "\(y - (height / 2))"
// list["width"] = "\(width)"
// list["height"] = "\(height)"
// }
// return SerializableData.safeInit(list)
// }
//
//}
//
//// MARK: SerializedDataRetrievable
//extension MapLocationPoint: SerializedDataRetrievable {
//
// public init?(data: SerializableData?) {
// guard let data = data,
// var x = data["x"]?.cgFloat,
// var y = data["y"]?.cgFloat
// else {
// return nil
// }
//
// if let width = data["width"]?.cgFloat, let height = data["height"]?.cgFloat {
// // rect uses top left; convert to center
// x += (width / 2)
// y += (height / 2)
// self.init(x: x, y: y, width: width, height: height)
// } else {
// self.init(x: x, y: y, radius: data["radius"]?.cgFloat ?? 0)
// }
// }
//
// public mutating func setData(_ data: SerializableData) {}
//}
// MARK: Equatable
extension MapLocationPoint: Equatable {
public static func == (
_ lhs: MapLocationPoint,
_ rhs: MapLocationPoint
) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
| mit | 23980eb247d631ac574911ad15c28377 | 29.528662 | 110 | 0.592739 | 3.609187 | false | false | false | false |
headione/criticalmaps-ios | CriticalMapsKit/Sources/ChatFeature/ChatFeatureCore.swift | 1 | 3914 | import ApiClient
import ComposableArchitecture
import CryptoKit
import Foundation
import Helpers
import IDProvider
import L10n
import Logger
import SharedModels
import UserDefaultsClient
// MARK: State
public struct ChatFeatureState: Equatable {
public var chatMessages: ContentState<[String: ChatMessage]>
public var chatInputState: ChatInputState
public var hasConnectivity: Bool
public init(
chatMessages: ContentState<[String: ChatMessage]> = .loading([:]),
chatInputState: ChatInputState = .init(),
hasConnectivity: Bool = true
) {
self.chatMessages = chatMessages
self.chatInputState = chatInputState
self.hasConnectivity = hasConnectivity
}
}
// MARK: Actions
public enum ChatFeatureAction: Equatable {
case onAppear
case chatInputResponse(Result<LocationAndChatMessages, NSError>)
case chatInput(ChatInputAction)
}
// MARK: Environment
public struct ChatEnvironment {
public var locationsAndChatDataService: LocationsAndChatDataService
public var mainQueue: AnySchedulerOf<DispatchQueue>
public var idProvider: IDProvider
public var uuid: () -> UUID
public var date: () -> Date
public var userDefaultsClient: UserDefaultsClient
public init(
locationsAndChatDataService: LocationsAndChatDataService,
mainQueue: AnySchedulerOf<DispatchQueue>,
idProvider: IDProvider,
uuid: @escaping () -> UUID,
date: @escaping () -> Date,
userDefaultsClient: UserDefaultsClient
) {
self.locationsAndChatDataService = locationsAndChatDataService
self.mainQueue = mainQueue
self.idProvider = idProvider
self.uuid = uuid
self.date = date
self.userDefaultsClient = userDefaultsClient
}
var md5Uuid: String {
Insecure.MD5.hash(data: uuid().uuidString.data(using: .utf8)!)
.map { String(format: "%02hhx", $0) }
.joined()
}
}
// MARK: Reducer
/// Reducer responsible for handling logic from the chat feature.
public let chatReducer = Reducer<ChatFeatureState, ChatFeatureAction, ChatEnvironment>.combine(
chatInputReducer.pullback(
state: \.chatInputState,
action: /ChatFeatureAction.chatInput,
environment: { _ in
ChatInputEnvironment()
}
),
Reducer<ChatFeatureState, ChatFeatureAction, ChatEnvironment> { state, action, environment in
switch action {
case .onAppear:
return environment
.userDefaultsClient
.setChatReadTimeInterval(environment.date().timeIntervalSince1970)
.fireAndForget()
case let .chatInputResponse(.success(response)):
state.chatInputState.isSending = false
state.chatInputState.message.removeAll()
state.chatMessages = .results(response.chatMessages)
return .none
case let .chatInputResponse(.failure(error)):
state.chatInputState.isSending = false
logger.debug("ChatInput Action failed with error: \(error.localizedDescription)")
return .none
case let .chatInput(chatInputAction):
switch chatInputAction {
case .onCommit:
let message = ChatMessagePost(
text: state.chatInputState.message,
timestamp: environment.date().timeIntervalSince1970,
identifier: environment.md5Uuid
)
let body = SendLocationAndChatMessagesPostBody(
device: environment.idProvider.id(),
location: nil,
messages: [message]
)
guard state.hasConnectivity else {
logger.debug("Not sending chat input. No connectivity")
return .none
}
state.chatInputState.isSending = true
return environment.locationsAndChatDataService
.getLocationsAndSendMessages(body)
.receive(on: environment.mainQueue)
.catchToEffect()
.map(ChatFeatureAction.chatInputResponse)
default:
return .none
}
}
}
)
| mit | d0b2b90d93153dcaa3538a75bfa55728 | 28.877863 | 95 | 0.696474 | 4.727053 | false | false | false | false |
yotamoo/Delugion | Example/Tests/GetHostStatusSpec.swift | 1 | 2170 | //
// GetHostStatusSpec.swift
// Delugion_Tests
//
// Created by Yotam Ohayon on 19/10/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Himotoki
@testable import Delugion
class GetHostStatusSpec: QuickSpec {
override func spec() {
let networkManager = NetworkManagerMock()
var delugion: DelugionService!
beforeEach {
delugion = Delugion(networkManager: networkManager,
hostname: "asdf",
port: 8112)
}
describe("getHostStatus") {
it("returns an error when not authenticated") {
networkManager.file = "NotAuthenticated"
var result: Bool?
delugion.getHostStatus(hash: "") {
switch $0 {
case .error(_):
result = false
case .valid(_):
result = true
}
}
expect(result).toEventuallyNot(beNil())
expect(result) == false
}
it("returns a correctly parsed host") {
networkManager.file = "GetHostStatusValidHost"
var result: Host?
delugion.getHostStatus(hash: "asdfasdfsdaf") {
switch $0 {
case .error(_):
fail("returned an error")
case .valid(let host):
result = host
}
}
expect(result).toEventuallyNot(beNil())
expect(result?.hash) == "9d7827e0d8c5146a5618ec253944d9d38a3f8f40"
expect(result?.hostname) == "127.0.0.1"
expect(result?.port) == 58846
expect(result?.status) == "Connected"
expect(result?.version) == "1.3.12"
}
}
}
}
| mit | 913e6d9ed1f67d79dee8340f6e34d153 | 28.310811 | 82 | 0.43799 | 5.213942 | false | false | false | false |
clarkcb/xsearch | swift/swiftsearch/Tests/swiftsearchTests/SearchSettingsTests.swift | 1 | 4267 | //
// SearchSettingsTests.swift
// swiftsearch
//
// Created by Cary Clark on 5/18/15.
// Copyright (c) 2015 Cary Clark. All rights reserved.
//
import Cocoa
import XCTest
import swiftsearch
class SearchSettingsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testDefaultSettings() {
XCTAssert(DefaultSettings.archivesOnly == false, "archivesOnly == false")
XCTAssert(DefaultSettings.colorize == true, "colorize == true")
XCTAssert(DefaultSettings.debug == false, "debug == false")
XCTAssert(DefaultSettings.excludeHidden == true, "excludeHidden == true")
XCTAssert(DefaultSettings.firstMatch == false, "firstMatch == false")
XCTAssert(DefaultSettings.listDirs == false, "listDirs == false")
XCTAssert(DefaultSettings.listFiles == false, "listFiles == false")
XCTAssert(DefaultSettings.listLines == false, "listLines == false")
XCTAssert(DefaultSettings.multiLineSearch == false, "multiLineSearch == false")
XCTAssert(DefaultSettings.printResults == true, "printResults == true")
XCTAssert(DefaultSettings.printUsage == false, "printUsage == false")
XCTAssert(DefaultSettings.printVersion == false, "printVersion == false")
XCTAssert(DefaultSettings.searchArchives == false, "searchArchives == false")
XCTAssert(DefaultSettings.uniqueLines == false, "uniqueLines == false")
XCTAssert(DefaultSettings.verbose == false, "verbose == false")
}
func testInitialSettingsEqualDefaultSettings() {
let settings = SearchSettings()
XCTAssert(settings.archivesOnly == DefaultSettings.archivesOnly, "archivesOnly == false")
XCTAssert(settings.colorize == DefaultSettings.colorize, "colorize == true")
XCTAssert(settings.debug == DefaultSettings.debug, "debug == false")
XCTAssert(settings.excludeHidden == DefaultSettings.excludeHidden, "excludeHidden == true")
XCTAssert(settings.firstMatch == DefaultSettings.firstMatch, "firstMatch == false")
XCTAssert(settings.listDirs == DefaultSettings.listDirs, "listDirs == false")
XCTAssert(settings.listFiles == DefaultSettings.listFiles, "listFiles == false")
XCTAssert(settings.listLines == DefaultSettings.listLines, "listLines == false")
XCTAssert(settings.multiLineSearch == DefaultSettings.multiLineSearch,
"multiLineSearch == false")
XCTAssert(settings.printResults == DefaultSettings.printResults, "printResults == true")
XCTAssert(settings.printUsage == DefaultSettings.printUsage, "printUsage == false")
XCTAssert(settings.printVersion == DefaultSettings.printVersion, "printVersion == false")
XCTAssert(settings.searchArchives == DefaultSettings.searchArchives,
"searchArchives == false")
XCTAssert(settings.uniqueLines == DefaultSettings.uniqueLines, "uniqueLines == false")
XCTAssert(settings.verbose == DefaultSettings.verbose, "verbose == false")
}
func testAddExtensions() {
let settings = SearchSettings()
settings.addInExtension("java")
settings.addInExtension("scala")
settings.addInExtension("cs,fs")
XCTAssert(settings.inExtensions.count == 4)
XCTAssert(settings.inExtensions.contains("java"))
XCTAssert(settings.inExtensions.contains("scala"))
XCTAssert(settings.inExtensions.contains("cs"))
XCTAssert(settings.inExtensions.contains("fs"))
}
func testAddPattern() {
let settings = SearchSettings()
settings.addSearchPattern("Searcher")
}
func testSetArchivesOnly() {
let settings = SearchSettings()
XCTAssertFalse(settings.archivesOnly)
XCTAssertFalse(settings.searchArchives)
settings.archivesOnly = true
XCTAssertTrue(settings.archivesOnly)
XCTAssertTrue(settings.searchArchives)
}
func testSetDebug() {
let settings = SearchSettings()
XCTAssertFalse(settings.debug)
XCTAssertFalse(settings.verbose)
settings.debug = true
XCTAssertTrue(settings.debug)
XCTAssertTrue(settings.verbose)
}
}
| mit | 63180364da1ebeed3829a5689acb7527 | 43.447917 | 99 | 0.686665 | 4.921569 | false | true | false | false |
akesson/LogCentral | Sources/Activity.swift | 1 | 9727 | //
// Activity.swift
//
// Created by Zachary Waldowski on 8/21/16.
// Copyright © 2016 Zachary Waldowski. Licensed under MIT.
//
import os.activity
private final class LegacyActivityContext {
let dsoHandle: UnsafeRawPointer?
let description: UnsafePointer<CChar>
let flags: os_activity_flag_t
init(dsoHandle: UnsafeRawPointer?, description: UnsafePointer<CChar>, flags: os_activity_flag_t) {
self.dsoHandle = dsoHandle
self.description = description
self.flags = flags
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@_silgen_name("_os_activity_create")
private func _os_activity_create(_ dso: UnsafeRawPointer?,
_ description: UnsafePointer<Int8>,
_ parent: Unmanaged<AnyObject>?,
_ flags: os_activity_flag_t) -> AnyObject!
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@_silgen_name("os_activity_apply")
private func _os_activity_apply(_ storage: AnyObject,
_ block: @convention(block) () -> Void)
@_silgen_name("_os_activity_initiate")
private func __os_activity_initiate(_ dso: UnsafeRawPointer?,
_ description: UnsafePointer<Int8>,
_ flags: os_activity_flag_t,
_ block: @convention(block) () -> Void)
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@_silgen_name("os_activity_scope_enter")
private func _os_activity_scope_enter(_ storage: AnyObject,
_ state: UnsafeMutablePointer<os_activity_scope_state_s>)
@_silgen_name("_os_activity_start")
private func __os_activity_start(_ dso: UnsafeRawPointer?,
_ description: UnsafePointer<Int8>,
_ flags: os_activity_flag_t) -> UInt64
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@_silgen_name("os_activity_scope_leave")
private func _os_activity_scope_leave(_ state: UnsafeMutablePointer<os_activity_scope_state_s>)
@_silgen_name("os_activity_end")
private func __os_activity_end(_ state: UInt64)
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
private let OS_ACTIVITY_NONE = unsafeBitCast(dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_os_activity_none"), to: Unmanaged<AnyObject>.self)
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
private let OS_ACTIVITY_CURRENT = unsafeBitCast(dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_os_activity_current"), to: Unmanaged<AnyObject>.self)
internal struct Activity {
/// Support flags for OSActivity.
internal struct Options: OptionSet {
internal let rawValue: UInt32
internal init(rawValue: UInt32) {
self.rawValue = rawValue
}
/// Detach a newly created activity from a parent activity, if any.
///
/// If passed in conjunction with a parent activity, the activity will
/// only note what activity "created" the new one, but will make the
/// new activity a top level activity. This allows seeing what
/// activity triggered work without actually relating the activities.
internal static let detached = Options(rawValue: OS_ACTIVITY_FLAG_DETACHED.rawValue)
/// Will only create a new activity if none present.
///
/// If an activity ID is already present, a new activity will be
/// returned with the same underlying activity ID.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal static let ifNonePresent = Options(rawValue: OS_ACTIVITY_FLAG_IF_NONE_PRESENT.rawValue)
}
private let opaque: AnyObject
/// Creates an activity.
internal init(_ description: StaticString, dso: UnsafeRawPointer? = #dsohandle, options: Options = []) {
self.opaque = description.withUTF8Buffer { (buf: UnsafeBufferPointer<UInt8>) -> AnyObject in
let str = buf.baseAddress!.withMemoryRebound(to: Int8.self, capacity: 8, { $0 })
let flags = os_activity_flag_t(rawValue: options.rawValue)
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return _os_activity_create(dso, str, OS_ACTIVITY_CURRENT, flags)
} else {
return LegacyActivityContext(dsoHandle: dso, description: str, flags: flags)
}
}
}
private func active(execute body: @convention(block) () -> Void) {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
_os_activity_apply(opaque, body)
} else {
let context = opaque as! LegacyActivityContext
__os_activity_initiate(context.dsoHandle, context.description, context.flags, body)
}
}
/// Executes a function body within the context of the activity.
internal func active<Return>(execute body: () throws -> Return) rethrows -> Return {
func impl(execute work: () throws -> Return, recover: (Error) throws -> Return) rethrows -> Return {
var result: Return?
var error: Error?
active {
do {
result = try work()
} catch let e {
error = e
}
}
if let e = error {
return try recover(e)
} else {
return result!
}
}
return try impl(execute: body, recover: { throw $0 })
}
/// Opaque structure created by `Activity.enter()` and restored using
/// `leave()`.
internal struct Scope {
fileprivate var state = os_activity_scope_state_s()
fileprivate init() {}
/// Pops activity state to `self`.
internal mutating func leave() {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
_os_activity_scope_leave(&state)
} else {
UnsafeRawPointer(bitPattern: Int(state.opaque.0)).map(Unmanaged<AnyObject>.fromOpaque)?.release()
__os_activity_end(state.opaque.1)
}
}
}
/// Changes the current execution context to the activity.
///
/// An activity can be created and applied to the current scope by doing:
///
/// var scope = OSActivity("my new activity").enter()
/// defer { scope.leave() }
/// ... do some work ...
///
internal func enter() -> Scope {
var scope = Scope()
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
_os_activity_scope_enter(opaque, &scope.state)
} else {
let context = opaque as! LegacyActivityContext
scope.state.opaque.0 = numericCast(Int(bitPattern: Unmanaged.passRetained(context).toOpaque()))
scope.state.opaque.1 = __os_activity_start(context.dsoHandle, context.description, context.flags)
}
return scope
}
/// Creates an activity.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal init(_ description: StaticString, dso: UnsafeRawPointer? = #dsohandle, parent: Activity, options: Options = []) {
self.opaque = description.withUTF8Buffer { (buf: UnsafeBufferPointer<UInt8>) -> AnyObject in
let str = buf.baseAddress!.withMemoryRebound(to: Int8.self, capacity: 8, { $0 })
let flags = os_activity_flag_t(rawValue: options.rawValue)
return _os_activity_create(dso, str, Unmanaged.passRetained(parent.opaque), flags)
}
}
private init(_ opaque: AnyObject) {
self.opaque = opaque
}
/// An activity with no traits; as a parent, it is equivalent to a
/// detached activity.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal static var none: Activity {
return Activity(OS_ACTIVITY_NONE.takeUnretainedValue())
}
/// The running activity.
///
/// As a parent, the new activity is linked to the current activity, if one
/// is present. If no activity is present, it behaves the same as `.none`.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal static var current: Activity {
return Activity(OS_ACTIVITY_CURRENT.takeUnretainedValue())
}
/// Label an activity auto-generated by UI with a name that is useful for
/// debugging macro-level user actions.
///
/// This function should be called early within the scope of an `IBAction`,
/// before any sub-activities are created. The name provided will be shown
/// in tools in addition to the system-provided name. This API should only
/// be called once, and only on an activity created by the system. These
/// actions help determine workflow of the user in order to reproduce
/// problems that occur.
///
/// For example, a control press and/or menu item selection can be labeled:
///
/// OSActivity.labelUserAction("New mail message")
/// OSActivity.labelUserAction("Empty trash")
///
/// Where the underlying name will be "gesture:" or "menuSelect:".
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
internal static func labelUserAction(_ description: StaticString, dso: UnsafeRawPointer? = #dsohandle) {
description.withUTF8Buffer { (buf: UnsafeBufferPointer<UInt8>) in
let str = buf.baseAddress!.withMemoryRebound(to: Int8.self, capacity: 8, { $0 })
_os_activity_label_useraction(UnsafeMutableRawPointer(mutating: dso!), str)
}
}
}
| mit | 346ceadcc5d62fe602ad988b2b9fbd0a | 42.035398 | 150 | 0.60693 | 4.239756 | false | false | false | false |
janicduplessis/resultscrawler | ios/iOsResultsCrawler/RegisterViewController.swift | 1 | 3506 | //
// RegisterViewController.swift
// iOsResultsCrawler
//
// Created by Charles Vinette on 2015-03-02.
// Copyright (c) 2015 App and Flow. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loading: UIActivityIndicatorView!
@IBAction func backLoginPage(sender: UIButton) {
let loginViewController = LoginViewController()
self.dismissViewControllerAnimated(true , completion: nil) }
let client = Client.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func register(sender: UIButton) {
let firstName = firstNameTextField.text
let lastName = lastNameTextField.text
let email = emailTextField.text
let password = passwordTextField.text
self.loading.startAnimating()
if(firstName != "" && lastName != "" && email != "" && password != ""){
client.register(email, password: password, firstName: firstName, lastName: lastName, callback: {(response) in
if let response = response{
if response.status == RegisterStatus.Ok{
self.loading.stopAnimating()
let signupSuccess = UIAlertController(title: "Compte crée!", message: nil, preferredStyle: .Alert)
let retour = UIAlertAction(title: "Retour", style: .Default, handler: { (retour) -> Void in
self.dismissViewControllerAnimated(true , completion: nil)
})
signupSuccess.addAction(retour)
self.presentViewController(signupSuccess, animated: true, completion: nil)
}
}else{
self.loading.stopAnimating()
let signupFail = UIAlertController(title: "Erreur", message: "Champs vides", preferredStyle: .Alert)
let retourSignup = UIAlertAction(title: "Ok", style: .Default, handler: { (retourSignup) -> Void in
self.dismissViewControllerAnimated(true , completion: nil)
})
signupFail.addAction(retourSignup)
self.presentViewController(signupFail, animated: true, completion: nil)
}
})
}
else{
self.loading.stopAnimating()
let signupFail = UIAlertController(title: "Erreur", message: "Champs vides", preferredStyle: .Alert)
let retourSignup = UIAlertAction(title: "Ok", style: .Default, handler: { (retourSignup) -> Void in
self.dismissViewControllerAnimated(true , completion: nil)
})
signupFail.addAction(retourSignup)
self.presentViewController(signupFail, animated: true, completion: nil)
}
}
}
| mit | 4d543bba106b2dae61ee250f1ee4ee87 | 33.70297 | 122 | 0.555492 | 5.7743 | false | false | false | false |
janniklorenz/MyPlan | MyPlan/MPCalenderLayout.swift | 1 | 7541 | //
// MPCalenderLayout.swift
// MyPlan
//
// Created by Jannik Lorenz on 27.04.15.
// Copyright (c) 2015 Jannik Lorenz. All rights reserved.
//
import UIKit
protocol MPCalenderLayoutDelegate {
func dateForRowAtIndexPath(indexPath: NSIndexPath) -> MPDate
func canMoveRowAtIndexPath(indexPath: NSIndexPath) -> Bool
func didMoveRowAtIndexPath(indexPath: NSIndexPath, toDate: MPDate)
func didDropRowAtIndexPath(indexPath: NSIndexPath, toDate: MPDate)
}
class MPCalenderLayout: UICollectionViewFlowLayout {
var delegate: MPCalenderLayoutDelegate?
let houreHeight: CGFloat = 60
var movingIndexPath: NSIndexPath?
override func prepareLayout() {
super.prepareLayout()
// self.collectionView?.backgroundColor = UIColor.redColor()
var longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongPressGesture:")
self.collectionView?.addGestureRecognizer(longPressGesture)
}
override func collectionViewContentSize() -> CGSize {
return CGSize(width: 320, height: houreHeight*24)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var elements = [UICollectionViewLayoutAttributes]()
for (var i = 0; i < self.collectionView?.numberOfSections(); i++) {
for (var j = 0; j < self.collectionView?.numberOfItemsInSection(i); j++) {
var indexPath = NSIndexPath(forRow: j, inSection: i)
var attr = self.layoutAttributesForItemAtIndexPath(indexPath);
elements.append(attr);
}
}
return elements
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
var attribute = super.layoutAttributesForItemAtIndexPath(indexPath)
var cellDate = delegate?.dateForRowAtIndexPath(indexPath)
println(cellDate?.description)
if let date = cellDate {
var x: CGFloat = 10
var y: CGFloat = houreHeight*CGFloat(date.seconds)/CGFloat(3600)
var rect = CGRectMake(x, y, 320, houreHeight)
attribute.frame = rect;
}
return attribute
}
// MARK: - UILongPressGestureRecognizer
var moveingStartPointInCell: CGPoint?
func handleLongPressGesture(longPress: UILongPressGestureRecognizer) {
if let collectionView = self.collectionView {
switch (longPress.state) {
case .Began:
if let indexPath = collectionView.indexPathForItemAtPoint(longPress.locationInView(collectionView)) {
if self.delegate?.canMoveRowAtIndexPath(indexPath) != false {
movingIndexPath = indexPath
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
moveingStartPointInCell = longPress.locationInView(cell)
UIView.animateWithDuration(0.3) {
cell.transform = CGAffineTransformMakeScale(1.03, 1.03)
}
}
}
}
case .Changed:
if let indexPath = movingIndexPath {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
if let moveingStartPointInCell = moveingStartPointInCell {
println("\(moveingStartPointInCell.y) \(longPress.locationInView(collectionView).y)")
var y = longPress.locationInView(collectionView).y - moveingStartPointInCell.y
if y >= 0 {
cell.frame.origin.y = y
var point = longPress.locationInView(collectionView)
var date = MPDate(seconds: Int( Double(point.y) / Double(houreHeight) * 3600 ))
self.delegate?.didMoveRowAtIndexPath(indexPath, toDate: date)
// if let collectionView = self.collectionView {
//
// dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
//
// while (
// (y < 10 /*|| Int(collectionView.frame.size.height - y) < 10*/) &&
// (collectionView.contentOffset.y <= 0 /*|| Int(collectionView.contentSize.height - collectionView.contentOffset.y) <= 0*/)) {
//
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// //if y < 10 {
// println("up \(collectionView.contentOffset.y)")
// collectionView.contentOffset.y--
// //}
// //else if Int(collectionView.frame.size.height - y) < 10 {
// // println("down \(collectionView.contentOffset.y)")
// // collectionView.contentOffset.y++
// //}
// })
// }
//
// })
//
// }
}
else {
cell.frame.origin.y = 0
}
}
}
}
case .Ended, .Cancelled, .Failed:
if let indexPath = movingIndexPath {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
UIView.animateWithDuration(0.3) {
cell.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}
if longPress.state == .Ended {
if let moveingStartPointInCell = moveingStartPointInCell {
var y = longPress.locationInView(collectionView).y - moveingStartPointInCell.y
var date = MPDate(seconds: Int( Double(y) / Double(houreHeight) * 3600 ))
self.delegate?.didDropRowAtIndexPath(indexPath, toDate: date)
}
}
}
movingIndexPath = nil
moveingStartPointInCell = nil
case .Possible:
print()
break
}
}
}
}
| gpl-2.0 | 2cae3ff870fdbf1986a4411005d54900 | 40.20765 | 170 | 0.456571 | 6.51209 | false | false | false | false |
slashlos/Helium | Helium/Helium/UserSettings.swift | 1 | 4536 | //
// UserSettings.swift
// Helium
//
// Created by Christian Hoffmann on 10/31/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
// Copyright © 2017-2020 Carlos D. Santiago. All rights reserved.
//
import Foundation
internal struct UserSettings {
internal class Setting<T> {
private let key: String
private let defaultValue: T
init(_ userDefaultsKey: String, defaultValue: T) {
self.key = userDefaultsKey
self.defaultValue = defaultValue
}
var keyPath: String {
get {
return self.key
}
}
var `default`: T {
get {
return self.defaultValue
}
set (value) {
self.set(value)
}
}
var value: T {
get {
return self.get()
}
set (value) {
self.set(value)
// Inform all interested parties
NotificationCenter.default.post(name: Notification.Name(rawValue: self.keyPath), object: nil)
}
}
private func get() -> T {
if let value = UserDefaults.standard.object(forKey: self.key) as? T {
return value
} else {
// Sets default value if failed
set(self.defaultValue)
return self.defaultValue
}
}
private func set(_ value: T) {
UserDefaults.standard.set(value as Any, forKey: self.key)
}
}
// Global Defaults keys
static let DisabledMagicURLs = Setting<Bool>("disabledMagicURLs", defaultValue: false)
static let PlaylistThrottle = Setting<Int>("playlistThrottle", defaultValue: 32)
static let HomePageURL = Setting<String>(
"homePageURL",
defaultValue: "https://slashlos.github.io/Helium/helium_start.html"
)
static let HomeStrkURL = Setting<String>(
"homeStrkURL",
defaultValue: "https://slashlos.github.io/Helium/helium_stark.html"
)
static let HelpPageURL = Setting<String>(
"helpPageURL",
defaultValue: "https://slashlos.github.io/Helium/Help/index.html"
)
static let HomePageName = Setting<String>("homePageName", defaultValue: "helium_start")
// NOTE: UserAgent default is loaded at run-time
static let UserAgent = Setting<String>("userAgent", defaultValue:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15")
// Snapshots path loading once
static let SnapshotsURL = Setting<String>("snapshotsURL", defaultValue: "")
// User Defaults keys
static let HistoryName = Setting<String>("historyName", defaultValue:"History")
static let HistoryKeep = Setting<Int>("historyKeep", defaultValue:2048)
static let HistoryList = Setting<String>("historyList", defaultValue:"histories")
static let HistorySaves = Setting<Bool>("historySaves", defaultValue: true)
static let HideAppMenu = Setting<Bool>("hideAppMenu", defaultValue: false)
static let AutoHideTitle = Setting<Bool>("autoHideTitle", defaultValue: true)
static let AutoSaveDocs = Setting<Bool>("autoSaveDocs", defaultValue: true)
static let AutoSaveTime = Setting<TimeInterval>("autoSaveTimeSeconds", defaultValue: 10.0)
static let PromoteHTTPS = Setting<Bool>("promoteHTTPS", defaultValue: false)
static let RestoreDocAttrs = Setting<Bool>("restoreDocAttrs", defaultValue: true)
static let RestoreWebURLs = Setting<Bool>("restoreWebURLs", defaultValue: true)
static let RestoreLocationSvcs = Setting<Bool>("restoreLocationSvcs", defaultValue: true)
static let AcceptWebCookie = Setting<Bool>("acceptWebCookie", defaultValue: true)
static let ShareWebCookies = Setting<Bool>("shareWebCookies", defaultValue: true)
static let StoreWebCookies = Setting<Bool>("storeWebCookies", defaultValue: true)
// User non-document windows to restore
static let KeepListName = Setting<String>("keepList", defaultValue: "Keep")
// Search provider - must match k struct, menu item tags
static let Search = Setting<Int>("search", defaultValue: 1) // Google
static let SearchNames = Setting<String>("webSearches", defaultValue: "WebSearches")
// Developer setting(s)
static let DeveloperExtrasEnabled = Setting<Bool>("developerExtrasEnabled", defaultValue: false)
}
| mit | 6a67c8540f40623a56e7a1dcf7ff1a6b | 39.482143 | 130 | 0.636965 | 4.561368 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/ui/views/phoneid_buttons/CompactPhoneIdLoginButton.swift | 2 | 9501 | //
// CompactPhoneIdLoginButton.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@IBDesignable open class CompactPhoneIdLoginButton: PhoneIdBaseView {
@objc open var phoneNumberE164: String! {
get {
return self.phoneIdModel.e164Format()
}
set {
self.phoneIdModel = NumberInfo(numberE164: newValue)
self.numberInputControl?.setupWithModel(self.phoneIdModel)
self.verifyCodeControl?.setupWithModel(self.phoneIdModel)
}
}
fileprivate(set) var loginButton: PhoneIdLoginButton!
fileprivate(set) var numberInputControl: NumberInputControl!
fileprivate(set) var verifyCodeControl: VerifyCodeControl!
@objc open var titleText:String?{
get{ return loginButton.titleLabel.text}
set{ loginButton.titleLabel.text = newValue}
}
@objc open var placeholderText:String?{
get{ return numberInputControl.numberText.placeholder}
set{ numberInputControl.numberText.placeholder = newValue}
}
@objc public init() {
super.init(frame: CGRect.zero)
prep()
initUI(designtime: false)
}
// init from viewcontroller
@objc public override init(frame: CGRect) {
super.init(frame: frame)
prep()
initUI(designtime: false)
}
// init from interface builder
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prep()
initUI(designtime: false);
}
@objc override open func prepareForInterfaceBuilder() {
self.prep()
initUI(designtime: true);
}
fileprivate class InternalPhoneIdLoginButton: PhoneIdLoginButton{
var loginTouchedBlock: (() -> Void)?
override func loginTouched() { loginTouchedBlock?() }
}
func initUI(designtime:Bool) {
loginButton = InternalPhoneIdLoginButton(frame:CGRect.zero, designtime:designtime)
var subviews:[UIView] = []
if designtime {
subviews = [loginButton]
}else{
phoneIdModel = NumberInfo()
setupNumberInputControl()
setupVerificationCodeControl()
subviews = [loginButton, numberInputControl, verifyCodeControl]
(loginButton as? InternalPhoneIdLoginButton)?.loginTouchedBlock = {
self.numberInputControl.isHidden = false
self.loginButton.isHidden = true
self.numberInputControl.validatePhoneNumber()
self.numberInputControl.becomeFirstResponder()
}
}
for subview in subviews {
subview.translatesAutoresizingMaskIntoConstraints = false
addSubview(subview)
addConstraint(NSLayoutConstraint(item: subview, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: subview, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: subview, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: subview, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0))
subview.isHidden = true
}
loginButton.isHidden = false
}
func prep() {
localizationBundle = phoneIdComponentFactory.localizationBundle
localizationTableName = phoneIdComponentFactory.localizationTableName
colorScheme = phoneIdComponentFactory.colorScheme
let notificator = NotificationCenter.default
notificator.addObserver(self, selector: #selector(CompactPhoneIdLoginButton.doOnSuccessfulLogin), name: NSNotification.Name(rawValue: Notifications.VerificationSuccess), object: nil)
notificator.addObserver(self, selector: #selector(CompactPhoneIdLoginButton.doOnlogout), name: NSNotification.Name(rawValue: Notifications.DidLogout), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func setupNumberInputControl() {
numberInputControl = NumberInputControl(model: phoneIdModel, scheme: colorScheme, bundle: localizationBundle, tableName: localizationTableName)
numberInputControl.numberInputCompleted = { [weak self] (numberInfo) -> Void in
guard let me = self else {return}
me.phoneIdModel = numberInfo
me.verifyCodeControl.phoneIdModel = numberInfo
me.requestAuthentication()
PhoneIdService.sharedInstance.phoneIdWorkflowNumberInputCompleted?(numberInfo)
}
}
func setupVerificationCodeControl() {
verifyCodeControl = VerifyCodeControl(model: phoneIdModel, scheme: colorScheme, bundle: localizationBundle, tableName: self.localizationTableName)
verifyCodeControl.verificationCodeDidCahnge = { [weak self] (code) -> Void in
guard let me = self else {return}
if (code.utf16.count == me.verifyCodeControl.maxVerificationCodeLength) {
PhoneIdService.sharedInstance.phoneIdWorkflowVerificationCodeInputCompleted?(code)
me.phoneIdService.verifyAuthentication(code, info: me.phoneIdModel) { (token, error) -> Void in
guard let me = self else {return}
if (error == nil) {
me.verifyCodeControl.indicateVerificationSuccess() { [weak self] in
guard let me = self else {return}
print("PhoneId login finished")
me.phoneIdService.phoneIdAuthenticationSucceed?(me.phoneIdService.token!)
me.resetControls()
}
} else {
print("PhoneId login cancelled")
me.verifyCodeControl.indicateVerificationFail()
}
}
} else {
me.phoneIdService.abortCall()
}
}
verifyCodeControl.backButtonTapped = {
self.verifyCodeControl.reset()
self.verifyCodeControl.resignFirstResponder()
self.verifyCodeControl.isHidden = true
self.numberInputControl.isHidden = false
self.numberInputControl.validatePhoneNumber()
self.numberInputControl.becomeFirstResponder()
}
verifyCodeControl.requestVoiceCall = {
self.phoneIdService.requestAuthenticationCode(self.phoneIdModel, channel: .call, completion: {
[weak self] (error) -> Void in
if let e = error {
self?.presentErrorMessage(e)
}
})
}
}
func requestAuthentication() {
phoneIdService.requestAuthenticationCode(self.phoneIdModel, completion: {
[weak self] (error) -> Void in
guard let me = self else {return}
if let e = error {
me.presentErrorMessage(e)
} else {
me.numberInputControl.isHidden = true
me.verifyCodeControl.isHidden = false
me.verifyCodeControl.becomeFirstResponder()
me.verifyCodeControl.setupHintTimer()
}
});
}
func presentErrorMessage(_ error: NSError) {
let bundle = self.phoneIdService.componentFactory.localizationBundle
let alert = UIAlertController(title: NSLocalizedString("alert.title.error", bundle: bundle, comment: "Error"), message: "\(error.localizedDescription)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("alert.button.title.dismiss", bundle: bundle, comment: "Dismiss"), style: .cancel, handler: nil))
let presenter: UIViewController = PhoneIdWindow.currentPresenter()
presenter.present(alert, animated: true, completion: nil)
self.numberInputControl.validatePhoneNumber()
}
@objc func doOnSuccessfulLogin() -> Void {
}
@objc func doOnlogout() -> Void {
resetControls()
}
func resetControls() {
if let control = numberInputControl {
control.reset();
control.isHidden = true
control.resignFirstResponder()
}
if let control = verifyCodeControl {
control.reset();
control.isHidden = true
control.resignFirstResponder()
}
self.loginButton?.isHidden = false
}
@objc open override var intrinsicContentSize : CGSize {
return CGSize(width: 280, height: 48)
}
}
| apache-2.0 | 4ffa12df629554088cb40c2eb027a741 | 35.263359 | 206 | 0.634986 | 4.96395 | false | false | false | false |
ALiOSDev/ALTableView | ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/Extension/Array+ALTableView.swift | 1 | 4360 | //
// Array+ALTableView.swift
// ALTableView
//
// Created by lorenzo villarroel perez on 27/3/18.
// Copyright © 2018 lorenzo villarroel perez. All rights reserved.
//
import Foundation
extension Array {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
internal subscript (ALSafe index: Index) -> Element? {
let position: ALPosition = ALPosition.middle(index)
return self[ALSafePosition: position]
}
internal subscript (ALSafePosition position: ALPosition) -> Element? {
let index: Int = self.getRealIndex(operation: .get, position: position)
return indices.contains(index) ? self[index] : nil
}
internal mutating func safeInsert<C>(contentsOf newElements: C, at i: Int) -> Bool where C : Collection, Element == C.Element {
let position: ALPosition = ALPosition.middle(i)
return self.safeInsert(contentsOf: newElements, at: position)
}
internal mutating func safeInsert<C>(contentsOf newElements: C, at position: ALPosition) -> Bool where C : Collection, Element == C.Element {
let index: Int = self.getRealIndex(operation: .insert, position: position)
guard index >= 0 && index <= self.count else {
return false
}
self.insert(contentsOf: newElements, at: index)
return true
}
internal mutating func safeReplace<C>(contentsOf newElements: C, at i: Int) -> Bool where C: Collection, Element == C.Element {
let position: ALPosition = ALPosition.middle(i)
return self.safeReplace(contentsOf: newElements, at: position)
}
internal mutating func safeReplace<C>(contentsOf newElements: C, at position: ALPosition) -> Bool where C: Collection, Element == C.Element {
let initialIndex = self.getRealIndex(operation: .replace, position: position)
let finalIndex = initialIndex + Int(newElements.count)
guard initialIndex >= 0,
finalIndex <= self.count else {
return false
}
let headArray = self[0..<initialIndex]
let tailArray = self[finalIndex..<self.count]
self = Array(headArray + newElements + tailArray)
return true
}
internal mutating func safeDelete(numberOfElements: Int, at i: Int) -> Bool {
let position: ALPosition = ALPosition.middle(i)
return self.safeDelete(numberOfElements: numberOfElements, at: position)
}
internal mutating func safeDelete(numberOfElements: Int, at position: ALPosition) -> Bool {
let initialIndex = self.getRealIndex(operation: .delete, position: position)
let finalIndex = initialIndex + numberOfElements
guard initialIndex >= 0,
finalIndex <= self.count else {
return false
}
let headArray = self[0..<initialIndex]
let tailArray = self[finalIndex..<self.count]
self = Array(headArray + tailArray)
return true
}
private func getRealIndex(operation: ALOperation, position: ALPosition) -> Int {
let indexOperator: ALIndexOperator = self.getIndexOperator(operation: operation, position: position)
return indexOperator.calculateIndex()
}
private func getIndexOperator(operation: ALOperation, position: ALPosition) -> ALIndexOperator {
return operation.getIndexOperator(position: position, numberOfElements: self.count)
}
}
extension Array where Element: Equatable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
internal func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
var found = true
for element in elements {
if !self.contains(element) {
found = false
}
}
return found
}
}
| mit | 901d1a4056db8148eca83a82e9939136 | 33.595238 | 145 | 0.614361 | 4.479959 | false | false | false | false |
yahua/YAHCharts | Source/Charts/Renderers/LegendRenderer.swift | 3 | 20441 | //
// LegendRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartLegendRenderer)
open class LegendRenderer: Renderer
{
/// the legend object this renderer renders
open var legend: Legend?
public init(viewPortHandler: ViewPortHandler?, legend: Legend?)
{
super.init(viewPortHandler: viewPortHandler)
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
open func computeLegend(data: ChartData)
{
guard
let legend = legend,
let viewPortHandler = self.viewPortHandler
else { return }
if !legend.isLegendCustom
{
var entries: [LegendEntry] = []
// loop for building up the colors and labels used in the legend
for i in 0..<data.dataSetCount
{
guard let dataSet = data.getDataSetByIndex(i) else { continue }
var clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.entryCount
// if we have a barchart with stacked bars
if dataSet is IBarChartDataSet &&
(dataSet as! IBarChartDataSet).isStacked
{
let bds = dataSet as! IBarChartDataSet
var sLabels = bds.stackLabels
for j in 0..<min(clrs.count, bds.stackSize)
{
entries.append(
LegendEntry(
label: sLabels[j % sLabels.count],
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is IPieChartDataSet
{
let pds = dataSet as! IPieChartDataSet
for j in 0..<min(clrs.count, entryCount)
{
entries.append(
LegendEntry(
label: (pds.entryForIndex(j) as? PieChartDataEntry)?.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is ICandleChartDataSet &&
(dataSet as! ICandleChartDataSet).decreasingColor != nil
{
let candleDataSet = dataSet as! ICandleChartDataSet
entries.append(
LegendEntry(
label: nil,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.decreasingColor
)
)
entries.append(
LegendEntry(
label: dataSet.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.increasingColor
)
)
}
else
{ // all others
for j in 0..<min(clrs.count, entryCount)
{
let label: String?
// if multiple colors are set for a DataSet, group them
if j < clrs.count - 1 && j < entryCount - 1
{
label = nil
}
else
{ // add label to the last entry
label = dataSet.label
}
entries.append(
LegendEntry(
label: label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
}
}
legend.entries = entries + legend.extraEntries
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
open func renderLegend(context: CGContext)
{
guard
let legend = legend,
let viewPortHandler = self.viewPortHandler
else { return }
if !legend.enabled
{
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
var entries = legend.entries
let defaultFormSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let yEntrySpace = legend.yEntrySpace
let orientation = legend.orientation
let horizontalAlignment = legend.horizontalAlignment
let verticalAlignment = legend.verticalAlignment
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
var originPosX: CGFloat = 0.0
switch horizontalAlignment
{
case .left:
if orientation == .vertical
{
originPosX = xoffset
}
else
{
originPosX = viewPortHandler.contentLeft + xoffset
}
if direction == .rightToLeft
{
originPosX += legend.neededWidth
}
case .right:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth - xoffset
}
else
{
originPosX = viewPortHandler.contentRight - xoffset
}
if direction == .leftToRight
{
originPosX -= legend.neededWidth
}
case .center:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth / 2.0
}
else
{
originPosX = viewPortHandler.contentLeft
+ viewPortHandler.contentWidth / 2.0
}
originPosX += (direction == .leftToRight
? +xoffset
: -xoffset)
// Horizontally layed out legends do the center offset on a line basis,
// So here we offset the vertical ones only.
if orientation == .vertical
{
if direction == .leftToRight
{
originPosX -= legend.neededWidth / 2.0 - xoffset
}
else
{
originPosX += legend.neededWidth / 2.0 - xoffset
}
}
}
switch orientation
{
case .horizontal:
var calculatedLineSizes = legend.calculatedLineSizes
var calculatedLabelSizes = legend.calculatedLabelSizes
var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
switch verticalAlignment
{
case .top:
posY = yoffset
case .bottom:
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
case .center:
posY = (viewPortHandler.chartHeight - legend.neededHeight) / 2.0 + yoffset
}
var lineIndex: Int = 0
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if i < calculatedLabelBreakPoints.count &&
calculatedLabelBreakPoints[i]
{
posX = originPosX
posY += labelLineHeight + yEntrySpace
}
if posX == originPosX &&
horizontalAlignment == .center &&
lineIndex < calculatedLineSizes.count
{
posX += (direction == .rightToLeft
? calculatedLineSizes[lineIndex].width
: -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex += 1
}
let isStacked = e.label == nil // grouped forms have null labels
if drawingForm
{
if direction == .rightToLeft
{
posX -= formSize
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if !isStacked
{
if drawingForm
{
posX += direction == .rightToLeft ? -formToTextSpace : formToTextSpace
}
if direction == .rightToLeft
{
posX -= calculatedLabelSizes[i].width
}
drawLabel(
context: context,
x: posX,
y: posY,
label: e.label!,
font: labelFont,
textColor: labelTextColor)
if direction == .leftToRight
{
posX += calculatedLabelSizes[i].width
}
posX += direction == .rightToLeft ? -xEntrySpace : xEntrySpace
}
else
{
posX += direction == .rightToLeft ? -stackSpace : stackSpace
}
}
case .vertical:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posY: CGFloat = 0.0
switch verticalAlignment
{
case .top:
posY = (horizontalAlignment == .center
? 0.0
: viewPortHandler.contentTop)
posY += yoffset
case .bottom:
posY = (horizontalAlignment == .center
? viewPortHandler.chartHeight
: viewPortHandler.contentBottom)
posY -= legend.neededHeight + yoffset
case .center:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
var posX = originPosX
if drawingForm
{
if direction == .leftToRight
{
posX += stack
}
else
{
posX -= formSize - stack
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if e.label != nil
{
if drawingForm && !wasStacked
{
posX += direction == .leftToRight ? formToTextSpace : -formToTextSpace
}
else if wasStacked
{
posX = originPosX
}
if direction == .rightToLeft
{
posX -= (e.label as NSString!).size(attributes: [NSFontAttributeName: labelFont]).width
}
if !wasStacked
{
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
else
{
posY += labelLineHeight + yEntrySpace
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
// make a step down
posY += labelLineHeight + yEntrySpace
stack = 0.0
}
else
{
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
fileprivate var _formLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
/// Draws the Legend-form at the given position with the color at the given index.
open func drawForm(
context: CGContext,
x: CGFloat,
y: CGFloat,
entry: LegendEntry,
legend: Legend)
{
guard
let formColor = entry.formColor,
formColor != NSUIColor.clear
else { return }
var form = entry.form
if form == .default
{
form = legend.form
}
let formSize = entry.formSize.isNaN ? legend.formSize : entry.formSize
context.saveGState()
defer { context.restoreGState() }
switch form
{
case .none:
// Do nothing
break
case .empty:
// Do not draw, but keep space for the form
break
case .default: fallthrough
case .circle:
context.setFillColor(formColor.cgColor)
context.fillEllipse(in: CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .square:
context.setFillColor(formColor.cgColor)
context.fill(CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .line:
let formLineWidth = entry.formLineWidth.isNaN ? legend.formLineWidth : entry.formLineWidth
let formLineDashPhase = entry.formLineDashPhase.isNaN ? legend.formLineDashPhase : entry.formLineDashPhase
let formLineDashLengths = entry.formLineDashLengths == nil ? legend.formLineDashLengths : entry.formLineDashLengths
context.setLineWidth(formLineWidth)
if formLineDashLengths != nil && formLineDashLengths!.count > 0
{
context.setLineDash(phase: formLineDashPhase, lengths: formLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(formColor.cgColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formSize
_formLineSegmentsBuffer[1].y = y
context.strokeLineSegments(between: _formLineSegmentsBuffer)
}
}
/// Draws the provided label at the given position.
open func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor])
}
}
| mit | 8653213a09e4979abe4a9786dec8bcfa | 34.487847 | 184 | 0.419989 | 7.19247 | false | false | false | false |
tuanphung/LazyTableView | Demo/Demo/Models/Hotel.swift | 2 | 1636 | //
// Copyright (c) 2016 PHUNG ANH TUAN. 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
import SwiftyJSON
class Hotel {
// Properties
var name: String = ""
var imageName: String = ""
var price: Double = 0
var userRating: Double = 0
var rating: Double = 0
init(json: JSON) {
self.name = json["name"].stringValue
self.imageName = json["imageName"].stringValue
self.price = json["price"].doubleValue
self.userRating = json["userRating"].doubleValue
self.rating = json["rating"].doubleValue
}
} | mit | 9c3d1332fe6bf9bc6b7f26058070c3ae | 39.925 | 80 | 0.720049 | 4.506887 | false | false | false | false |
ahoppen/swift | benchmark/single-source/ArrayOfGenericPOD.swift | 10 | 2777 | //===--- ArrayOfGenericPOD.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests creation and destruction of arrays of enum and
// generic type bound to trivial types. It should take the same time as
// ArrayOfPOD. (In practice, it takes a little longer to construct
// the optional arrays).
//
// For comparison, we always create three arrays of 200,000 words.
// An integer enum takes two words.
import TestsUtils
public let benchmarks = [
BenchmarkInfo(
// Renamed benchmark to "2" when IUO test was removed, which
// effectively changed what we're benchmarking here.
name: "ArrayOfGenericPOD2",
runFunction: run_ArrayOfGenericPOD,
tags: [.validation, .api, .Array]),
// Initialize an array of generic POD from a slice.
// This takes a unique path through stdlib customization points.
BenchmarkInfo(
name: "ArrayInitFromSlice",
runFunction: run_initFromSlice,
tags: [.validation, .api, .Array], setUpFunction: createArrayOfPOD)
]
class RefArray<T> {
var array: [T]
init(_ i:T) {
array = [T](repeating: i, count: 100000)
}
}
// Check the performance of destroying an array of enums (optional) where the
// enum has a single payload of trivial type. Destroying the
// elements should be a nop.
@inline(never)
func genEnumArray() {
blackHole(RefArray<Int?>(3))
// should be a nop
}
// Check the performance of destroying an array of structs where the
// struct has multiple fields of trivial type. Destroying the
// elements should be a nop.
struct S<T> {
var x: T
var y: T
}
@inline(never)
func genStructArray() {
blackHole(RefArray<S<Int>>(S(x:3, y:4)))
// should be a nop
}
@inline(never)
public func run_ArrayOfGenericPOD(_ n: Int) {
for _ in 0..<n {
genEnumArray()
genStructArray()
}
}
// --- ArrayInitFromSlice
let globalArray = Array<UInt8>(repeating: 0, count: 4096)
func createArrayOfPOD() {
blackHole(globalArray)
}
@inline(never)
@_optimize(none)
func copyElements<S: Sequence>(_ contents: S) -> [UInt8]
where S.Iterator.Element == UInt8
{
return [UInt8](contents)
}
@inline(never)
public func run_initFromSlice(_ n: Int) {
for _ in 0..<n {
for _ in 0..<1000 {
// Slice off at least one element so the array buffer can't be reused.
blackHole(copyElements(globalArray[0..<4095]))
}
}
}
| apache-2.0 | ebbaa0304cfcce1fff9ceabf3eb71b9d | 26.49505 | 80 | 0.664746 | 3.825069 | false | false | false | false |
icharny/CommonUtils | CommonUtils/StringExtensions.swift | 1 | 4674 | infix operator =~
public extension String {
init(fromData data: Data?) {
if let data = data {
self = data.map { String(format: "%02x", $0) }.joined()
} else {
self = ""
}
}
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = (self as NSString).boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return boundingBox.height
}
func trimWhitespace() -> String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
var localized: String {
return NSLocalizedString(self, comment: "")
}
func localized(_ args: CVarArg...) -> String {
return String(format: localized, arguments: args)
}
func substring(to: Int) -> String {
switch to {
case 0 ... count:
return String(self[startIndex ..< index(startIndex, offsetBy: to)])
default:
return self
}
}
func substring(from: Int) -> String {
switch from {
case 0 ... count:
return String(self[index(startIndex, offsetBy: from) ..< endIndex])
default:
return ""
}
}
func substring(with range: Range<Int>) -> String {
switch (range.lowerBound, range.upperBound) {
case (0 ... count, range.lowerBound ... Int.max):
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: min(range.upperBound, count))
return String(self[start ..< end])
default:
return ""
}
}
func capturedGroups(withRegex pattern: String) -> [String] {
var results = [String]()
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: pattern, options: [])
} catch {
return results
}
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: count))
guard let match = matches.first else { return results }
let lastRangeIndex = match.numberOfRanges - 1
guard lastRangeIndex >= 1 else { return results }
for i in 1 ... lastRangeIndex {
let capturedGroupIndex = match.range(at: i)
let matchedString = (self as NSString).substring(with: capturedGroupIndex)
results.append(matchedString)
}
return results
}
func replacingCharacters(in range: NSRange, with string: String) -> String {
return (self as NSString).replacingCharacters(in: range, with: string)
}
static func isNilOrEmptyString(_ object: Any?) -> Bool {
return object == nil || ((object as? String)?.isEmpty ?? false)
}
func preferredWidth(forFont font: UIFont) -> CGFloat {
return (self as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: font],
context: nil)
.width
}
}
public extension String {
static func =~ (testString: String, regExString: String) -> Bool {
if let regEx = try? NSRegularExpression(pattern: regExString, options: []) {
return regEx.matches(in: testString, options: [], range: NSRange(location: 0, length: testString.count)).count > 0
} else {
return false
}
}
static func * (lhs: String, rhs: Int) -> String {
return (0 ..< rhs).map { _ in lhs }.joined()
}
static func * (lhs: Int, rhs: String) -> String {
return rhs * lhs
}
static func toReadable(_ obj: Any?, indent: Int = 0) -> String {
guard let obj = obj else { return "" }
if let obj = obj as? [AnyHashable: Any] {
return "\(indent > 0 ? "\n" : "")\(" " * indent){\n\(obj.map { "\(" " * (indent + 1))\(String.toReadable($0.key, indent: indent + 1)): \(String.toReadable($0.value, indent: indent + 1))" }.joined(separator: ",\n"))\n\(" " * indent)}"
} else if let obj = obj as? [Any] {
return "[\n\(obj.map { (" " * (indent + 1)) + String.toReadable($0, indent: indent + 1) }.joined(separator: ",\n"))\n\(" " * indent)]"
} else {
return "\(obj)"
}
}
}
| mit | 0a09edc049e86228e7117331bee51bbd | 34.409091 | 248 | 0.56718 | 4.52907 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/UserinfoHeaderTableViewCell.swift | 1 | 2899 | //
// UserinfoHeaderTableViewCell.swift
// Pigeon-project
//
// Created by Roman Mizin on 10/18/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
class UserinfoHeaderTableViewCell: UITableViewCell {
var icon: UIImageView = {
var icon = UIImageView()
icon.translatesAutoresizingMaskIntoConstraints = false
icon.contentMode = .scaleAspectFill
icon.layer.cornerRadius = 32
icon.layer.masksToBounds = true
icon.isUserInteractionEnabled = true
icon.image = UIImage(named: "UserpicIcon")
return icon
}()
var title: UILabel = {
var title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
title.textColor = ThemeManager.currentTheme().generalTitleColor
return title
}()
var subtitle: UILabel = {
var subtitle = UILabel()
subtitle.translatesAutoresizingMaskIntoConstraints = false
subtitle.font = UIFont.systemFont(ofSize: 15)
subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor
return subtitle
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
title.backgroundColor = backgroundColor
icon.backgroundColor = backgroundColor
contentView.addSubview(icon)
icon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
icon.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
icon.widthAnchor.constraint(equalToConstant: 66).isActive = true
icon.heightAnchor.constraint(equalToConstant: 66).isActive = true
contentView.addSubview(title)
title.topAnchor.constraint(equalTo: icon.topAnchor, constant: 0).isActive = true
title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true
title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
title.heightAnchor.constraint(equalToConstant: 33).isActive = true
contentView.addSubview(subtitle)
subtitle.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 0).isActive = true
subtitle.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true
subtitle.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
subtitle.heightAnchor.constraint(equalToConstant: 33).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
icon.image = UIImage(named: "UserpicIcon")
title.text = ""
subtitle.text = ""
}
}
| gpl-3.0 | 1609f8fac5ed64398c72adbb05f3fd0b | 35.683544 | 106 | 0.743961 | 4.936968 | false | false | false | false |
wvteijlingen/Spine | Spine/SerializeOperation.swift | 1 | 6325 | //
// SerializeOperation.swift
// Spine
//
// Created by Ward van Teijlingen on 30-12-14.
// Copyright (c) 2014 Ward van Teijlingen. All rights reserved.
//
import Foundation
import SwiftyJSON
/// A SerializeOperation serializes a JSONAPIDocument to JSON data in the form of Data.
class SerializeOperation: Operation {
fileprivate let resources: [Resource]
let valueFormatters: ValueFormatterRegistry
let keyFormatter: KeyFormatter
var options: SerializationOptions = [.IncludeID]
var result: Failable<Data, SerializerError>?
// MARK: -
init(document: JSONAPIDocument, valueFormatters: ValueFormatterRegistry, keyFormatter: KeyFormatter) {
self.resources = document.data ?? []
self.valueFormatters = valueFormatters
self.keyFormatter = keyFormatter
}
override func main() {
let serializedData: Any
if resources.count == 1 {
serializedData = serializeResource(resources.first!)
} else {
serializedData = resources.map { resource in
serializeResource(resource)
}
}
do {
let serialized = try JSONSerialization.data(withJSONObject: ["data": serializedData], options: [])
result = Failable.success(serialized)
} catch let error as NSError {
result = Failable.failure(SerializerError.jsonSerializationError(error))
}
}
// MARK: Serializing
fileprivate func serializeResource(_ resource: Resource) -> [String: Any] {
Spine.logDebug(.serializing, "Serializing resource \(resource) of type '\(resource.resourceType)' with id '\(resource.id)'")
var serializedData: [String: Any] = [:]
// Serialize ID
if let id = resource.id , options.contains(.IncludeID) {
serializedData["id"] = id as AnyObject?
}
// Serialize type
serializedData["type"] = resource.resourceType as AnyObject?
// Serialize fields
addAttributes(from: resource, to: &serializedData )
addRelationships(from: resource, to: &serializedData)
return serializedData
}
// MARK: Attributes
/// Adds the attributes of the the given resource to the passed serialized data.
///
/// - parameter resource: The resource whose attributes to add.
/// - parameter serializedData: The data to add the attributes to.
fileprivate func addAttributes(from resource: Resource, to serializedData: inout [String: Any]) {
var attributes = [String: Any]();
for case let field as Attribute in resource.fields where field.isReadOnly == false {
let key = keyFormatter.format(field)
Spine.logDebug(.serializing, "Serializing attribute \(field) as '\(key)'")
if let unformattedValue = resource.value(forField: field.name) {
attributes[key] = valueFormatters.formatValue(unformattedValue, forAttribute: field)
} else if(!options.contains(.OmitNullValues)){
attributes[key] = NSNull()
}
}
serializedData["attributes"] = attributes
}
// MARK: Relationships
/// Adds the relationships of the the given resource to the passed serialized data.
///
/// - parameter resource: The resource whose relationships to add.
/// - parameter serializedData: The data to add the relationships to.
fileprivate func addRelationships(from resource: Resource, to serializedData: inout [String: Any]) {
for case let field as Relationship in resource.fields where field.isReadOnly == false {
let key = keyFormatter.format(field)
Spine.logDebug(.serializing, "Serializing relationship \(field) as '\(key)'")
switch field {
case let toOne as ToOneRelationship:
if options.contains(.IncludeToOne) {
addToOneRelationship(resource.value(forField: field.name) as? Resource, to: &serializedData, key: key, type: toOne.linkedType.resourceType)
}
case let toMany as ToManyRelationship:
if options.contains(.IncludeToMany) {
addToManyRelationship(resource.value(forField: field.name) as? ResourceCollection, to: &serializedData, key: key, type: toMany.linkedType.resourceType)
}
default: ()
}
}
}
/// Adds the given resource as a to to-one relationship to the serialized data.
///
/// - parameter linkedResource: The linked resource to add to the serialized data.
/// - parameter serializedData: The data to add the related resource to.
/// - parameter key: The key to add to the serialized data.
/// - parameter type: The resource type of the linked resource as defined on the parent resource.
fileprivate func addToOneRelationship(_ linkedResource: Resource?, to serializedData: inout [String: Any], key: String, type: ResourceType) {
let serializedId: Any
if let resourceId = linkedResource?.id {
serializedId = resourceId
} else {
serializedId = NSNull()
}
let serializedRelationship = [
"data": [
"type": type,
"id": serializedId
]
]
if serializedData["relationships"] == nil {
serializedData["relationships"] = [key: serializedRelationship]
} else {
var relationships = serializedData["relationships"] as! [String: Any]
relationships[key] = serializedRelationship
serializedData["relationships"] = relationships
}
}
/// Adds the given resources as a to to-many relationship to the serialized data.
///
/// - parameter linkedResources: The linked resources to add to the serialized data.
/// - parameter serializedData: The data to add the related resources to.
/// - parameter key: The key to add to the serialized data.
/// - parameter type: The resource type of the linked resource as defined on the parent resource.
fileprivate func addToManyRelationship(_ linkedResources: ResourceCollection?, to serializedData: inout [String: Any], key: String, type: ResourceType) {
var resourceIdentifiers: [ResourceIdentifier] = []
if let resources = linkedResources?.resources {
resourceIdentifiers = resources.filter { $0.id != nil }.map { resource in
return ResourceIdentifier(type: resource.resourceType, id: resource.id!)
}
}
let serializedRelationship = [
"data": resourceIdentifiers.map { $0.toDictionary() }
]
if serializedData["relationships"] == nil {
serializedData["relationships"] = [key: serializedRelationship]
} else {
var relationships = serializedData["relationships"] as! [String: Any]
relationships[key] = serializedRelationship
serializedData["relationships"] = relationships
}
}
}
| mit | a798d3ab42c6c724ff604a01acf54b1a | 33.944751 | 156 | 0.714625 | 4.085917 | false | false | false | false |
banxi1988/Staff | Staff/UIButton+ActionAppearance.swift | 1 | 2020 | //
// UIButton+ActionAppearance.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/3.
// Copyright © 2015年 xiyili. All rights reserved.
//
import Foundation
import DynamicColor
extension UIButton{
func setupAsRedButton(){
backgroundColor = nil
let redColor = AppColors.redColor
let normalBg = AppButtons.backgroundImage(redColor)
let disabledBg = AppButtons.backgroundImage(redColor.desaturateColor(0.35))
setBackgroundImage(normalBg, forState: .Normal)
setBackgroundImage(disabledBg, forState: .Disabled)
setTitleColor(UIColor.whiteColor(), forState: .Normal)
}
func setupAsAccentButton(){
backgroundColor = nil
let highlighBg = AppButtons.backgroundImage(AppColors.accentColor.saturateColor(0.2))
setBackgroundImage(highlighBg, forState: .Highlighted)
setBackgroundImage(AppButtons.accentImage, forState: .Normal)
setBackgroundImage(AppButtons.accentDisabledImage, forState: .Disabled)
setBackgroundImage(AppButtons.accentPressedImage, forState: .Highlighted)
setTitleColor(.whiteColor(),forState:.Normal)
}
func setupAsPrimaryActionButton(){
setupAsAccentButton()
titleLabel?.font = UIFont.systemFontOfSize(18)
}
}
struct AppButtons{
static func backgroundImage(color:UIColor) -> UIImage{
let cornerRadius = AppMetrics.cornerRadius
let size = CGSize(width: 36, height: 36)
let image = UIImage.bx_roundImage(color, size: size, cornerRadius: cornerRadius)
let buttonImage = image.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadius, left: cornerRadius, bottom: cornerRadius, right: cornerRadius))
return buttonImage
}
static let accentImage = AppButtons.backgroundImage(AppColors.accentColor)
static let accentPressedImage = AppButtons.backgroundImage(AppColors.accentColor.darkerColor())
static let accentDisabledImage = AppButtons.backgroundImage(AppColors.accentColor.desaturateColor(0.35))
static let primaryImage = AppButtons.backgroundImage(AppColors.accentColor)
} | mit | f62d2342a8c6ebf817d6b168ca5d4ecf | 35.690909 | 151 | 0.76946 | 4.462389 | false | false | false | false |
jackcook/mozart | Source/Mozart.swift | 1 | 4006 | // Mozart.swift (v. 0.1)
//
// Copyright (c) 2015 Jack Cook
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class Mozart {
class func load(url: String) -> LoadingClass {
let loadingClass = LoadingClass(url: url)
return loadingClass
}
}
class LoadingClass {
var url: String!
var completionBlock: (UIImage -> Void)!
var imageView: UIImageView!
var button: UIButton!
var controlState: UIControlState!
var controlStates: [UIControlState]!
var holderType = ImageHolder.Unknown
init(url: String) {
self.url = url
getImage() { (img) -> Void in
if let cb = self.completionBlock {
self.completionBlock(img)
}
switch self.holderType {
case .ImageView:
self.imageView.image = img
case .ButtonWithoutControlState:
self.button.setImage(img, forState: .Normal)
case .ButtonWithControlState:
self.button.setImage(img, forState: self.controlState)
case .ButtonWithControlStates:
for state in self.controlStates {
self.button.setImage(img, forState: state)
}
case .Unknown:
break
}
}
}
func into(imageView: UIImageView) -> LoadingClass {
self.imageView = imageView
holderType = .ImageView
return self
}
func into(button: UIButton) -> LoadingClass {
self.button = button
holderType = .ButtonWithoutControlState
return self
}
func into(button: UIButton, forState state: UIControlState) -> LoadingClass {
self.button = button
controlState = state
holderType = .ButtonWithControlState
return self
}
func into(button: UIButton, forStates states: [UIControlState]) -> LoadingClass {
self.button = button
controlStates = states
holderType = .ButtonWithControlStates
return self
}
func completion(block: UIImage -> Void) {
completionBlock = block
}
internal func getImage(block: UIImage -> Void) {
let actualUrl = NSURL(string: url)!
let request = NSURLRequest(URL: actualUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)!
block(image)
if (self.completionBlock != nil) {
self.completionBlock(image)
}
} else {
println("Error: \(error.localizedDescription)")
}
}
}
}
enum ImageHolder {
case ImageView, ButtonWithoutControlState, ButtonWithControlState, ButtonWithControlStates, Unknown
}
| mit | b00bd62873ded511c8479f1a87afe414 | 31.836066 | 130 | 0.619571 | 4.903305 | false | false | false | false |
grigaci/WallpapersCollectionView | WallpapersCollectionView/WallpapersCollectionView/Classes/GUI/Photo/BIPhotoViewController.swift | 1 | 2473 | //
// BIPhotoViewController.swift
// WallpapersCollectionView
//
// Created by Bogdan Iusco on 9/29/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import UIKit
class BIPhotoViewController: UIViewController {
lazy var imageView: UIImageView = {
var tmpView = UIImageView()
tmpView.setTranslatesAutoresizingMaskIntoConstraints(false)
return tmpView
}()
lazy var scrollView: UIScrollView = {
var tmpView = UIScrollView()
tmpView.setTranslatesAutoresizingMaskIntoConstraints(false)
return tmpView
}()
var photo: BIPhoto? {
didSet {
if photo != nil {
self.imageView.image = photo?.image()
}
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init()
}
override func viewDidLoad () {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.scrollView);
self.scrollView.addSubview(self.imageView);
self.setupConstraintsScrollView()
self.setupConstraintsImageView()
}
private func setupConstraintsScrollView() {
let viewsDictionary = ["scrollView":self.scrollView]
let constraints_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|",
options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let constraints_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|",
options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(constraints_H)
self.view.addConstraints(constraints_V)
}
private func setupConstraintsImageView() {
let viewsDictionary = ["imageView":self.imageView]
let constraints_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[imageView]|",
options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let constraints_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|",
options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.scrollView.addConstraints(constraints_H)
self.scrollView.addConstraints(constraints_V)
}
}
| mit | d830ea49226a601b0f665a105dafaf33 | 34.328571 | 100 | 0.673676 | 5.22833 | false | false | false | false |
lnds/9d9l | desafio4/swift/Sources/io.swift | 1 | 2580 | import Foundation
func _panic(msg : String) {
print(msg)
exit(-1)
}
class BitInputStream {
var buffer : UInt16 = 0
var pos : Int = 0
var bitsInBuffer : UInt16 = 0
var eof : Bool = false
var bytes : [UInt8] = [UInt8]()
var len : Int = 0
init(inputFile: String) {
if let data = NSData(contentsOfFile: inputFile) {
bytes = [UInt8](repeating: 0, count: data.length)
data.getBytes(&bytes, length: data.length)
len = data.length
}
fillBuffer()
}
func readBool() -> Bool {
if eof {
_panic(msg: "can't read bool from input stream")
}
bitsInBuffer -= 1
let bit = ((buffer >> bitsInBuffer) & 1) == 1
if bitsInBuffer == 0 {
fillBuffer()
}
return bit
}
func readChar() -> UInt8 {
if eof {
_panic(msg: "reading from empty input stream")
}
var x = buffer
if bitsInBuffer == 8 {
fillBuffer()
} else {
x = x << (8 - bitsInBuffer)
let temp = bitsInBuffer
fillBuffer()
bitsInBuffer = temp
x |= buffer >> bitsInBuffer
}
return UInt8(x & 0xFF)
}
func readInt() -> UInt32 {
var x = UInt32(readChar())
x = (x << 8) | UInt32(readChar())
x = (x << 8) | UInt32(readChar())
x = (x << 8) | UInt32(readChar())
return x
}
func fillBuffer() {
if pos == len {
eof = true
} else {
buffer = UInt16(bytes[pos])
bitsInBuffer = 8
pos += 1
}
}
func getBytes() -> [UInt8] {
return bytes
}
}
class BitOutputStream {
var out : Data
var buffer : UInt16 = 0
var bitsInBuffer : UInt16 = 0
var output : String
init(outputFile: String) {
out = Data()
output = outputFile
}
func writeBitc(bit: Character) {
if bit == "0" {
writeBit(bit: 0)
} else if bit == "1" {
writeBit(bit: 1)
} else {
_panic(msg: "argument must be '0' or '1'")
}
}
func writeBit(bit: UInt16) {
if bit != 0 && bit != 1 {
_panic(msg: "argument must be 0 or 1")
}
buffer = (buffer << 1) | bit
bitsInBuffer += 1
if bitsInBuffer == 8 {
clearBuffer()
}
}
func writeByte(byte: UInt16) {
for i in 0..<8 {
let bit = (byte >> (8 - i - 1)) & 1
writeBit(bit: bit)
}
}
func writeInt(i: UInt32) {
writeByte(byte: UInt16((i >> 24) & 0xFF))
writeByte(byte: UInt16((i >> 16) & 0xFF))
writeByte(byte: UInt16((i >> 8) & 0xFF))
writeByte(byte: UInt16((i >> 0) & 0xFF))
}
func clearBuffer() {
if bitsInBuffer == 0 { return }
if bitsInBuffer > 0 {
buffer = buffer << (8 - bitsInBuffer)
}
out.append(UInt8(buffer))
buffer = 0
bitsInBuffer = 0
}
func close() {
let nsdata = NSData(data: out)
nsdata.write(toFile: output, atomically: true)
}
} | mit | dbf02c8ce34c95cf615eef7ecbdc9bfa | 17.176056 | 52 | 0.586434 | 2.701571 | false | false | false | false |
davetobin/pxctest | PXCTestKitTests/Extension/ArrayExtensionTests.swift | 2 | 1224 | //
// ArrayExtensionTests.swift
// pxctest
//
// Created by Johannes Plunien on 23/01/17.
// Copyright © 2017 Johannes Plunien. All rights reserved.
//
import XCTest
@testable import PXCTestKit
class ArrayExtensionTests: XCTestCase {
func testSplitIntoTwo() {
var result = ["foo", "bar", "bla", "fasel", "last"].split(partitions: 2)
var expected = [["foo", "bla", "last"], ["bar", "fasel"]]
repeat {
XCTAssertEqual(result.popLast()!, expected.popLast()!)
} while result.count > 0 && expected.count > 0
}
func testSplitIntoThree() {
var result = ["foo", "bar", "bla", "fasel", "last"].split(partitions: 3)
var expected = [["foo", "fasel"], ["bar", "last"], ["bla"]]
repeat {
XCTAssertEqual(result.popLast()!, expected.popLast()!)
} while result.count > 0 && expected.count > 0
}
func testSplitIntoTen() {
var result = ["foo", "bar", "bla", "fasel", "last"].split(partitions: 10)
var expected = [["foo"], ["bar"], ["bla"], ["fasel"], ["last"]]
repeat {
XCTAssertEqual(result.popLast()!, expected.popLast()!)
} while result.count > 0 && expected.count > 0
}
}
| mit | 0e7b327cf7b7bdc4342ce95e1df99334 | 31.184211 | 81 | 0.567457 | 3.870253 | false | true | false | false |
adtrevor/GeneKit | Sources/GeneKit/GAAgent.swift | 1 | 4728 | import Foundation
public class GAAgent<Chromosome> {
public init(generator:GAGenerator<Chromosome>,
fitnessEvaluator:GAFitnessEvaluator<Chromosome>,
selector:GASelector<Chromosome>,
elitesSelector:GAElitesSelector<Chromosome>?,
crosser:GACrosser<Chromosome>?,
mutator:GAMutator<Chromosome>,
terminator:GATerminator) {
// Initializing values
self.generator = generator
self.fitnessEvaluator = fitnessEvaluator
self.selector = selector
self.elitesSelector = elitesSelector
self.crosser = crosser
self.mutator = mutator
self.terminator = terminator
}
public var generator:GAGenerator<Chromosome>
public var fitnessEvaluator:GAFitnessEvaluator<Chromosome>
public var selector:GASelector<Chromosome>
public var elitesSelector:GAElitesSelector<Chromosome>?
public var crosser:GACrosser<Chromosome>?
public var mutator:GAMutator<Chromosome>
public var terminator:GATerminator
// Evolution observer
public var observer:((_ currentGenerationNumber:Int, _ population:[Chromosome], _ fitnesses:[Double])->())?
/**
Runs the genetic algorithm synchronously
- returns: Evolved solutions and their scores, sorted from best score to the worse
*/
public func solve(usingPopulationSize populationSize:Int) -> [(Chromosome, Double)] {
let generationStartDate = Date()
var generationsCount = 0
// Is initiated with the provided generator
var population = generator.generate(populationSize: populationSize)
// Will be filled inside the loop
var populationFitnesses = [Double]()
// Will get its value during loop evaluation, it is used to dertermine when the terminator condition is reached
var generationIsTerminated:Bool
// This loop repeats until the terminator condition is reached
repeat {
generationsCount += 1
populationFitnesses = fitnessEvaluator.computeFitnesses(of: population)
// If there is an observer it receives each generation
observer?(generationsCount, population, populationFitnesses)
let elites:[Chromosome]? = elitesSelector?.selectElites(in: population, withScores: populationFitnesses)
// The children population size is equel to the populationSize except in case of elitism where less children are needed
let offspringPopulationSize = (populationSize - (elites?.count ?? 0))
// An array containing selected parents that will be bred to gether to create a new offspring
// If there is a crosser than parentsCount will be multiplied by the required number of parents to create one offspring
let selectionMultiplier = crosser?.parentsCount ?? 1
let selectedIndividuals = selector.selectedIndividuals(in: population, fitnesses: populationFitnesses, selectionCount: selectionMultiplier * offspringPopulationSize)
// If there is a crosser then it crosses the selected individuals to create the children, otherwise the nextPopulation will simply represent the fittest individuals
var nextGeneration = crosser?.crossed(individuals: selectedIndividuals) ?? selectedIndividuals
nextGeneration = mutator.mutated(individuals: nextGeneration)
// The current population elements are destroyed but the array keeps its capacity as it will be filled back with the newly generated population
population.removeAll(keepingCapacity: true)
// Adding the new population
population += nextGeneration
// If there are elites we add those too
if let elites = elites {
population += elites
}
// Checking if loop should continue running
switch terminator {
case .elapsedTime(let maximumTime):
generationIsTerminated = Date().timeIntervalSince(generationStartDate) >= maximumTime
case .generationsCount(let maximumGenerations):
generationIsTerminated = maximumGenerations >= generationsCount
}
} while !generationIsTerminated
return Array(zip(population, populationFitnesses)).sorted(by: {$0.1 >= $1.1})
}
}
| apache-2.0 | 445ce6d9cbd113b57fa9e83a4992205e | 41.594595 | 177 | 0.635787 | 5.601896 | false | false | false | false |
xin-wo/kankan | kankan/kankan/Class/VIP/Controller/VIPHomeViewController.swift | 1 | 12640 | //
// VIPHomeViewController.swift
// kankan
//
// Created by Xin on 16/10/24.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import Kingfisher
import Alamofire
class VIPHomeViewController: UIViewController {
// collectionView 懒加载
lazy var collectionView: UICollectionView = {[unowned self] in
// 1.创建 layout
let flowLayout = UICollectionViewFlowLayout()
// flowLayout.itemSize = self.bounds.size
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.scrollDirection = .Vertical
// 2.创建 collectionView
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight - 140), collectionViewLayout: flowLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
collectionView.delegate = self
// collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
collectionView.registerNib(UINib(nibName: "FooterReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer")
collectionView.registerClass(HeaderReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headercell")
collectionView.registerNib(UINib(nibName: "NormalCell", bundle: nil), forCellWithReuseIdentifier: "normal")
collectionView.registerNib(UINib(nibName: "OtherReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "other")
// collectionView.registerClass(FirstCollectionViewCell.self, forCellWithReuseIdentifier: "first")
collectionView.registerNib(UINib(nibName: "VIPHomeCell", bundle: nil), forCellWithReuseIdentifier: "VIPHomeCellId")
collectionView.backgroundColor = UIColor.whiteColor()
return collectionView
}()
var scrNameArray: [String] = []
var subTitleArray: [String] = ["","","","","",""]
//轮播页数据
var dataArray1: [VIPHomeScrModel] = []
//section1数据
var dataArray2: [VIPHomeHotAndNewModel] = []
//section2数据
var dataArray3: [VIPHomeHotAndNewModel] = []
//其余section数据
var dataArray4: [VIPHomeModulesModel] = []
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
configUI()
}
func configUI() {
automaticallyAdjustsScrollViewInsets = false
collectionView.showsVerticalScrollIndicator = false
view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView)
}
func loadData() {
Alamofire.request(.GET, VIPRecUrl).responseJSON { [unowned self] (response) in
if response.result.error == nil {
let keyArray = ["headlinePics", "newRelease", "hotVodRank", "modules"]
for i in 0...3 {
let array = (response.result.value as! NSDictionary)["data"]![keyArray[i]] as! [AnyObject]
for dic in array {
if i == 0 {
let model = VIPHomeScrModel()
model.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
self.dataArray1.append(model)
self.scrNameArray.append(model.image)
} else if i == 1 {
let model = VIPHomeHotAndNewModel()
model.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
self.dataArray2.append(model)
} else if i == 2 {
let model = VIPHomeHotAndNewModel()
model.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
self.dataArray3.append(model)
} else if i == 3 {
let model = VIPHomeModulesModel()
model.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
self.dataArray4.append(model)
}
}
}
self.collectionView.reloadData()
}
}
}
}
//MARK: UICollectionView代理
extension VIPHomeViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 6
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 0
} else if section == 1 {
return 3
} else if section == 2 {
return 3
} else {
if dataArray4.count == 0 {
return 0
} else {
return dataArray4[section-3].movies.count
}
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("VIPHomeCellId", forIndexPath: indexPath) as! VIPHomeCell
if indexPath.section == 0 {
return cell
} else if indexPath.section == 1 {
if dataArray2.count != 0 {
let model = dataArray2[indexPath.row]
cell.posterImage.kf_setImageWithURL((NSURL(string: model.image)), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.descLabel.text = model.subTitle
cell.rankLabel.text = model.score
cell.titleLabel.text = model.title
return cell
}
} else if indexPath.section == 2 {
if dataArray3.count != 0 {
let model = dataArray3[indexPath.row]
cell.posterImage.kf_setImageWithURL((NSURL(string: model.image)), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.descLabel.text = model.subTitle
cell.rankLabel.text = model.score
cell.titleLabel.text = model.title
return cell
}
} else if indexPath.section == 3 {
if dataArray4.count != 0 {
let model = dataArray4[0].movies[indexPath.row]
cell.posterImage.kf_setImageWithURL((NSURL(string: model.image)), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.descLabel.text = model.subTitle
cell.rankLabel.text = model.score
cell.titleLabel.text = model.title
return cell
}
} else if indexPath.section == 4 {
if dataArray4.count != 0 {
let model = dataArray4[1].movies[indexPath.row]
cell.posterImage.kf_setImageWithURL((NSURL(string: model.image)), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.descLabel.text = model.subTitle
cell.rankLabel.text = model.score
cell.titleLabel.text = model.title
return cell
}
} else {
if dataArray4.count != 0 {
let model = dataArray4[2].movies[indexPath.row]
cell.posterImage.kf_setImageWithURL((NSURL(string: model.image)), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.descLabel.text = model.subTitle
cell.rankLabel.text = model.score
cell.titleLabel.text = model.title
return cell
}
}
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
if indexPath.section == 0 {
let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "headercell", forIndexPath: indexPath) as! HeaderReusableView
header.setImages(scrNameArray, textString: subTitleArray)
header.jumpClosure = { [unowned self] (index) in
print("您点击的是第\(index)张图片,视频Id为:\(self.dataArray1[index].movieId)(视频地址已加密)")
}
return header
} else if indexPath.section == 1 {
let other = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "other", forIndexPath: indexPath) as! OtherReusableView
other.categoryLabel.text = "新片首发"
return other
} else if indexPath.section == 2 {
let other = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "other", forIndexPath: indexPath) as! OtherReusableView
other.categoryLabel.text = "热播排行"
return other
} else {
let other = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "other", forIndexPath: indexPath) as! OtherReusableView
if dataArray4.count != 0 {
other.categoryLabel.text = dataArray4[(indexPath.section-1)%(dataArray4.count)].moduleName
}
return other
}
} else {
let footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "footer", forIndexPath: indexPath)
return footer
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: (screenWidth-20)/3, height: (screenHeight-100)/3)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: screenWidth, height: (screenHeight-100)/3)
}
return CGSize(width: screenWidth, height: 30)
}
/*返回第section组collectionView尾部视图的尺寸
*/
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 0 {
return CGSize()
}
return CGSize(width: screenWidth, height: 1)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}
//页面跳转
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let VC = DetailViewController()
VC.URLString = "http://wvideo.spriteapp.cn/video/2016/0328/56f8ec01d9bfe_wpd.mp4"
VC.title = "蝙蝠侠大战超人"
VC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(VC, animated: true)
}
}
| mit | 5980824df60c9aed54375d73f7928aa4 | 39.947541 | 203 | 0.590039 | 5.752649 | false | false | false | false |
KrauseFx/fastlane | snapshot/lib/assets/SnapshotHelperXcode8.swift | 14 | 6155 | //
// SnapshotHelperXcode8.swift
// Example
//
// Created by Felix Krause on 10/8/15.
//
// -----------------------------------------------------
// IMPORTANT: When modifying this file, make sure to
// increment the version number at the very
// bottom of the file to notify users about
// the new SnapshotHelperXcode8.swift
// -----------------------------------------------------
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
@available(*, deprecated, message: "use setupSnapshot: instead")
func setLanguage(_ app: XCUIApplication) {
setupSnapshot(app)
}
func setupSnapshot(_ app: XCUIApplication) {
Snapshot.setupSnapshot(app)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
open class Snapshot: NSObject {
open class func setupSnapshot(_ app: XCUIApplication) {
setLanguage(app)
setLocale(app)
setLaunchArguments(app)
}
class func setLanguage(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("language.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLocale(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
} catch {
print("Couldn't detect/set locale...")
}
if locale.isEmpty {
locale = Locale(identifier: deviceLanguage).identifier
}
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
class func setLaunchArguments(_ app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
open class func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work
sleep(1) // Waiting for the animation to be finished (kind of)
#if os(tvOS)
XCUIApplication().childrenMatchingType(.Browser).count
#elseif os(OSX)
XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
#else
XCUIDevice.shared().orientation = .unknown
#endif
}
class func waitForLoadingIndicatorToDisappear() {
#if os(tvOS)
return
#endif
let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other)
while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) {
sleep(1)
print("Waiting for loading indicator to disappear...")
}
}
class func pathPrefix() -> URL? {
let homeDir: URL
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
guard let user = ProcessInfo().environment["USER"] else {
print("Couldn't find Snapshot configuration files - can't detect current user ")
return nil
}
guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else {
print("Couldn't find Snapshot configuration files - can't detect `Users` dir")
return nil
}
homeDir = usersDir.appendingPathComponent(user)
#else
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
print("Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable.")
return nil
}
guard let homeDirUrl = URL(string: simulatorHostHome) else {
print("Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?")
return nil
}
homeDir = URL(fileURLWithPath: homeDirUrl.path)
#endif
return homeDir.appendingPathComponent("Library/Caches/tools.fastlane")
}
}
extension XCUIElement {
var isLoadingIndicator: Bool {
let allowListedLoaders = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
if allowListedLoaders.contains(self.identifier) {
return false
}
return self.frame.size == CGSize(width: 10, height: 20)
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperXcode8Version [1.5]
| mit | 6608ab5800fa3a813bae30b0295bb6b0 | 34.784884 | 142 | 0.611373 | 5.090984 | false | false | false | false |
yjiang28/Hackers | cordova/plugins/cordova-plugin-iosrtc/src/iosrtcPlugin.swift | 1 | 31155 | import Foundation
import AVFoundation
@objc(iosrtcPlugin) // This class must be accesible from Objective-C.
class iosrtcPlugin : CDVPlugin {
// RTCPeerConnectionFactory single instance.
var rtcPeerConnectionFactory: RTCPeerConnectionFactory!
// Single PluginGetUserMedia instance.
var pluginGetUserMedia: PluginGetUserMedia!
// PluginRTCPeerConnection dictionary.
var pluginRTCPeerConnections: [Int : PluginRTCPeerConnection]!
// PluginMediaStream dictionary.
var pluginMediaStreams: [String : PluginMediaStream]!
// PluginMediaStreamTrack dictionary.
var pluginMediaStreamTracks: [String : PluginMediaStreamTrack]!
// PluginMediaStreamRenderer dictionary.
var pluginMediaStreamRenderers: [Int : PluginMediaStreamRenderer]!
// Dispatch queue for serial operations.
var queue: dispatch_queue_t!
// This is just called if <param name="onload" value="true" /> in plugin.xml.
override func pluginInitialize() {
NSLog("iosrtcPlugin#pluginInitialize()")
// Make the web view transparent
self.webView!.opaque = false
self.webView!.backgroundColor = UIColor.clearColor()
pluginMediaStreams = [:]
pluginMediaStreamTracks = [:]
pluginMediaStreamRenderers = [:]
queue = dispatch_queue_create("cordova-plugin-iosrtc", DISPATCH_QUEUE_SERIAL)
pluginRTCPeerConnections = [:]
// Initialize DTLS stuff.
RTCPeerConnectionFactory.initializeSSL()
// Create a RTCPeerConnectionFactory.
self.rtcPeerConnectionFactory = RTCPeerConnectionFactory()
// Create a PluginGetUserMedia instance.
self.pluginGetUserMedia = PluginGetUserMedia(
rtcPeerConnectionFactory: rtcPeerConnectionFactory
)
}
override func onReset() {
NSLog("iosrtcPlugin#onReset() | doing nothing")
}
override func onAppTerminate() {
NSLog("iosrtcPlugin#onAppTerminate() | doing nothing")
}
func new_RTCPeerConnection(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#new_RTCPeerConnection()")
let pcId = command.argumentAtIndex(0) as! Int
var pcConfig: NSDictionary?
var pcConstraints: NSDictionary?
if command.argumentAtIndex(1) != nil {
pcConfig = command.argumentAtIndex(1) as? NSDictionary
}
if command.argumentAtIndex(2) != nil {
pcConstraints = command.argumentAtIndex(2) as? NSDictionary
}
let pluginRTCPeerConnection = PluginRTCPeerConnection(
rtcPeerConnectionFactory: self.rtcPeerConnectionFactory,
pcConfig: pcConfig,
pcConstraints: pcConstraints,
eventListener: { (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
},
eventListenerForAddStream: self.saveMediaStream,
eventListenerForRemoveStream: self.deleteMediaStream
)
// Store the pluginRTCPeerConnection into the dictionary.
self.pluginRTCPeerConnections[pcId] = pluginRTCPeerConnection
// Run it.
pluginRTCPeerConnection.run()
}
func RTCPeerConnection_createOffer(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_createOffer()")
let pcId = command.argumentAtIndex(0) as! Int
var options: NSDictionary?
if command.argumentAtIndex(1) != nil {
options = command.argumentAtIndex(1) as? NSDictionary
}
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_createOffer() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.createOffer(options,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { (error: NSError) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error.localizedDescription)
)
}
)
}
}
func RTCPeerConnection_createAnswer(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_createAnswer()")
let pcId = command.argumentAtIndex(0) as! Int
var options: NSDictionary?
if command.argumentAtIndex(1) != nil {
options = command.argumentAtIndex(1) as? NSDictionary
}
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_createAnswer() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.createAnswer(options,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { (error: NSError) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error.localizedDescription)
)
}
)
}
}
func RTCPeerConnection_setLocalDescription(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_setLocalDescription()")
let pcId = command.argumentAtIndex(0) as! Int
let desc = command.argumentAtIndex(1) as! NSDictionary
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_setLocalDescription() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.setLocalDescription(desc,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { (error: NSError) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error.localizedDescription)
)
}
)
}
}
func RTCPeerConnection_setRemoteDescription(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_setRemoteDescription()")
let pcId = command.argumentAtIndex(0) as! Int
let desc = command.argumentAtIndex(1) as! NSDictionary
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_setRemoteDescription() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.setRemoteDescription(desc,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { (error: NSError) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error.localizedDescription)
)
}
)
}
}
func RTCPeerConnection_addIceCandidate(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_addIceCandidate()")
let pcId = command.argumentAtIndex(0) as! Int
let candidate = command.argumentAtIndex(1) as! NSDictionary
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_addIceCandidate() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.addIceCandidate(candidate,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { () -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR)
)
}
)
}
}
func RTCPeerConnection_addStream(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_addStream()")
let pcId = command.argumentAtIndex(0) as! Int
let streamId = command.argumentAtIndex(1) as! String
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
let pluginMediaStream = self.pluginMediaStreams[streamId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_addStream() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_addStream() | ERROR: pluginMediaStream with id=%@ does not exist", String(streamId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection, weak pluginMediaStream] in
if pluginRTCPeerConnection?.addStream(pluginMediaStream!) == true {
self.saveMediaStream(pluginMediaStream!)
}
}
}
func RTCPeerConnection_removeStream(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_removeStream()")
let pcId = command.argumentAtIndex(0) as! Int
let streamId = command.argumentAtIndex(1) as! String
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
let pluginMediaStream = self.pluginMediaStreams[streamId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_removeStream() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_removeStream() | ERROR: pluginMediaStream with id=%@ does not exist", String(streamId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection, weak pluginMediaStream] in
pluginRTCPeerConnection?.removeStream(pluginMediaStream!)
}
}
func RTCPeerConnection_createDataChannel(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_createDataChannel()")
let pcId = command.argumentAtIndex(0) as! Int
let dcId = command.argumentAtIndex(1) as! Int
let label = command.argumentAtIndex(2) as! String
var options: NSDictionary?
if command.argumentAtIndex(3) != nil {
options = command.argumentAtIndex(3) as? NSDictionary
}
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_createDataChannel() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.createDataChannel(dcId,
label: label,
options: options,
eventListener: { (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
},
eventListenerForBinaryMessage: { (data: NSData) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArrayBuffer: data)
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
}
)
}
}
func RTCPeerConnection_getStats(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_getStats()")
let pcId = command.argumentAtIndex(0) as! Int
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_getStats() | ERROR: pluginRTCPeerConnection with pcId=\(pcId) does not exist")
return;
}
var pluginMediaStreamTrack: PluginMediaStreamTrack?
if command.argumentAtIndex(1) != nil {
let trackId = command.argumentAtIndex(1) as! String
pluginMediaStreamTrack = self.pluginMediaStreamTracks[trackId]
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_getStats() | ERROR: pluginMediaStreamTrack with id=\(trackId) does not exist")
return;
}
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection, weak pluginMediaStreamTrack] in
pluginRTCPeerConnection?.getStats(pluginMediaStreamTrack,
callback: { (array: NSArray) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsArray: array as [AnyObject])
)
},
errback: { (error: NSError) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error.localizedDescription)
)
}
)
}
}
func RTCPeerConnection_close(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_close()")
let pcId = command.argumentAtIndex(0) as! Int
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_close() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
if pluginRTCPeerConnection != nil {
pluginRTCPeerConnection!.close()
}
// Remove the pluginRTCPeerConnection from the dictionary.
self.pluginRTCPeerConnections[pcId] = nil
}
}
func RTCPeerConnection_RTCDataChannel_setListener(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_setListener()")
let pcId = command.argumentAtIndex(0) as! Int
let dcId = command.argumentAtIndex(1) as! Int
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_setListener() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.RTCDataChannel_setListener(dcId,
eventListener: { (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
},
eventListenerForBinaryMessage: { (data: NSData) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArrayBuffer: data)
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
}
)
}
}
func RTCPeerConnection_RTCDataChannel_sendString(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_sendString()")
let pcId = command.argumentAtIndex(0) as! Int
let dcId = command.argumentAtIndex(1) as! Int
let data = command.argumentAtIndex(2) as! String
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_sendString() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.RTCDataChannel_sendString(dcId,
data: data,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
}
)
}
}
func RTCPeerConnection_RTCDataChannel_sendBinary(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_sendBinary()")
let pcId = command.argumentAtIndex(0) as! Int
let dcId = command.argumentAtIndex(1) as! Int
let data = command.argumentAtIndex(2) as! NSData
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_sendBinary() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.RTCDataChannel_sendBinary(dcId,
data: data,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
}
)
}
}
func RTCPeerConnection_RTCDataChannel_close(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_close()")
let pcId = command.argumentAtIndex(0) as! Int
let dcId = command.argumentAtIndex(1) as! Int
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDataChannel_close() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.RTCDataChannel_close(dcId)
}
}
func RTCPeerConnection_createDTMFSender(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_createDTMFSender()")
let pcId = command.argumentAtIndex(0) as! Int
let dsId = command.argumentAtIndex(1) as! Int
let trackId = command.argumentAtIndex(2) as! String
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[trackId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_createDTMFSender() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_createDTMFSender() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(trackId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.createDTMFSender(dsId,
track: pluginMediaStreamTrack!,
eventListener: { (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
}
)
}
}
func RTCPeerConnection_RTCDTMFSender_insertDTMF(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDTMFSender_insertDTMF()")
let pcId = command.argumentAtIndex(0) as! Int
let dsId = command.argumentAtIndex(1) as! Int
let tones = command.argumentAtIndex(2) as! String
let duration = command.argumentAtIndex(3) as! Int
let interToneGap = command.argumentAtIndex(4) as! Int
let pluginRTCPeerConnection = self.pluginRTCPeerConnections[pcId]
if pluginRTCPeerConnection == nil {
NSLog("iosrtcPlugin#RTCPeerConnection_RTCDTMFSender_insertDTMF() | ERROR: pluginRTCPeerConnection with pcId=%@ does not exist", String(pcId))
return;
}
dispatch_async(self.queue) { [weak pluginRTCPeerConnection] in
pluginRTCPeerConnection?.RTCDTMFSender_insertDTMF(dsId,
tones: tones,
duration: duration,
interToneGap: interToneGap
)
}
}
func MediaStream_setListener(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStream_setListener()")
let id = command.argumentAtIndex(0) as! String
let pluginMediaStream = self.pluginMediaStreams[id]
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#MediaStream_setListener() | ERROR: pluginMediaStream with id=%@ does not exist", String(id))
return;
}
dispatch_async(self.queue) { [weak pluginMediaStream] in
// Set the eventListener.
pluginMediaStream?.setListener(
{ (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
},
eventListenerForAddTrack: self.saveMediaStreamTrack,
eventListenerForRemoveTrack: self.deleteMediaStreamTrack
)
}
}
func MediaStream_addTrack(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStream_addTrack()")
let id = command.argumentAtIndex(0) as! String
let trackId = command.argumentAtIndex(1) as! String
let pluginMediaStream = self.pluginMediaStreams[id]
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[trackId]
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#MediaStream_addTrack() | ERROR: pluginMediaStream with id=%@ does not exist", String(id))
return
}
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#MediaStream_addTrack() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(trackId))
return;
}
dispatch_async(self.queue) { [weak pluginMediaStream, weak pluginMediaStreamTrack] in
pluginMediaStream?.addTrack(pluginMediaStreamTrack!)
}
}
func MediaStream_removeTrack(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStream_removeTrack()")
let id = command.argumentAtIndex(0) as! String
let trackId = command.argumentAtIndex(1) as! String
let pluginMediaStream = self.pluginMediaStreams[id]
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[trackId]
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#MediaStream_removeTrack() | ERROR: pluginMediaStream with id=%@ does not exist", String(id))
return
}
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#MediaStream_removeTrack() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(trackId))
return;
}
dispatch_async(self.queue) { [weak pluginMediaStream, weak pluginMediaStreamTrack] in
pluginMediaStream?.removeTrack(pluginMediaStreamTrack!)
}
}
func MediaStream_release(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStream_release()")
let id = command.argumentAtIndex(0) as! String
let pluginMediaStream = self.pluginMediaStreams[id]
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#MediaStream_release() | ERROR: pluginMediaStream with id=%@ does not exist", String(id))
return;
}
self.pluginMediaStreams[id] = nil
}
func MediaStreamTrack_setListener(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamTrack_setListener()")
let id = command.argumentAtIndex(0) as! String
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[id]
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#MediaStreamTrack_setListener() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(id))
return;
}
dispatch_async(self.queue) { [weak pluginMediaStreamTrack] in
// Set the eventListener.
pluginMediaStreamTrack?.setListener(
{ (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
},
eventListenerForEnded: { () -> Void in
// Remove the track from the container.
self.pluginMediaStreamTracks[pluginMediaStreamTrack!.id] = nil
}
)
}
}
func MediaStreamTrack_setEnabled(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamTrack_setEnabled()")
let id = command.argumentAtIndex(0) as! String
let value = command.argumentAtIndex(1) as! Bool
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[id]
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#MediaStreamTrack_setEnabled() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(id))
return;
}
dispatch_async(self.queue) {[weak pluginMediaStreamTrack] in
pluginMediaStreamTrack?.setEnabled(value)
}
}
func MediaStreamTrack_stop(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamTrack_stop()")
let id = command.argumentAtIndex(0) as! String
let pluginMediaStreamTrack = self.pluginMediaStreamTracks[id]
if pluginMediaStreamTrack == nil {
NSLog("iosrtcPlugin#MediaStreamTrack_stop() | ERROR: pluginMediaStreamTrack with id=%@ does not exist", String(id))
return;
}
dispatch_async(self.queue) { [weak pluginMediaStreamTrack] in
pluginMediaStreamTrack?.stop()
}
}
func new_MediaStreamRenderer(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#new_MediaStreamRenderer()")
let id = command.argumentAtIndex(0) as! Int
let pluginMediaStreamRenderer = PluginMediaStreamRenderer(
webView: self.webView!,
eventListener: { (data: NSDictionary) -> Void in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
// Allow more callbacks.
result.setKeepCallbackAsBool(true);
self.emit(command.callbackId, result: result)
}
)
// Store into the dictionary.
self.pluginMediaStreamRenderers[id] = pluginMediaStreamRenderer
// Run it.
pluginMediaStreamRenderer.run()
}
func MediaStreamRenderer_render(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamRenderer_render()")
let id = command.argumentAtIndex(0) as! Int
let streamId = command.argumentAtIndex(1) as! String
let pluginMediaStreamRenderer = self.pluginMediaStreamRenderers[id]
let pluginMediaStream = self.pluginMediaStreams[streamId]
if pluginMediaStreamRenderer == nil {
NSLog("iosrtcPlugin#MediaStreamRenderer_render() | ERROR: pluginMediaStreamRenderer with id=%@ does not exist", String(id))
return
}
if pluginMediaStream == nil {
NSLog("iosrtcPlugin#MediaStreamRenderer_render() | ERROR: pluginMediaStream with id=%@ does not exist", String(streamId))
return;
}
pluginMediaStreamRenderer!.render(pluginMediaStream!)
}
func MediaStreamRenderer_mediaStreamChanged(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamRenderer_mediaStreamChanged()")
let id = command.argumentAtIndex(0) as! Int
let pluginMediaStreamRenderer = self.pluginMediaStreamRenderers[id]
if pluginMediaStreamRenderer == nil {
NSLog("iosrtcPlugin#MediaStreamRenderer_mediaStreamChanged() | ERROR: pluginMediaStreamRenderer with id=%@ does not exist", String(id))
return;
}
pluginMediaStreamRenderer!.mediaStreamChanged()
}
func MediaStreamRenderer_refresh(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamRenderer_refresh()")
let id = command.argumentAtIndex(0) as! Int
let data = command.argumentAtIndex(1) as! NSDictionary
let pluginMediaStreamRenderer = self.pluginMediaStreamRenderers[id]
if pluginMediaStreamRenderer == nil {
NSLog("iosrtcPlugin#MediaStreamRenderer_refresh() | ERROR: pluginMediaStreamRenderer with id=%@ does not exist", String(id))
return;
}
pluginMediaStreamRenderer!.refresh(data)
}
func MediaStreamRenderer_close(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#MediaStreamRenderer_close()")
let id = command.argumentAtIndex(0) as! Int
let pluginMediaStreamRenderer = self.pluginMediaStreamRenderers[id]
if pluginMediaStreamRenderer == nil {
NSLog("iosrtcPlugin#MediaStreamRenderer_close() | ERROR: pluginMediaStreamRenderer with id=%@ does not exist", String(id))
return
}
pluginMediaStreamRenderer!.close()
// Remove from the dictionary.
self.pluginMediaStreamRenderers[id] = nil
}
func getUserMedia(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#getUserMedia()")
let constraints = command.argumentAtIndex(0) as! NSDictionary
self.pluginGetUserMedia.call(constraints,
callback: { (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
},
errback: { (error: String) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: error)
)
},
eventListenerForNewStream: self.saveMediaStream
)
}
func enumerateDevices(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#enumerateDevices()")
dispatch_async(self.queue) {
PluginEnumerateDevices.call(
{ (data: NSDictionary) -> Void in
self.emit(command.callbackId,
result: CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: data as [NSObject : AnyObject])
)
}
)
}
}
func selectAudioOutputEarpiece(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#selectAudioOutputEarpiece()")
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.None)
} catch {
NSLog("iosrtcPlugin#selectAudioOutputEarpiece() | ERROR: %@", String(error))
};
}
func selectAudioOutputSpeaker(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#selectAudioOutputSpeaker()")
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
} catch {
NSLog("iosrtcPlugin#selectAudioOutputSpeaker() | ERROR: %@", String(error))
};
}
func dump(command: CDVInvokedUrlCommand) {
NSLog("iosrtcPlugin#dump()")
for (id, _) in self.pluginRTCPeerConnections {
NSLog("- PluginRTCPeerConnection [id:%@]", String(id))
}
for (_, pluginMediaStream) in self.pluginMediaStreams {
NSLog("- PluginMediaStream %@", String(pluginMediaStream.rtcMediaStream.description))
}
for (id, pluginMediaStreamTrack) in self.pluginMediaStreamTracks {
NSLog("- PluginMediaStreamTrack [id:%@, kind:%@]", String(id), String(pluginMediaStreamTrack.kind))
}
for (id, _) in self.pluginMediaStreamRenderers {
NSLog("- PluginMediaStreamRenderer [id:%@]", String(id))
}
}
/**
* Private API.
*/
private func emit(callbackId: String, result: CDVPluginResult) {
dispatch_async(dispatch_get_main_queue()) {
self.commandDelegate!.sendPluginResult(result, callbackId: callbackId)
}
}
private func saveMediaStream(pluginMediaStream: PluginMediaStream) {
if self.pluginMediaStreams[pluginMediaStream.id] == nil {
self.pluginMediaStreams[pluginMediaStream.id] = pluginMediaStream
} else {
return;
}
// Store its PluginMediaStreamTracks' into the dictionary.
for (id, track) in pluginMediaStream.audioTracks {
if self.pluginMediaStreamTracks[id] == nil {
self.pluginMediaStreamTracks[id] = track
}
}
for (id, track) in pluginMediaStream.videoTracks {
if self.pluginMediaStreamTracks[id] == nil {
self.pluginMediaStreamTracks[id] = track
}
}
}
private func deleteMediaStream(id: String) {
self.pluginMediaStreams[id] = nil
}
private func saveMediaStreamTrack(pluginMediaStreamTrack: PluginMediaStreamTrack) {
if self.pluginMediaStreamTracks[pluginMediaStreamTrack.id] == nil {
self.pluginMediaStreamTracks[pluginMediaStreamTrack.id] = pluginMediaStreamTrack
}
}
private func deleteMediaStreamTrack(id: String) {
self.pluginMediaStreamTracks[id] = nil
}
}
| mit | 5a960cc11241d2bbb490519de5efc6ee | 31.933404 | 146 | 0.748901 | 3.867784 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.StatusTampered.swift | 1 | 2033 | import Foundation
public extension AnyCharacteristic {
static func statusTampered(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Status Tampered",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.statusTampered(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func statusTampered(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Status Tampered",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt8> {
GenericCharacteristic<UInt8>(
type: .statusTampered,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | f7babcda931b8bd164f977c8dc40a895 | 32.327869 | 67 | 0.575504 | 5.294271 | false | false | false | false |
zhangchn/swelly | swelly/Site.swift | 1 | 935 | //
// Site.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import Foundation
fileprivate let WLDefaultSiteName = "DefaultSiteName"
fileprivate let WLDefaultAutoReplyString = "DefaultAutoReplyString"
struct Site {
var isDummy: Bool { get { return address.isEmpty }}
var connectionProtocol: ConnectionProtocol = .ssh
var name = NSLocalizedString(WLDefaultSiteName, comment: "Site")
var address = ""
var encoding = GlobalConfig.sharedInstance.defaultEncoding
var ansiColorKey: ANSIColorKey = GlobalConfig.sharedInstance.defaultANSIColorKey
var shouldAutoReply: Bool = false
var shouldDetectDoubleByte = GlobalConfig.sharedInstance.shouldDetectDoubleByte
var shouldEnableMouse = GlobalConfig.sharedInstance.shouldEnableMouse
var autoReplyString = NSLocalizedString(WLDefaultAutoReplyString, comment: "Site")
var proxyAddress = ""
var proxyType: ProxyType = .None
}
| gpl-2.0 | 91c050479b78ecdb73fb3423afa8ac59 | 33.62963 | 86 | 0.762567 | 4.43128 | false | true | false | false |
FeatureKit/FeatureKit | Tests/FeatureKit/Feature+MarshalTests.swift | 2 | 3075 | //
// FeatureKit
//
// Copyright © 2016 FeatureKit. All rights reserved.
//
import XCTest
import Marshal
@testable import FeatureKit
class JSONFeatureMapperTests: XCTestCase {
func test__feature_with_no_parent() {
do {
let feature = try TestFeature(object: ["id": "Foo", "title": "This is a title", "available": true])
XCTAssertEqual(feature.id, TestFeatureId.Foo)
XCTAssertNil(feature.parent)
XCTAssertEqual(feature.title, "This is a title")
XCTAssertEqual(feature.isEditable, false)
XCTAssertEqual(feature.defaultAvailability, true)
XCTAssertEqual(feature.currentAvailability, true)
XCTAssertEqual(feature.isAvailable, true)
XCTAssertEqual(feature.isToggled, false)
}
catch { XCTFail("Caught unexpected error: \(error)") }
}
func test__feature_with_parent() {
do {
let feature = try TestFeature(object: ["id": "Bar", "parent": "Foo", "title": "This is a different title", "available": true])
XCTAssertEqual(feature.id, TestFeatureId.Bar)
XCTAssertEqual(feature.parent, TestFeatureId.Foo)
XCTAssertEqual(feature.title, "This is a different title")
XCTAssertEqual(feature.isEditable, false)
XCTAssertEqual(feature.defaultAvailability, true)
XCTAssertEqual(feature.currentAvailability, true)
XCTAssertEqual(feature.isAvailable, true)
XCTAssertEqual(feature.isToggled, false)
}
catch { XCTFail("Caught unexpected error: \(error)") }
}
func test__feature_with_all_possible_fields() {
var feature: TestFeature! = nil
measure {
do {
feature = try TestFeature(object: ["id": "Hat", "parent": "Fat", "title": "This is a another title", "editable": true, "defaultAvailable": false, "available": true])
}
catch { XCTFail("Caught unexpected error: \(error)") }
}
XCTAssertEqual(feature.id, TestFeatureId.Hat)
XCTAssertEqual(feature.parent, TestFeatureId.Fat)
XCTAssertEqual(feature.title, "This is a another title")
XCTAssertEqual(feature.isEditable, true)
XCTAssertEqual(feature.defaultAvailability, false)
XCTAssertEqual(feature.currentAvailability, true)
XCTAssertEqual(feature.isAvailable, true)
XCTAssertEqual(feature.isToggled, true)
}
func test__throws_error_if_no_id() {
do {
let _ = try TestFeature(object: ["parent": "Foo", "title": "This is a different title", "available": true])
}
catch MarshalError.keyNotFound { /* passing test */ }
catch { XCTFail("Caught unexpected error: \(error)") }
}
func test__throws_error_if_no_id_or_title() {
do {
let _ = try TestFeature(object: ["parent": "Foo", "available": true])
}
catch MarshalError.keyNotFound { /* passing test */ }
catch { XCTFail("Caught unexpected error: \(error)") }
}
}
| mit | 6c93a5a47df8c91ce044726764cbc36b | 38.922078 | 181 | 0.620364 | 4.500732 | false | true | false | false |
proversity-org/edx-app-ios | Source/PostTableViewCell.swift | 1 | 8297 | //
// PostTableViewCell.swift
// edX
//
// Created by Tang, Jeff on 5/13/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class PostTableViewCell: UITableViewCell {
static let identifier = "PostCell"
private let typeLabel = UILabel()
private let infoLabel = UILabel()
private let titleLabel = UILabel()
private let countLabel = UILabel()
private var postReadStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralXDark())
}
private var postUnreadStyle : OEXTextStyle {
return OEXTextStyle(weight: .bold, size: .base, color: OEXStyles.shared().neutralXDark())
}
private var questionStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().secondaryDarkColor())
}
private var answerStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().utilitySuccessDark())
}
private var infoTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .xSmall, color: OEXStyles.shared().neutralDark())
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = OEXStyles.shared().neutralWhite()
contentView.addSubview(typeLabel)
contentView.addSubview(titleLabel)
contentView.addSubview(infoLabel)
contentView.addSubview(countLabel)
addConstraints()
titleLabel.numberOfLines = 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints() {
typeLabel.snp.makeConstraints { make in
make.leading.equalTo(contentView).offset(StandardHorizontalMargin)
make.top.equalTo(titleLabel)
}
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(typeLabel.snp.trailing).offset(StandardHorizontalMargin)
make.top.equalTo(contentView).offset(StandardVerticalMargin)
}
countLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel)
make.leading.greaterThanOrEqualTo(titleLabel.snp.trailing).offset(StandardHorizontalMargin)
make.trailing.equalTo(contentView).offset(-StandardHorizontalMargin)
}
infoLabel.snp.makeConstraints { make in
make.leading.equalTo(titleLabel)
make.top.equalTo(titleLabel.snp.bottom)
make.bottom.equalTo(contentView).offset(-StandardVerticalMargin)
}
}
private var titleTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color : OEXStyles.shared().neutralXDark())
}
private var activeCountStyle : OEXTextStyle {
return OEXTextStyle(weight: .bold, size: .base, color : OEXStyles.shared().primaryBaseColor())
}
private var inactiveCountStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color : OEXStyles.shared().neutralDark())
}
private var typeText : NSAttributedString? {
get {
return typeLabel.attributedText
}
set {
typeLabel.attributedText = newValue
}
}
private func updateThreadCount(count : String) {
countLabel.attributedText = activeCountStyle.attributedString(withText: count)
}
func useThread(thread : DiscussionThread, selectedOrderBy : DiscussionPostsSort) {
self.typeText = threadTypeText(thread: thread)
titleLabel.attributedText = thread.read ? postReadStyle.attributedString(withText: thread.title) : postUnreadStyle.attributedString(withText: thread.title)
var options = [NSAttributedString]()
if thread.closed { options.append(Icon.Closed.attributedTextWithStyle(style: infoTextStyle, inline : true)) }
if thread.pinned { options.append(Icon.Pinned.attributedTextWithStyle(style: infoTextStyle, inline : true)) }
if thread.following { options.append(Icon.FollowStar.attributedTextWithStyle(style: infoTextStyle)) }
if options.count > 0 { options.append(infoTextStyle.attributedString(withText: Strings.pipeSign)) }
options.append(infoTextStyle.attributedString(withText: Strings.Discussions.repliesCount(count: formatdCommentsCount(count: thread.commentCount))))
if let updatedAt = thread.updatedAt {
options.append(infoTextStyle.attributedString(withText: Strings.pipeSign))
options.append(infoTextStyle.attributedString(withText: Strings.Discussions.lastPost(date: updatedAt.displayDate)))
}
infoLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: options)
let count = formatdCommentsCount(count: thread.unreadCommentCount)
countLabel.attributedText = activeCountStyle.attributedString(withText: count)
countLabel.isHidden = !NSNumber(value: thread.unreadCommentCount).boolValue
setAccessibility(thread: thread)
setNeedsLayout()
layoutIfNeeded()
}
private func styledCellTextWithIcon(icon : Icon, text : String?) -> NSAttributedString? {
return text.map {text in
let style = infoTextStyle
return NSAttributedString.joinInNaturalLayout(attributedStrings: [icon.attributedTextWithStyle(style: style),
style.attributedString(withText: text)])
}
}
private func formatdCommentsCount(count: NSInteger) -> String {
if count > 99 {
return "99+"
}
return String(count)
}
private func threadTypeText(thread : DiscussionThread) -> NSAttributedString {
switch thread.type {
case .Discussion:
return (thread.unreadCommentCount > 0) ? Icon.Comments.attributedTextWithStyle(style: activeCountStyle) : Icon.Comments.attributedTextWithStyle(style: inactiveCountStyle)
case .Question:
return thread.hasEndorsed ? Icon.Answered.attributedTextWithStyle(style: answerStyle) : Icon.Question.attributedTextWithStyle(style: questionStyle)
}
}
private func setAccessibility(thread : DiscussionThread) {
var accessibilityString = ""
switch thread.type {
case .Discussion:
accessibilityString = Strings.discussion
case .Question:
thread.hasEndorsed ? (accessibilityString = Strings.answeredQuestion) : (accessibilityString = Strings.question)
}
accessibilityString = accessibilityString+","+(thread.title ?? "")
if thread.closed {
accessibilityString = accessibilityString+","+Strings.Accessibility.discussionClosed
}
if thread.pinned {
accessibilityString = accessibilityString+","+Strings.Accessibility.discussionPinned
}
if thread.following {
accessibilityString = accessibilityString+","+Strings.Accessibility.discussionFollowed
}
accessibilityString = accessibilityString+","+Strings.Discussions.repliesCount(count: formatdCommentsCount(count: thread.commentCount))
if let updatedAt = thread.updatedAt {
accessibilityString = accessibilityString+","+Strings.Accessibility.discussionLastPostOn(date: updatedAt.displayDate)
}
if thread.unreadCommentCount > 0 {
accessibilityString = accessibilityString+","+Strings.Accessibility.discussionUnreadReplies(count: formatdCommentsCount(count: thread.unreadCommentCount));
}
accessibilityLabel = accessibilityString
accessibilityHint = Strings.Accessibility.discussionThreadHint
}
}
extension DiscussionPostsSort {
var canHide : Bool {
switch self {
case .RecentActivity, .MostActivity:
return true
case .VoteCount:
return false
}
}
}
| apache-2.0 | 3421de9bb3ca83518a9462fa4687fafc | 37.771028 | 182 | 0.66518 | 5.429974 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Photo/PublishQuestionClassViewController.swift | 1 | 3397 | //
// PublishQuestionClassViewController.swift
// Whereami
//
// Created by A on 16/4/12.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
class PublishQuestionClassViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var questionModel:QuestionModel? = nil
var tableView:UITableView? = nil
var classList:[GameKindModel]? = nil
var nameArray:[String]? = nil
var codeArray:[String]? = nil
var selectedIndex:Int? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.classList = FileManager.sharedInstance.readGameKindListFromFile()
if classList != nil {
self.nameArray = GameKindModel.getNamesFromModels(classList!)
self.codeArray = GameKindModel.getCodesFromModels(classList!)
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(self.pushToNext))
self.setUI()
// Do any additional setup after loading the view.
}
func setUI(){
self.tableView = UITableView()
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.registerClass(UITableViewCell.self , forCellReuseIdentifier: "PublishQuestionClassViewCell")
self.view.addSubview(tableView!)
self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
}
func pushToNext(){
if selectedIndex != nil {
let viewController = PublishQuestionRangeViewController()
viewController.questionModel = self.questionModel
self.navigationController?.pushViewController(viewController, animated: true)
}
else{
let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: NSLocalizedString("selectRange",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: nil)
alertController.addAction(confirmAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if classList != nil {
return (classList?.count)!
}
return 0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//self.selectedRange = nameArray![indexPath.row]
self.selectedIndex = indexPath.row
self.questionModel?.classificationCode = codeArray![selectedIndex!]
self.questionModel?.classificationName = nameArray![selectedIndex!]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PublishQuestionClassViewCell")
if nameArray != nil {
cell?.textLabel?.text = nameArray![indexPath.row]
}
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 20bc4fc3959c624b493519f0b5bbfae6 | 39.891566 | 229 | 0.677961 | 5.294852 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/common/ZCDownload.swift | 1 | 1481 | //
// ZCDownload.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/24.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
import Alamofire
protocol ZCDownloadDelegate:NSObjectProtocol {
//下载失败
func download(download:ZCDownload, didFailWithError error:NSError)
//下载成功
func download(download:ZCDownload, didFinishWithData data:NSData?)
}
enum DownloadType:Int {
case Normal = 0
case Recommend
case Ingredients
case Classify
case FoodCourseDetail
case FoodCourseComment
}
class ZCDownload: NSObject {
weak var delegate:ZCDownloadDelegate?
var downloadType: DownloadType = .Normal
//POST
func postWithUrl(urlString:String, params:[String:AnyObject])
{
var tmpParams = NSDictionary(dictionary: params) as! [String:AnyObject]
//token=8ABD36C80D1639D9E81130766BE642B7&user_id=1386387&version=4.32
tmpParams["token"] = ""
tmpParams["user_id"] = ""
tmpParams["version"] = 4.5
Alamofire.request(.POST, urlString, parameters: tmpParams, encoding: ParameterEncoding.URL, headers: nil).responseData {
(response) in
switch response.result {
case .Failure(let error):
self.delegate?.download(self, didFailWithError: error)
case .Success:
self.delegate?.download(self, didFinishWithData: response.data)
}
}
}
}
| mit | 24f7a0dc135e05d51915a7d2db606904 | 26 | 128 | 0.64952 | 4.226087 | false | false | false | false |
haijianhuo/TopStore | Pods/KRPullLoader/KRPullLoader/Classes/KRPullLoadView.swift | 1 | 2722 | //
// KRPullLoadView.swift
// KRPullLoader
//
// Copyright © 2017 Krimpedance. All rights reserved.
//
import UIKit
/**
Delegate for KRPullLoadView.
*/
public protocol KRPullLoadViewDelegate: class {
/**
Handler when KRPullLoaderState value changed.
- parameter pullLoadView: KRPullLoadView.
- parameter state: New state.
- parameter type: KRPullLoaderType.
*/
func pullLoadView(_ pullLoadView: KRPullLoadView, didChangeState state: KRPullLoaderState, viewType type: KRPullLoaderType)
}
/**
Simple view which inherited KRPullLoadable protocol.
This has only activity indicator and message label.
*/
open class KRPullLoadView: UIView, KRPullLoadable {
private lazy var oneTimeSetUp: Void = { self.setUp() }()
open let activityIndicator = UIActivityIndicatorView()
open let messageLabel = UILabel()
open weak var delegate: KRPullLoadViewDelegate?
open override func layoutSubviews() {
super.layoutSubviews()
_ = oneTimeSetUp
}
// MARK: - Set up --------------
open func setUp() {
backgroundColor = .clear
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.hidesWhenStopped = false
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
addSubview(activityIndicator)
messageLabel.font = .systemFont(ofSize: 10)
messageLabel.textAlignment = .center
messageLabel.textColor = .gray
messageLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(messageLabel)
addConstraints([
NSLayoutConstraint(item: activityIndicator, attribute: .top, toItem: self, constant: 15.0),
NSLayoutConstraint(item: activityIndicator, attribute: .centerX, toItem: self),
NSLayoutConstraint(item: messageLabel, attribute: .top, toItem: self, constant: 40.0),
NSLayoutConstraint(item: messageLabel, attribute: .centerX, toItem: self),
NSLayoutConstraint(item: messageLabel, attribute: .bottom, toItem: self, constant: -15.0)
])
messageLabel.addConstraint(
NSLayoutConstraint(item: messageLabel, attribute: .width, relatedBy: .lessThanOrEqual, constant: 300)
)
}
// MARK: - KRPullLoadable --------------
open func didChangeState(_ state: KRPullLoaderState, viewType type: KRPullLoaderType) {
switch state {
case .none:
activityIndicator.stopAnimating()
case .pulling:
break
case .loading:
activityIndicator.startAnimating()
}
delegate?.pullLoadView(self, didChangeState: state, viewType: type)
}
}
| mit | da392c584efafc0c595c30c3e533927d | 30.639535 | 127 | 0.669607 | 5.153409 | false | false | false | false |
torinmb/Routinely | Routinely/TimerView.swift | 1 | 2173 | //
// TimerView.swift
// Routinely
//
// Created by Torin Blankensmith on 4/9/15.
// Copyright (c) 2015 Torin Blankensmith. All rights reserved.
//
import UIKit
class TimerView: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
@IBOutlet var displayTimeLabel: UILabel!
var startTime = NSTimeInterval()
var timer:NSTimer = NSTimer()
@IBAction func start(sender: AnyObject) {
if (!timer.valid) {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}
@IBAction func stop(sender: AnyObject) {
timer.invalidate()
}
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
displayTimeLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}
}
| mit | cb782881e2597b1bde00f09d18716f53 | 31.924242 | 129 | 0.635527 | 4.861298 | false | false | false | false |
lyimin/iOS-Animation-Demo | iOS-Animation学习笔记/iOS-Animation学习笔记/加载进度条/ProgressView.swift | 1 | 2821 | //
// ProgressView.swift
// iOS-Animation学习笔记
//
// Created by 梁亦明 on 16/5/26.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
class ProgressView: UIView {
@IBOutlet weak var percentLabel: UILabel!
/**
* 进度条颜色
*/
struct ColorPalette {
static let teal = UIColor(red:0.27, green:0.80, blue:0.80, alpha:1.0)
static let orange = UIColor(red:0.90, green:0.59, blue:0.20, alpha:1.0)
static let pink = UIColor(red:0.98, green:0.12, blue:0.45, alpha:1.0)
}
// 进度条位子
fileprivate let progressLayer = CAShapeLayer()
fileprivate let gradientLayer = CAGradientLayer()
// 总量
var range: CGFloat = 128
var curValue: CGFloat = 0 {
didSet {
animateStroke()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupLayers()
}
fileprivate func setupLayers() {
// 设置位置
progressLayer.position = CGPoint.zero
// 设置线宽
progressLayer.lineWidth = 3.0
progressLayer.strokeEnd = 0.0
progressLayer.fillColor = nil
progressLayer.strokeColor = UIColor.black.cgColor
// 创建路径
let radius = CGFloat(self.width/2) - progressLayer.lineWidth
let startAngle = CGFloat(-M_PI / 2)
let endAngle = CGFloat(3/2 * M_PI)
let path = UIBezierPath(arcCenter: self.center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
progressLayer.path = path.cgPath
// 添加layer
self.layer.addSublayer(progressLayer)
// 初始化渐变颜色layer
gradientLayer.frame = self.bounds
// 设置渐变颜色
gradientLayer.colors = [ColorPalette.teal.cgColor, ColorPalette.orange.cgColor, ColorPalette.pink.cgColor]
// 设置渐变位置
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
gradientLayer.mask = progressLayer // Use progress layer as mask for gradient layer.
self.layer.addSublayer(gradientLayer)
}
func animateStroke() {
let fromValue = progressLayer.strokeEnd
let toValue = curValue / range
// 执行动画
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = fromValue
animation.toValue = toValue
progressLayer.add(animation, forKey: "stroke")
progressLayer.strokeEnd = toValue
}
class func createView() -> ProgressView {
return Bundle.main.loadNibNamed("ProgressView", owner: nil, options: nil)!.first as! ProgressView
}
}
| mit | faee98898b289cd766bcf2f96e642bc1 | 28.413043 | 132 | 0.601626 | 4.45799 | false | false | false | false |
QuarkX/Quark | Tests/QuarkTests/HTTP/Content/ResponseContentTests.swift | 1 | 2408 | import XCTest
@testable import Quark
struct Fuu : MapFallibleRepresentable {
let content: Map
func asMap() throws -> Map {
return content
}
}
class ResponseContentTests : XCTestCase {
func testContent() throws {
let content = 1969
let response = Response(content: content)
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers, ["Content-Length": "0"])
XCTAssertEqual(response.body, .buffer(Data()))
XCTAssertEqual(response.content, Map(content))
}
func testOptionalContent() throws {
let content: Int? = 1969
let response = Response(content: content)
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers, ["Content-Length": "0"])
XCTAssertEqual(response.body, .buffer(Data()))
XCTAssertEqual(response.content, Map(content))
}
func testArrayContent() throws {
let content = [1969]
let response = Response(content: content)
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers, ["Content-Length": "0"])
XCTAssertEqual(response.body, .buffer(Data()))
XCTAssertEqual(response.content, Map(content))
}
func testDictionaryContent() throws {
let content = ["Woodstock": 1969]
let response = Response(content: content)
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers, ["Content-Length": "0"])
XCTAssertEqual(response.body, .buffer(Data()))
XCTAssertEqual(response.content, Map(content))
}
func testFallibleContent() throws {
let content = 1969
let fuu = Fuu(content: 1969)
let response = try Response(content: fuu)
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers, ["Content-Length": "0"])
XCTAssertEqual(response.body, .buffer(Data()))
XCTAssertEqual(response.content, Map(content))
}
}
extension ResponseContentTests {
static var allTests : [(String, (ResponseContentTests) -> () throws -> Void)] {
return [
("testContent", testContent),
("testOptionalContent", testOptionalContent),
("testArrayContent", testArrayContent),
("testDictionaryContent", testDictionaryContent),
("testFallibleContent", testFallibleContent),
]
}
}
| mit | eae531486dffa26a3a92e89a712e0029 | 33.898551 | 83 | 0.641611 | 4.740157 | false | true | false | false |
DumbDuck/VecodeKit | iOS_Mac/QuartzPictureExample/example-ios/PictureListViewController.swift | 1 | 1802 | import Foundation
import UIKit
private let kCellID = "CellId"
class PictureListViewController: UITableViewController {
fileprivate let _pictures = [
("tiger", g_picture_tiger),
("icons", g_picture_icons),
("snow_woman", g_picture_snow_woman),
("river_man", g_picture_river_man),
("all_test", g_picture_all_test),
]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 100
self.title = NSLocalizedString("Pictures", comment: "")
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: kCellID)
if #available(iOS 9.0, *) {
self.tableView.cellLayoutMarginsFollowReadableWidth = false
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _pictures.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath)
let (title, picture) = _pictures[(indexPath as NSIndexPath).row]
let imageHeight = self.tableView.rowHeight - 10
cell.textLabel?.text = title
cell.imageView?.image = picture.transToImage(CGSize(width: imageHeight, height: imageHeight))
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let (title, picture) = _pictures[(indexPath as NSIndexPath).row]
let aViewController = PictureViewController(picture: picture)
aViewController.title = title
self.navigationController?.pushViewController(aViewController, animated: true)
}
}
| mit | 84586af7b3f622b696d4d0e1eb2532e1 | 36.541667 | 109 | 0.6798 | 4.896739 | false | false | false | false |
daltoniam/Skeets | ImageManager.swift | 1 | 7669 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// ImageManager.swift
//
// Created by Dalton Cherry on 9/24/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import SwiftHTTP
///This stores the blocks that come from the fetch method.
///This is used to ensure only one request goes out for multiple of the same url.
private class BlockHolder {
var progress:((Double) -> Void)?
var success:((NSData) -> Void)?
var failure:((NSError) -> Void)?
init(progress: ((Double) -> Void)?, success: ((NSData) -> Void)?, failure: ((NSError) -> Void)?) {
self.progress = progress
self.success = success
self.failure = failure
}
}
///This is the main class. It handles interaction with cache and ensuring only one request goes out for multiples of the same url
public class ImageManager {
///The cache. This is anything that responses to the cache protocol. By default it uses the provided ImageCache.
public var cache: CacheProtocol
///This is used so multiple request for the same url only sends one request
private var pending = Dictionary<String,Array<BlockHolder>>()
/**
Initializes a new ImageManager
:param: cacheDirectory is the directory on disk to save cached images to.
*/
public init(cacheDirectory: String) {
var dir = cacheDirectory
if dir == "" {
#if os(iOS)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
dir = "\(paths[0])" //use default documents folder, not ideal but better than the cache not working
#elseif os(OSX)
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
if let name = NSBundle.mainBundle().bundleIdentifier {
dir = "\(paths[0])/\(name)"
}
#endif
}
cache = ImageCache(dir)
}
/**
Fetches the image from the nearest location avaliable.
:param: url The url you would like to make a request to.
:param: method The HTTP method/verb for the request.
:param: progress The closure that is run when reporting download progress via HTTP.
:param: success The closure that is run on a sucessful image retrieval.
:param: failure The closure that is run on a failed HTTP Request.
*/
public func fetch(url: String, progress:((Double) -> Void)!, success:((NSData) -> Void)!, failure:((NSError) -> Void)!) {
let hash = self.hash(url)
//check from memory first
let data = cache.fromMemory(hash)
if data != nil {
if let s = success {
s(data!)
}
return
}
//The pending Dictionary makes sure we don't run multiple request for the same image
//so we check that to make sure we aren't already requesting that image
if self.pending[hash] == nil {
var holder = Array<BlockHolder>()
holder.append(BlockHolder(progress: progress, success: success, failure: failure))
self.pending[hash] = holder
//next check from disk asynchronously
cache.fromDisk(hash, success: { (d: NSData) in
self.doSuccess(hash, data: d)
}, failure: { (Void) in
//lastly fetch from the network asynchronously
let task = HTTPTask()
task.download(url, parameters: nil, progress: { (status: Double) in
dispatch_async(dispatch_get_main_queue(), {
self.doProgress(hash, status: status)
})
}, completionHandler: { (response: HTTPResponse) in
if let err = response.error {
dispatch_async(dispatch_get_main_queue(), {
self.doFailure(hash, error: err)
})
} else {
self.cache.add(hash, url: response.responseObject! as! NSURL)
dispatch_async(dispatch_get_main_queue(), {
if let d = self.cache.fromMemory(hash) {
self.doSuccess(hash, data: d)
}
})
}
})
})
} else if var array = self.pending[hash] {
array.append(BlockHolder(progress: progress, success: success, failure: failure))
self.pending[hash] = array
}
}
///cancel the request, by simply removing the closures
public func cancel(url: String) {
let hash = self.hash(url)
self.pending.removeValueForKey(hash)
}
///run all the success closures
private func doSuccess(hash: String, data: NSData) {
let holder = self.pending[hash]
if let array = holder {
for blocks in array {
if let s = blocks.success {
s(data)
}
}
self.pending.removeValueForKey(hash)
}
}
///run all the failure closures
private func doFailure(hash: String, error: NSError) {
let holder = self.pending[hash]
if let array = holder {
for blocks in array {
if let f = blocks.failure {
f(error)
}
}
self.pending.removeValueForKey(hash)
}
}
///run all the progress closures
private func doProgress(hash: String, status: Double) {
let holder = self.pending[hash]
if let array = holder {
for blocks in array {
if let p = blocks.progress {
p(status)
}
}
}
}
///Hashes the url so it can be saved to disk.
private func hash(u: String) -> String {
var url = u
let len = count(url)-1
if url[advance(url.startIndex,len)] == "/" {
url = url[url.startIndex..<advance(url.startIndex,len)]
}
var hash: UInt32 = 0
for (index, codeUnit) in enumerate(url.utf8) {
hash += (UInt32(codeUnit) * UInt32(index))
hash ^= (hash >> 6)
}
hash += (hash << 3)
hash ^= (hash >> 11)
hash += (hash << 15)
return "\(hash)"
}
///convenience method so you don't have to call "ImageManager.sharedManager" everytime you want to fetch an image
public class func fetch(url: String, progress:((Double) -> Void)!, success:((NSData) -> Void)!, failure:((NSError) -> Void)!) {
ImageManager.sharedManager.fetch(url, progress: progress, success: success, failure: failure)
}
///convenience method so you don't have to call "ImageManager.sharedManager" everytime you want to cancel an image
public class func cancel(url: String) {
ImageManager.sharedManager.cancel(url)
}
///Image manager singleton to manage displaying/caching images.
///This is normally the primary vehicle for displaying your images.
public class var sharedManager : ImageManager {
struct Static {
static let instance : ImageManager = ImageManager(cacheDirectory: "")
}
return Static.instance
}
}
| apache-2.0 | d5f3e62f1196beb6bfab71ff197c4c43 | 38.735751 | 131 | 0.540096 | 4.983106 | false | false | false | false |
xiaoyangrun/DYTV | DYTV/DYTV/Classes/Tools/Extention/UIBarButtonItem-Extension.swift | 1 | 1450 | //
// UIBarButtonItem-Extension.swift
// DYTV
//
// Created by 小羊快跑 on 2017/1/11.
// Copyright © 2017年 小羊快跑. All rights reserved.
// 扩展功能
import UIKit
extension UIBarButtonItem{
// class func creatBarButtonItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem {
// let btn = UIButton()
// btn.setImage(UIImage(named: imageName), for: .normal)
// btn.setImage(UIImage(named: highImageName), for: .highlighted)
// btn.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: size)
//// btn.addTarget(self, action: #selector(leftItemClick), for: .touchUpInside)
// return UIBarButtonItem.init(customView: btn)
// }
///便利构造函数
// 必须明确调用一个设计的构造函数, 用self调用
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.init(width: 0, height: 0), target: AnyObject, action: Selector) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
if size != CGSize.init(width: 0, height: 0){
btn.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: size)
}
btn.addTarget(target, action: action, for: .touchUpInside)
self.init(customView: btn)
}
}
| mit | 31c7c755801cccbf9c8e8a8a9c446f26 | 37.194444 | 155 | 0.629818 | 3.696237 | false | false | false | false |
Karetski/NewsReader | NewsReader/FavoritesTableViewController.swift | 1 | 6504 | //
// FavoritesTableViewController.swift
// NewsReader
//
// Created by Alexey on 20.12.15.
// Copyright © 2015 Alexey. All rights reserved.
//
import UIKit
import CoreData
class FavoritesTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var managedContext: NSManagedObjectContext!
var fetchedResultsController: NSFetchedResultsController!
let favoritesCellIdentifier = "FavoritesCell"
let favoritesExitSegueIdentifier = "FavoritesExitSegue"
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest = NSFetchRequest(entityName: "Favorite")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedContext, sectionNameKeyPath: nil, cacheName: nil)
self.fetchedResultsController.delegate = self
do {
try self.fetchedResultsController.performFetch()
} catch let error as NSError {
print("Error:\(error.localizedDescription)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Button actions
@IBAction func addFavoriteAction(sender: AnyObject) {
let alert = UIAlertController(title: "Favorites", message: "Add new RSS Channel", preferredStyle: .Alert)
let addFavoriteAction = UIAlertAction(title: "Add", style: .Default, handler: { (action: UIAlertAction!) in
let nameTextField = alert.textFields![0]
let linkTextField = alert.textFields![1]
let favorite = NSEntityDescription.insertNewObjectForEntityForName("Favorite", inManagedObjectContext: self.managedContext) as! Favorite
favorite.name = nameTextField.text
favorite.link = linkTextField.text
do {
try self.managedContext.save()
} catch let error as NSError {
print("Error: \(error) " + "description \(error.localizedDescription)")
}
})
addFavoriteAction.enabled = false
alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in
textField.placeholder = "Name"
}
alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in
textField.placeholder = "Link"
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue()) { (notification) in
if let link = textField.text {
if link.hasSuffix(".xml") || link.hasSuffix(".rss") {
addFavoriteAction.enabled = true
}
}
}
}
alert.addAction(addFavoriteAction)
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.favoritesCellIdentifier, forIndexPath: indexPath)
let favorite = fetchedResultsController.objectAtIndexPath(indexPath) as! Favorite
cell.textLabel?.text = favorite.name
cell.detailTextLabel?.text = favorite.link
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let favorite = fetchedResultsController.objectAtIndexPath(indexPath) as! Favorite
self.managedContext.deleteObject(favorite)
do {
try self.managedContext.save()
} catch let error as NSError {
print("Error: \(error) " + "description \(error.localizedDescription)")
}
}
}
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller:
NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
if type == .Insert {
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
} else if type == .Delete {
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
} else if type == .Move {
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == favoritesExitSegueIdentifier {
if let destination = segue.destinationViewController as? NewsTableViewController {
if let indexPath = self.tableView.indexPathForSelectedRow {
let favorite = fetchedResultsController.objectAtIndexPath(indexPath) as! Favorite
guard let link = favorite.link else {
return
}
destination.rssLink = link
}
}
}
}
}
| mit | eb4d79719eb25529ce520b3c6533e615 | 39.141975 | 211 | 0.652622 | 6.246878 | false | false | false | false |
Legoless/Saystack | Code/Extensions/StoreKit/SKProductFormatter.swift | 1 | 11182 | //
// SKProductFormatter.swift
// Saystack
//
// Created by Dal Rupnik on 4/5/20.
// Copyright © 2020 Unified Sense. All rights reserved.
//
import Foundation
import StoreKit
public class SKProductFormatter : Formatter {
public enum ProductComponent {
case subscriptionDuration
case subscriptionDurationUnit
case subscriptionPrice
// Introductionary Price
case introductoryPriceDuration
case introductoryPriceDurationUnit
case introductoryPrice
case introductoryPriceMode // For trial
}
public enum PriceFormatStyle {
case noConversion // Will never convert price.
case week // Will convert prices to weekly price.
case day // Will convert prices to daily price.
case month // Will convert prices to monthly price.
var targetUnit : SKProduct.PeriodUnit? {
switch self {
case .week:
return .week
case .day:
return .day
case .month:
return .month
case .noConversion:
return nil
}
}
}
public enum DurationUnitFormatStyle {
case normal // Will format duration as "month", "year"
case short // Will format duration as "mo", "yr"
}
/// All formatted components that will be output as a string
public var formatComponents: [ProductComponent] = [ .subscriptionPrice, .subscriptionDurationUnit ]
public var priceFormatStyle : PriceFormatStyle = .noConversion
public var durationUnitFormatStyle : DurationUnitFormatStyle = .normal
public var durationUnitSeparator : String? = nil
public var usePlural : Bool = true
public var convertToQuarter : Bool = false
public var componentSeparator = " "
public func componentStrings(from product: SKProduct) -> [String] {
return formatComponents.compactMap { format(component: $0, with: product) }
}
public func string(from product: SKProduct) -> String? {
let formattedComponents = componentStrings(from: product)
guard formattedComponents.count > 0 else {
return nil
}
return formattedComponents.joined(separator: componentSeparator)
}
private func format(component: ProductComponent, with product: SKProduct) -> String? {
guard let subscriptionPeriod = product.subscriptionPeriod else {
return nil
}
switch component {
case .subscriptionDuration:
return formatDuration(product.subscriptionPeriod)
case .subscriptionDurationUnit:
return formatDurationUnit(subscriptionPeriod)
case .subscriptionPrice:
let formatter = priceFormatter(locale: product.priceLocale)
if priceFormatStyle == .noConversion {
return formatter.string(from: product.price)!
}
else if let targetUnit = priceFormatStyle.targetUnit {
// We must do a price converstion to the correct price.
return formatter.string(from: convert(price: product.price, from: subscriptionPeriod, to: targetUnit))
}
else {
return nil
}
case .introductoryPriceMode, .introductoryPrice, .introductoryPriceDuration, .introductoryPriceDurationUnit:
return formatIntroductionary(component: component, introductoryPrice: product.introductoryPrice)
}
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
private func formatIntroductionary(component: ProductComponent, introductoryPrice: SKProductDiscount?) -> String? {
guard let introductoryPrice = introductoryPrice else {
return nil
}
switch component {
case .introductoryPriceMode:
switch introductoryPrice.paymentMode {
case .freeTrial:
return "trial"
case .payAsYouGo:
return "pay as you go"
case .payUpFront:
return "upfront"
@unknown default:
return nil
}
case .introductoryPriceDurationUnit:
return formatDurationUnit(introductoryPrice.subscriptionPeriod)
case .introductoryPriceDuration:
return formatDuration(introductoryPrice.subscriptionPeriod)
case .introductoryPrice:
return format(price: introductoryPrice.price, locale: introductoryPrice.priceLocale, period: introductoryPrice.subscriptionPeriod)
default:
return nil
}
}
private func format(price: NSDecimalNumber, locale: Locale, period: SKProductSubscriptionPeriod?) -> String? {
let formatter = priceFormatter(locale: locale)
if priceFormatStyle == .noConversion {
return formatter.string(from: price)
}
else if let targetUnit = priceFormatStyle.targetUnit, let period = period {
// We must do a price converstion to the correct price.
return formatter.string(from: convert(price: price, from: period, to: targetUnit))
}
else {
return nil
}
}
private func formatDuration(_ period: SKProductSubscriptionPeriod?) -> String? {
guard let period = period else {
return nil
}
let formattingUnit = priceFormatStyle.targetUnit ?? period.unit
var numberOfUnits = period.numberOfUnits
if priceFormatStyle.targetUnit != nil {
numberOfUnits = convert(numberOfUnits: numberOfUnits, from: period, to: formattingUnit)
}
// Handle quarter
if numberOfUnits == 3 && period.unit == .month && convertToQuarter {
numberOfUnits = 1
}
return "\(numberOfUnits)"
}
private func formatDurationUnit(_ period: SKProductSubscriptionPeriod) -> String? {
let formattingUnit = priceFormatStyle.targetUnit ?? period.unit
var numberOfUnits = period.numberOfUnits
if priceFormatStyle.targetUnit != nil {
numberOfUnits = convert(numberOfUnits: numberOfUnits, from: period, to: formattingUnit)
}
switch durationUnitFormatStyle {
case .normal:
if usePlural && durationUnitSeparator == nil {
// Handle quarter specifically
var unitString = formattingUnit.stringValue
if numberOfUnits == 3 && period.unit == .month && priceFormatStyle.targetUnit == nil && convertToQuarter {
unitString = "quarter"
}
else {
unitString = unitString.pluralize(count: numberOfUnits)
}
return "\(durationUnitSeparator ?? "")\(unitString)"
}
else {
var unitString = formattingUnit.stringValue
if numberOfUnits == 3 && period.unit == .month && priceFormatStyle.targetUnit == nil && convertToQuarter {
unitString = "quarter"
}
return "\(durationUnitSeparator ?? "")\(unitString)"
}
case .short:
return "\(durationUnitSeparator ?? "")\(formattingUnit.shortStringValue)"
}
}
/// Convert price number from period unit to desired target unit.
/// - Parameters:
/// - price: to be converted
/// - unit: unit price is currently in
/// - targetUnit: desired price unit
/// - Returns: price
private func convert(price: NSDecimalNumber, from period: SKProductSubscriptionPeriod, to targetUnit: SKProduct.PeriodUnit) -> NSDecimalNumber {
// Convert to monthly price
let singleUnitPrice = price.dividing(by: NSDecimalNumber(value: period.numberOfUnits))
let monthlyPrice : NSDecimalNumber
// First convert the price to monthly price, to work from same start.
switch period.unit {
case .day:
monthlyPrice = singleUnitPrice.multiplying(by: NSDecimalNumber(floatLiteral: 30.0))
case .week:
monthlyPrice = singleUnitPrice.multiplying(by: NSDecimalNumber(floatLiteral: 4.0))
case .year:
monthlyPrice = singleUnitPrice.dividing(by: NSDecimalNumber(floatLiteral: 12.0))
case .month:
monthlyPrice = singleUnitPrice
@unknown default:
monthlyPrice = singleUnitPrice
}
switch targetUnit {
case .day:
return monthlyPrice.dividing(by: NSDecimalNumber(floatLiteral: 30.0))
case .week:
return monthlyPrice.dividing(by: NSDecimalNumber(floatLiteral: 4.0))
case .year:
return monthlyPrice.multiplying(by: NSDecimalNumber(floatLiteral: 12.0))
case .month:
return monthlyPrice
@unknown default:
return monthlyPrice
}
}
private func convert(numberOfUnits: Int, from period: SKProductSubscriptionPeriod, to targetUnit: SKProduct.PeriodUnit) -> Int {
let dailyNumberOfUnits : Int
// First convert the price to monthly price, to work from same start.
switch period.unit {
case .day:
dailyNumberOfUnits = numberOfUnits
case .week:
dailyNumberOfUnits = numberOfUnits * 7
case .year:
dailyNumberOfUnits = numberOfUnits * 365
case .month:
dailyNumberOfUnits = numberOfUnits * 30
@unknown default:
dailyNumberOfUnits = numberOfUnits * 30
}
switch targetUnit {
case .day:
return dailyNumberOfUnits
case .week:
return Int(Double(dailyNumberOfUnits) / 7.0)
case .year:
return Int(Double(dailyNumberOfUnits) / 365.0)
case .month:
return Int(Double(dailyNumberOfUnits) / 30.0)
@unknown default:
return dailyNumberOfUnits
}
}
}
public extension SKProduct.PeriodUnit {
var stringValue : String {
switch self {
case .day:
return "day"
case .week:
return "week"
case .month:
return "month"
case .year:
return "year"
@unknown default:
return ""
}
}
var shortStringValue : String {
switch self {
case .day:
return "dy"
case .week:
return "wk"
case .month:
return "mo"
case .year:
return "yr"
@unknown default:
return ""
}
}
}
| mit | 186a999945381b03016ce92213212e14 | 34.722045 | 148 | 0.586799 | 5.306597 | false | false | false | false |
shaowei-su/swiftmi-app | swiftmi/swiftmi/CodeDal.swift | 4 | 3615 | //
// CodeDal.swift
// swiftmi
//
// Created by yangyin on 15/4/30.
// Copyright (c) 2015年 swiftmi. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
class CodeDal: NSObject {
func addList(items:JSON) {
for po in items {
self.addCode(po.1, save: false)
}
CoreDataManager.shared.save()
}
func addCode(obj:JSON,save:Bool){
var context=CoreDataManager.shared.managedObjectContext;
let model = NSEntityDescription.entityForName("Codedown", inManagedObjectContext: context)
var codeDown = ShareCode(entity: model!, insertIntoManagedObjectContext: context)
if model != nil {
self.obj2ManagedObject(obj, codeDown: codeDown)
if(save)
{
CoreDataManager.shared.save()
}
}
}
func deleteAll(){
CoreDataManager.shared.deleteTable("Codedown")
}
func save(){
var context=CoreDataManager.shared.managedObjectContext;
context.save(nil)
}
func getCodeList()->[AnyObject]? {
var request = NSFetchRequest(entityName: "Codedown")
var sort1=NSSortDescriptor(key: "createTime", ascending: false)
// var sort2=NSSortDescriptor(key: "postId", ascending: false)
request.fetchLimit = 30
request.sortDescriptors = [sort1]
request.resultType = NSFetchRequestResultType.DictionaryResultType
var result = CoreDataManager.shared.executeFetchRequest(request)
return result
}
func obj2ManagedObject(obj:JSON,codeDown:ShareCode) -> ShareCode{
var data = obj
codeDown.author = data["author"].string
codeDown.categoryId = data["categoryId"].int64Value
codeDown.categoryName = data["categoryName"].string
codeDown.codeId = data["codeId"].int64Value
codeDown.commentCount = data["commentCount"].int32Value
codeDown.content = data["content"].string
codeDown.contentLength = data["contentLength"].doubleValue
codeDown.createTime = data["createTime"].int64Value
codeDown.desc = data["desc"].string
codeDown.devices = data["devices"].string
codeDown.downCount = data["downCount"].int32Value
codeDown.downUrl = data["downUrl"].stringValue
codeDown.isHtml = data["isHtml"].int32Value
codeDown.keywords = data["keywords"].string
if data["lastCommentId"].int64 != nil {
codeDown.lastCommentId = data["lastCommentId"].int64Value
}
codeDown.lastCommentTime = data["lastCommentTime"].int64Value
codeDown.licence = data["licence"].string
codeDown.platform = data["platform"].string
codeDown.preview = data["preview"].stringValue
codeDown.sourceName = data["sourceName"].stringValue
codeDown.sourceType = data["sourceType"].int32Value
codeDown.sourceUrl = data["sourceUrl"].stringValue
codeDown.state = data["state"].int32Value
codeDown.tags = data["tags"].string
codeDown.title = data["title"].string
codeDown.updateTime = data["updateTime"].int64Value
codeDown.userId = data["userId"].int64Value
codeDown.username = data["username"].stringValue
codeDown.viewCount = data["viewCount"].int32Value
return codeDown
}
}
| mit | c96a11f0a109d866040048575f51eaa2 | 30.417391 | 98 | 0.606144 | 4.862719 | false | false | false | false |
nikitakirichek/concurrency-in-swift | PPCourseWork1/CSDataSource.swift | 1 | 837 | //
// CSDataSource.swift
// PPCourseWork1
//
// Created by Nikita Kirichek on 5/11/17.
// Copyright © 2017 Nikita Kirichek. All rights reserved.
//
import Cocoa
class CSDataSource: NSObject {
var P: Int
var N: Int
var e: Int?
var c: Int?
var Z: CSVector?
var MK: CSMatrix?
var B: CSVector?
var MO: CSMatrix?
init(numberOfProcesses: Int, size: Int) {
P = numberOfProcesses
N = size
}
func randomizeAll() {
let randomizer = CSRandomizer(max: 1, size: N)
e = randomizer.randomVar()
c = randomizer.randomVar()
Z = randomizer.randomVector()
B = randomizer.randomVector()
Z = randomizer.randomVector()
MK = randomizer.randomMatrix()
MO = randomizer.randomMatrix()
}
}
| mit | 076483387f4c4fd933b1387097365e6f | 18.904762 | 58 | 0.572967 | 3.634783 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Services/Exchange/Network/Model/CryptoExchangeAddressResponse.swift | 1 | 1946 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import MoneyKit
struct CryptoExchangeAddressResponse: Decodable, Equatable {
// MARK: - Types
/// Error to be thrown in case decoding is unsuccessful
enum ResponseError: Error {
case assetType
case state
case address
}
/// State of Exchange account linking
enum State: String, Equatable {
case pending = "PENDING"
case active = "ACTIVE"
case blocked = "BLOCKED"
/// Returns `true` for an active state
var isActive: Bool {
switch self {
case .active:
return true
case .pending, .blocked:
return false
}
}
}
private enum CodingKeys: String, CodingKey {
case state
case currency
case address
}
/// The asset type
let assetType: CryptoCurrency
/// The address associated with the asset type
let address: String
/// Thr state of the account
let state: State
// MARK: - Setup
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
address = try values.decode(String.self, forKey: .address)
guard !address.isEmpty else {
throw ResponseError.address
}
let currency = try values.decode(String.self, forKey: .currency)
let provider: EnabledCurrenciesServiceAPI = resolve()
if let assetType = provider.allEnabledCryptoCurrencies.first(where: { $0.code == currency }) {
self.assetType = assetType
} else {
throw ResponseError.assetType
}
let stateRawValue = try values.decode(String.self, forKey: .state)
if let state = State(rawValue: stateRawValue) {
self.state = state
} else {
throw ResponseError.state
}
}
}
| lgpl-3.0 | c773fabcc9b828d25b2d59fd6b4bf09b | 26.013889 | 102 | 0.594859 | 4.961735 | false | false | false | false |
thegrimheep/GitHubProject | GitHubProject/GitHubProject/GitHubProject/RepoViewController.swift | 1 | 3441 | //
// RepoViewController.swift
// GitHubProject
//
// Created by David Porter on 4/4/17.
// Copyright © 2017 David Porter. All rights reserved.
//
import UIKit
class RepoViewController: UIViewController, UISearchBarDelegate { //implement the delegate here see docs for more options
@IBOutlet weak var searchBarButton: UISearchBar!
@IBOutlet weak var listReops: UITableView!
var allRepos = [Repository]()
// var searchedRepos = [Repository]?()
override func viewDidLoad() {
super.viewDidLoad()
let repoXib = UINib(nibName: RepoTableViewCell.identifier, bundle: Bundle.main)
self.listReops.register(repoXib, forCellReuseIdentifier: RepoTableViewCell.identifier)
self.searchBarButton.delegate = self
self.listReops.delegate = self
self.listReops.dataSource = self
self.listReops.estimatedRowHeight = 100
self.listReops.rowHeight = UITableViewAutomaticDimension
update()
}
func update() {
GitHub.shared.getRepos { (repositories) in
if let repositories = repositories {
self.allRepos = repositories
// self.searchedRepos = repositories
}
self.listReops.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == RepoDetailViewController.identifier {
if let selectedIndex = self.listReops.indexPathForSelectedRow?.row {
let selectedRepo = self.allRepos[selectedIndex]
guard let destinationController = segue.destination as? RepoDetailViewController else {
return
}
destinationController.repo = selectedRepo
}
segue.destination.transitioningDelegate = self
}
}
}
extension RepoViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomTransition(duration: 1.0)
}
}
//MARK: UITableViewDelegate
extension RepoViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allRepos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: RepoTableViewCell.identifier, for: indexPath) as! RepoTableViewCell
cell.repoNameLabel.text = allRepos[indexPath.row].name
cell.repoDescriptionLabel.text = allRepos[indexPath.row].description
cell.repoLanguageLabel.text = allRepos[indexPath.row].language
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: RepoDetailViewController.identifier, sender: nil)
}
}
//if !searchText.validate() {
// let lastIndex = searchText.index(before: searchText.endIndex)
// searchBar.text = searchText.substring(to: lastIndex)
//}
//
//if let searchedText = searchBar.text {
// self.displayRepos = self.allRepos.filter({$0.name.contains(searchedText)})
//}
| mit | f8e91382f21585959bf9993f99cb7c64 | 36.391304 | 170 | 0.681977 | 5.142003 | false | false | false | false |
hoffmanjon/SwiftyBones | Sources/SwiftyBones_Components/MiscComponents/SBLed.swift | 1 | 3155 | //
// SBLed.swift
// SwiftyBones Component Library
//
// Created by Jon Hoffman on 5/7/16.
//
/**
This type represents a LED connected to a Digital GPIO port. The SBLed type is a value type.
Initialize:
let runningLed = try SBLed(header: .P9, pin: 11, componentName: "Running LED")
or
let runningLed = try SBLed(gpio: SBDigitalGPIO(id: "gpio30", direction: .OUT), componentName: "Running LED")
Methods:
turnLedOn() -> Bool: Turns the LED on
turnLedOff() -> Bool: Turns the LED off
*/
struct SBLed: SBComponentOutProtocol {
let componentName: String
let gpio: SBDigitalGPIO
/**
Initlizes the SBLed type using a SBDigitalGPIO type and a name.
- Parameter gpio: An instances of a SBDigitalGPIO type
- Parameter componentName: A name for this instance that identifies it like "Power on led" or "Error led"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(gpio: GPIO?,componentName: String) throws {
guard gpio != nil else {
throw ComponentErrors.GPIOCanNotBeNil
}
if let testGpio = gpio as? SBDigitalGPIO {
self.gpio = testGpio
self.componentName = componentName
} else {
throw ComponentErrors.InvalidGPIOType("\(componentName): Expecting SBDigitalGPIO Type")
}
}
/**
Initlizes the SBLed type using the pin defined by the header and pin parameters for the LED. The component name defines a name for the LED.
- Parameter header: The header of the pin that the LED is connected too
- Parameter pin: The pin that the LED is connected too
- Parameter componentName: A name for this instance that identifies it like "Power on led" or "Error led"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(header: BBExpansionHeader, pin: Int, componentName: String) throws {
if let gpio = SBDigitalGPIO(header: header, pin: pin, direction: .OUT) {
self.gpio = gpio
self.componentName = componentName
} else {
throw ComponentErrors.GPIOCanNotBeNil
}
}
/**
Sets the raw value to the GPIO pin.
- Parameter value: This is the value to set. It can be either 0 or 1
- Returns: true if the value was successfully written
*/
func setRawValue(value: Int) -> Bool {
guard value >= 0 && value <= 1 else {
return false
}
let newValue = (value == 1) ? DigitalGPIOValue.HIGH : DigitalGPIOValue.LOW
if !gpio.setValue(newValue) {
return false
}
return true
}
/**
Turns the LED on by setting the GPIO pin high
- Returns: true if the value was successfully written
*/
func turnLedOn() -> Bool {
return setRawValue(1)
}
/**
Turns the LED off by setting the GPIO pin low
- Returns: true if the value was successfully written
*/
func turnLedOff() -> Bool {
return setRawValue(0)
}
}
| mit | e433a6937cd4098ec498adef1cfcde0a | 34.852273 | 145 | 0.638669 | 4.189907 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeConstants/AwesomeConstants/Classes/Constants/DeviceConstants.swift | 1 | 1262 | //
// SchemaConstants.swift
// Mindvalley
//
// Created by Evandro Harrison Hoffmann on 2/14/18.
// Copyright © 2018 Mindvalley. All rights reserved.
//
import UIKit
public var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
public var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
public var isPadPro1366: Bool {
return UIScreen.main.bounds.width >= 1366 || UIScreen.main.bounds.height >= 1366
}
public var isPhonePlus: Bool {
return UIScreen.main.traitCollection.displayScale == 3.0
}
public var isPhoneX: Bool {
return (UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436)
}
public var isLandscape: Bool {
return (UIDevice.current.orientation.isLandscape || !UIDevice.current.orientation.isPortrait) && UIDevice.current.orientation.isValidInterfaceOrientation
}
public var screenSizeDisregardingOrientation: CGSize {
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
return CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
}
return CGSize(width: UIScreen.main.bounds.height, height: UIScreen.main.bounds.width)
}
public var aspectRatio16_9: CGFloat {
return CGFloat(9.0/16.0)
}
| mit | 1d82e01f1f8518342f92275d4fac074f | 27.659091 | 157 | 0.740682 | 3.844512 | false | false | false | false |
huonw/swift | test/Constraints/type_of.swift | 15 | 2018 | // RUN: %target-swift-frontend -module-name main -typecheck -verify -swift-version 4 %s
struct S: P {}
protocol P {}
let _: S.Type = type(of: S())
let _ = type(of: S())
let _: P.Type = type(of: S() as P)
let _ = type(of: S() as P)
let _: P.Protocol = type(of: S() as P) // expected-error{{}}
let _: S.Type = Swift.type(of: S())
let _ = Swift.type(of: S())
let _: P.Type = Swift.type(of: S() as P)
let _ = Swift.type(of: S() as P)
let _: P.Protocol = Swift.type(of: S() as P) // expected-error{{}}
let _: (S) -> S.Type = type(of:) // expected-error{{}}
func type(_: S) -> S {}
func type(kinda _: S) -> Any.Type {}
let _ = type(S())
let _: S = type(S())
let _ = type(kinda: S())
let _: Any.Type = type(kinda: S())
struct Q {}
struct R {}
func type(of: Q) -> R {}
let _: R = type(of: Q())
let _: Q.Type = type(of: Q())
let _: Q.Type = Swift.type(of: Q())
let _: R = Swift.type(of: Q()) // expected-error{{}}
let _: Q.Type = main.type(of: Q()) // expected-error{{}}
let _: R = main.type(of: Q())
// Let's make sure that binding of the left-hand side
// of the dynamic-type-of constraint is not attempted.
class C {
typealias T = Int
}
// We need at least 4 classes here because type(of:)
// has 3 declarations in this file, and we need to
// try and make it so type(of:) picked as first overload.
class D : C {
typealias T = Float
}
class E : D {
typealias T = Double
}
class F : E {
typealias T = UInt
}
class G : F {
typealias T = Float
}
func foo(_: Any...) {}
// It's imperative for bar() to have more overloads
// the that of type(of:) to make sure that latter is
// picked first.
func bar() -> Int {} // expected-note {{found this candidate}}
func bar() -> Float {} // expected-note {{found this candidate}}
func bar() -> String {} // expected-note {{found this candidate}}
func bar() -> UInt {} // expected-note {{found this candidate}}
foo(type(of: G.T.self)) // Ok
let _: Any = type(of: G.T.self) // Ok
foo(type(of: bar())) // expected-error {{ambiguous use of 'bar()'}}
| apache-2.0 | c6bdb0af390029ec96aab06624dfffd7 | 24.225 | 87 | 0.590684 | 2.886981 | false | false | false | false |
wonderkiln/WKAwesomeMenu | WKAwesomeMenu/ProgressTimer.swift | 2 | 1500 | //
// ProgressTimer.swift
//
//
// Created by Adrian Mateoaea on 30.01.2016.
//
//
import UIKit
class ProgressTimer: NSObject {
var animationDuration: TimeInterval = 0.5
var animationFrom: CGFloat = 0
var animationInverse: Bool = false
var startTime: CFTimeInterval = 0
var callback: ((CGFloat) -> Void)?
static func createWithDuration(_ duration: TimeInterval, from: CGFloat = 0, inverse: Bool = false, callback: @escaping (CGFloat) -> Void) {
let timer = ProgressTimer()
timer.animationDuration = duration
timer.animationFrom = inverse ? 1 - from : from
timer.animationInverse = inverse
timer.callback = callback
timer.start()
}
func start() {
self.startTime = CACurrentMediaTime()
let link = CADisplayLink(target: self, selector: #selector(ProgressTimer.tick(_:)))
link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
func tick(_ link: CADisplayLink) {
let elapsed = link.timestamp - self.startTime
var percent = self.animationFrom + CGFloat((elapsed / self.animationDuration))
if self.animationInverse {
percent = 1 - percent
if percent <= 0 {
percent = 0
link.invalidate()
}
} else if percent >= 1 {
percent = 1
link.invalidate()
}
self.callback?(percent)
}
}
| mit | b888ae1d769854d470766174c3a4c8db | 25.785714 | 143 | 0.579333 | 4.761905 | false | false | false | false |
CCIP-App/CCIP-iOS | Submodules/SlideOverCard/Modifiers.swift | 1 | 1169 | import SwiftUI
extension View {
public func slideOverCard<Content: View>(isPresented: Binding<Bool>, onDismiss: (() -> Void)? = nil, options: SOCOptions = [], backgroundColor: Color = Color(.systemGray6), @ViewBuilder content: @escaping () -> Content) -> some View {
return ZStack {
self
SlideOverCard(
isPresented: isPresented,
onDismiss: onDismiss,
options: options,
backgroundColor: backgroundColor
) { content() }
}
}
public func slideOverCard<Item: Identifiable, Content: View>(item: Binding<Item?>, onDismiss: (() -> Void)? = nil, options: SOCOptions = [], backgroundColor: Color = Color(.systemGray6), @ViewBuilder content: @escaping (Item) -> Content) -> some View {
let binding = Binding(get: { item.wrappedValue != nil }, set: { if !$0 { item.wrappedValue = nil } })
return self.slideOverCard(isPresented: binding, onDismiss: onDismiss, options: options, backgroundColor: backgroundColor, content: {
if let item = item.wrappedValue {
content(item)
}
})
}
}
| gpl-3.0 | d9094dc20f4f873ac693df2a6d59b46e | 47.708333 | 256 | 0.599658 | 4.790984 | false | false | false | false |
symentis/Palau | Sources/PalauDefaultsArrayEntry.swift | 1 | 2891 | //
// PalauDefaultsEntry.swift
// Palau
//
// Created by symentis GmbH on 26.04.16.
// Copyright © 2016 symentis GmbH. 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
/// A PalauDefaultsArrayEntry
///
/// This entry takes care of list of values like
/// ```
/// public static var intValues: PalauDefaultsArrayEntry<Int>
/// get { return value("intValues") }
/// set { }
/// }
/// ```
/// The value of the PalauDefaultsArrayEntry is always an optional list e.g.
/// ```
/// // val is of type [Int]?
/// let values = PalauDefaults.intValues.value
/// ```
public struct PalauDefaultsArrayEntry<T: PalauDefaultable>: PalauEntry where T.ValueType == T {
public typealias ValueType = T
public typealias ReturnType = [T]
/// for convenience
public typealias PalauDidSetArrayFunction = (_ newValue: ReturnType?, _ oldValue: ReturnType?) -> Void
public typealias PalauEnsureArrayFunction = (ReturnType?) -> ReturnType?
/// The key of the entry
public let key: String
/// Access to the default
public let defaults: NSUD
/// A function to change the incoming and outgoing value
public let ensure: PalauEnsureArrayFunction
/// A function as callback after set
public let didSet: PalauDidSetArrayFunction?
/// a initializer
public init(key: String, defaults: UserDefaults, didSet: (([T]?, [T]?) -> Void)? = nil, ensure: @escaping ([T]?) -> [T]?) {
self.key = key
self.defaults = defaults
self.ensure = ensure
self.didSet = didSet
}
/// The value
/// use this property to get the Optional<ReturnType>
/// or to set the ReturnType
public var value: ReturnType? {
get {
return ensure(ValueType.get(key, from: defaults))
}
set {
withDidSet {
ValueType.set(self.ensure(newValue), forKey: self.key, in: self.defaults)
}
}
}
}
| apache-2.0 | 865dfb89815217ba73086b3be8859e55 | 33.404762 | 124 | 0.705536 | 4.140401 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/ActionArea/ExperimentDetailEmptyStateViewController.swift | 1 | 1785 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Typography_Typography
// TODO: This VC still needs a final image.
final class ExperimentDetailEmptyStateViewController: UIViewController {
private enum Metrics {
static let labelTextColor: UIColor = .lightGray
static let labelFont = MDCTypography.fontLoader().boldFont?(ofSize: 16)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let backgroundImageView =
UIImageView(image: UIImage(named: "action_area_add_notes"))
view.addSubview(backgroundImageView)
backgroundImageView.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-40)
}
let label = UILabel()
label.font = Metrics.labelFont
label.text = String.actionAreaAddMoreNotes
label.textColor = Metrics.labelTextColor
view.addSubview(label)
label.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(backgroundImageView.snp.bottom)
}
}
override var description: String {
return "\(type(of: self))"
}
}
| apache-2.0 | 5b3f1fcf73f24efb3b2fc1ff330fbf39 | 30.315789 | 87 | 0.72605 | 4.343066 | false | false | false | false |
afarber/ios-newbie | FetchJsonEscapable/FetchJsonEscapable/Persistence.swift | 1 | 2526 | //
// Persistence.swift
// FetchJsonEscapable
//
// Created by Alexander Farber on 02.05.21.
//
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let moc = result.container.viewContext
for var i in 0..<10 {
let newTop = TopEntity(context: moc)
newTop.uid = Int32(i)
newTop.elo = 1500
newTop.given = "Person \(newTop.uid + 1)"
}
do {
try moc.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Tops")
container.viewContext.mergePolicy = NSMergePolicy.overwrite
container.viewContext.automaticallyMergesChangesFromParent = true
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
| unlicense | 435e5dd816ba888ee435a28442c85574 | 41.813559 | 199 | 0.632621 | 5.385928 | false | false | false | false |
feiin/VPNOn | VPNOnData/VPNDataManager+Selection.swift | 22 | 1145 | //
// VPNDataManager+Selection.swift
// VPNOn
//
// Created by Lex Tang on 1/20/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import CoreData
let kSelectedVPNIDKey = "lastVPNID"
extension VPNDataManager
{
var selectedVPNID: NSManagedObjectID? {
get {
if let URLData = NSUserDefaults.standardUserDefaults().objectForKey(kSelectedVPNIDKey) as! NSData? {
let url = NSKeyedUnarchiver.unarchiveObjectWithData(URLData) as! NSURL
if let ID = self.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(url) {
return ID
}
}
return .None
}
set {
if let value = newValue {
let IDURL = value.URIRepresentation()
let URLData = NSKeyedArchiver.archivedDataWithRootObject(IDURL)
NSUserDefaults.standardUserDefaults().setObject(URLData, forKey: kSelectedVPNIDKey)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(kSelectedVPNIDKey)
}
}
}
}
| mit | 205858a5942c9069a8e39a380a17274a | 29.945946 | 112 | 0.61048 | 5.134529 | false | false | false | false |
stripe/stripe-ios | Stripe/STPCameraView.swift | 1 | 2049 | //
// STPCameraView.swift
// StripeiOS
//
// Created by David Estes on 8/17/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import AVFoundation
import UIKit
@available(macCatalyst 14.0, *)
class STPCameraView: UIView {
private var flashLayer: CALayer?
var captureSession: AVCaptureSession? {
get {
return (videoPreviewLayer.session)!
}
set(captureSession) {
videoPreviewLayer.session = captureSession
}
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
func playSnapshotAnimation() {
CATransaction.begin()
CATransaction.setValue(
kCFBooleanTrue,
forKey: kCATransactionDisableActions
)
flashLayer?.frame = CGRect(
x: 0,
y: 0,
width: layer.bounds.size.width,
height: layer.bounds.size.height
)
flashLayer?.opacity = 1.0
CATransaction.commit()
DispatchQueue.main.async(execute: {
let fadeAnim = CABasicAnimation(keyPath: "opacity")
fadeAnim.fromValue = NSNumber(value: 1.0)
fadeAnim.toValue = NSNumber(value: 0.0)
fadeAnim.duration = 1.0
self.flashLayer?.add(fadeAnim, forKey: "opacity")
self.flashLayer?.opacity = 0.0
})
}
override init(
frame: CGRect
) {
super.init(frame: frame)
flashLayer = CALayer()
if let flashLayer = flashLayer {
layer.addSublayer(flashLayer)
}
flashLayer?.masksToBounds = true
flashLayer?.backgroundColor = UIColor.black.cgColor
flashLayer?.opacity = 0.0
layer.masksToBounds = true
videoPreviewLayer.videoGravity = .resizeAspectFill
}
override class var layerClass: AnyClass {
return AVCaptureVideoPreviewLayer.self
}
required init?(
coder aDecoder: NSCoder
) {
super.init(coder: aDecoder)
}
}
| mit | 2d815071f0c8975aaabf6428c0d724ca | 25.597403 | 63 | 0.600586 | 4.818824 | false | false | false | false |
yacir/YBSlantedCollectionViewLayout | Tests/CollectionViewSlantedLayoutTests.swift | 1 | 10416 | /**
This file is part of the CollectionViewSlantedLayout package.
Copyright © 2017 Yassir Barchi <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
@testable import CollectionViewSlantedLayout
import XCTest
class CollectionViewSlantedLayoutTests: XCTestCase {
var verticalSlantedViewLayout: CollectionViewSlantedLayout!
var collectionViewController: CollectionViewController!
var horizontalSlantedViewLayout: CollectionViewSlantedLayout!
var horizontalCollectionViewController: CollectionViewController!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
verticalSlantedViewLayout = CollectionViewSlantedLayout()
verticalSlantedViewLayout.itemSize = 225
verticalSlantedViewLayout.slantingSize = 50
verticalSlantedViewLayout.lineSpacing = 0
verticalSlantedViewLayout.slantingDirection = .downward
collectionViewController = CollectionViewController(collectionViewLayout: verticalSlantedViewLayout)
collectionViewController.view.frame = CGRect(x: 0, y: 0, width: 600, height: 600)
horizontalSlantedViewLayout = CollectionViewSlantedLayout()
horizontalSlantedViewLayout.scrollDirection = UICollectionView.ScrollDirection.horizontal
horizontalSlantedViewLayout.lineSpacing = 3
horizontalSlantedViewLayout.itemSize = 300
horizontalSlantedViewLayout.slantingDirection = .downward
horizontalSlantedViewLayout.zIndexOrder = .descending
horizontalSlantedViewLayout.isFirstCellExcluded = true
horizontalSlantedViewLayout.isLastCellExcluded = true
horizontalCollectionViewController = CollectionViewController(collectionViewLayout: horizontalSlantedViewLayout)
horizontalCollectionViewController.view.frame = CGRect(x: 0, y: 0, width: 600, height: 600)
}
func testSlantedViewLayoutHasDefaultValues() {
let defaultSlantedViewLayout = CollectionViewSlantedLayout()
XCTAssertEqual(defaultSlantedViewLayout.slantingSize, 75)
XCTAssertEqual(defaultSlantedViewLayout.slantingDirection, .upward)
XCTAssertEqual(defaultSlantedViewLayout.isFirstCellExcluded, false)
XCTAssertEqual(defaultSlantedViewLayout.isLastCellExcluded, false)
XCTAssertEqual(defaultSlantedViewLayout.lineSpacing, 10)
XCTAssertEqual(defaultSlantedViewLayout.scrollDirection, UICollectionView.ScrollDirection.vertical)
XCTAssertEqual(defaultSlantedViewLayout.itemSize, 225)
XCTAssertEqual(defaultSlantedViewLayout.zIndexOrder, .ascending)
}
func testLayoutContentViewSizeUsesController() {
collectionViewController.items = [0, 1, 2, 3, 5, 6, 7, 8, 9]
collectionViewController.itemSize = 150
collectionViewController.view.layoutIfNeeded()
let verticalSlantedViewLayoutSize = self.verticalSlantedViewLayout.collectionViewContentSize
let collectionViewControllerSize = self.collectionViewController.view.frame.size
let size = collectionViewController.itemSize
let lineSpicing = verticalSlantedViewLayout.lineSpacing
let slantingDelta = CGFloat(verticalSlantedViewLayout.slantingSize)
let itemSize = size! - slantingDelta + lineSpicing
let contentSize = (CGFloat(collectionViewController.items.count) * itemSize) + slantingDelta - lineSpicing
XCTAssertEqual(verticalSlantedViewLayoutSize.width, collectionViewControllerSize.width)
XCTAssertEqual(verticalSlantedViewLayoutSize.height, contentSize)
}
func testHorizontalLayoutContentViewSizeUsesController() {
horizontalCollectionViewController.items = [0, 1, 2, 3, 5, 6, 7, 8, 9]
horizontalCollectionViewController.view.layoutIfNeeded()
let horizontalSlantedViewLayoutSize = horizontalSlantedViewLayout.collectionViewContentSize
let collectionViewControllerSize = horizontalCollectionViewController.view.frame.size
let size = horizontalSlantedViewLayout.itemSize
let lineSpicing = horizontalSlantedViewLayout.lineSpacing
let slantingDelta = CGFloat(horizontalSlantedViewLayout.slantingSize)
let sectionSize = size - slantingDelta + lineSpicing
let count = CGFloat(horizontalCollectionViewController.items.count)
let contentSize = (count * sectionSize) + slantingDelta - lineSpicing
XCTAssertEqual(horizontalSlantedViewLayoutSize.width, contentSize)
XCTAssertEqual(horizontalSlantedViewLayoutSize.height, collectionViewControllerSize.height)
}
func testLayoutContentViewSizeUsesItemSizeIfDelegateMethodIsNotImplemented() {
collectionViewController.items = [0, 1, 2, 3, 5, 6, 7, 8, 9]
collectionViewController.collectionView?.delegate = nil
collectionViewController.view.layoutIfNeeded()
let verticalSlantedViewLayoutSize = self.verticalSlantedViewLayout.collectionViewContentSize
let collectionViewControllerSize = self.collectionViewController.view.frame.size
let size = verticalSlantedViewLayout.itemSize
let lineSpicing = verticalSlantedViewLayout.lineSpacing
let slantingDelta = CGFloat(verticalSlantedViewLayout.slantingSize)
let sectionSize = size - slantingDelta + lineSpicing
let count = CGFloat(collectionViewController.items.count)
let contentSize = (count * sectionSize) + slantingDelta - lineSpicing
XCTAssertEqual(verticalSlantedViewLayoutSize.width, collectionViewControllerSize.width)
XCTAssertEqual(verticalSlantedViewLayoutSize.height, contentSize)
collectionViewController.collectionView?.delegate = collectionViewController
}
func testThatZIndexAscendingOrderWorksAsExcpected() {
verticalSlantedViewLayout.slantingDirection = .upward
collectionViewController.items = [0, 1]
collectionViewController.view.layoutIfNeeded()
let firstItemIndexPath = IndexPath(item: 0, section: 0)
let firstItemZIndex = verticalSlantedViewLayout.layoutAttributesForItem(at: firstItemIndexPath)?.zIndex
let secondItemIndexPath = IndexPath(item: 1, section: 0)
let secondItemZIndex = verticalSlantedViewLayout.layoutAttributesForItem(at: secondItemIndexPath)?.zIndex
XCTAssertTrue(firstItemZIndex! < secondItemZIndex!)
}
func testThatZIndexDescendingOrderWorksAsExcpected() {
horizontalSlantedViewLayout.slantingDirection = .upward
horizontalCollectionViewController.items = [0, 1]
horizontalCollectionViewController.view.layoutIfNeeded()
let firstItemIndexPath = IndexPath(item: 0, section: 0)
let firstItemZIndex = horizontalSlantedViewLayout.layoutAttributesForItem(at: firstItemIndexPath)?.zIndex
let secondItemIndexPath = IndexPath(item: 1, section: 0)
let secondItemZIndex = horizontalSlantedViewLayout.layoutAttributesForItem(at: secondItemIndexPath)?.zIndex
XCTAssertTrue(firstItemZIndex! > secondItemZIndex!)
}
func testThatSlantingAngleIsWellCalculated() {
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 300, height: 600),
collectionViewLayout: verticalSlantedViewLayout)
let layout = CollectionViewSlantedLayout()
collectionView.collectionViewLayout = layout
layout.slantingSize = 150
XCTAssertEqual(layout.slantingAngle, -0.5)
layout.slantingDirection = .downward
XCTAssertEqual(layout.slantingAngle, 0.5)
layout.scrollDirection = .horizontal
XCTAssertEqual(layout.slantingAngle, -0.25)
layout.slantingDirection = .upward
XCTAssertEqual(layout.slantingAngle, 0.25)
}
func testLayoutHasSmoothScrolling() {
let proposedOffset = verticalSlantedViewLayout.targetContentOffset(forProposedContentOffset: CGPoint(),
withScrollingVelocity: CGPoint())
XCTAssertEqual(proposedOffset.x, 0)
XCTAssertEqual(proposedOffset.y, 0)
}
func testLayoutHasCachedLayoutAttributes() {
collectionViewController.items = [0]
collectionViewController.view.layoutIfNeeded()
XCTAssertEqual(verticalSlantedViewLayout.cachedAttributes.count, 1)
}
func testLayoutAttributeIsCached() {
collectionViewController.items = [0]
collectionViewController.view.layoutIfNeeded()
let attributes = verticalSlantedViewLayout.layoutAttributesForElements(in: CGRect())!
XCTAssertEqual(verticalSlantedViewLayout.cachedAttributes, attributes)
}
func testLayoutHasLayoutAttributesAtIndexPath() {
collectionViewController.items = [0, 1, 2]
collectionViewController.view.layoutIfNeeded()
let indexPath = IndexPath(item: 0, section: 0)
let attribute = verticalSlantedViewLayout.layoutAttributesForItem(at: indexPath)
XCTAssertEqual(verticalSlantedViewLayout.cachedAttributes[0], attribute)
}
func testLayoutShouldInvalidateLayoutForBoundsChange() {
collectionViewController.view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
collectionViewController.view.layoutIfNeeded()
XCTAssertTrue(verticalSlantedViewLayout.shouldInvalidateLayout(forBoundsChange: CGRect()))
}
}
| mit | d2b33daec33f33be304c6bc06bb9f0e0 | 49.558252 | 120 | 0.756889 | 5.14321 | false | true | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/BlixtTransitionAnimation.swift | 1 | 4035 | //
// BlixtTransitionAnimation.swift
// TransitionTreasury
//
// Created by DianQK on 1/1/16.
// Copyright © 2016 TransitionTreasury. All rights reserved.
//
import UIKit
//import TransitionTreasury
public class BlixtTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning, TransitionInteractiveable {
public var keyView: UIView
public var transitionStatus: TransitionStatus
public var transitionContext: UIViewControllerContextTransitioning?
public var percentTransition: UIPercentDrivenInteractiveTransition?
public var completion: (() -> Void)?
public var cancelPop: Bool = false
public var interacting: Bool = false
public let toFrame: CGRect
private lazy var keyViewCopy: UIView = self.keyView.tr_copyWithSnapshot()
public init(key: UIView, toFrame frame:CGRect, status: TransitionStatus = .push) {
keyView = key
toFrame = frame
transitionStatus = status
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let containView = transitionContext.containerView
let leftX: CGFloat = 0
let rightX = UIScreen.main.bounds.width
fromVC?.view.layer.frame.origin.x = leftX
toVC?.view.layer.frame.origin.x = transitionStatus == .push ? rightX : -rightX
containView.addSubview(fromVC!.view)
containView.addSubview(toVC!.view)
containView.tr_addSubview(keyViewCopy, convertFrom: (transitionStatus == .push ? keyView : keyViewCopy))
keyView.layer.opacity = 0
func bounce(_ completion: (() -> Void)? = nil) {
UIView.animate(withDuration: 0.1) {
self.keyViewCopy.frame = containView.convert(self.keyView.frame.tr_shape(0.97), from: self.keyView.superview)
}
UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseInOut, animations: {
self.keyViewCopy.frame = containView.convert(self.keyView.frame, from: self.keyView.superview)
}) { finished in
completion?()
}
}
if transitionStatus == .push {
bounce()
}
UIView.animate(withDuration: transitionDuration(using: transitionContext) - 0.2, delay: 0.2, options: .curveEaseInOut, animations: {
switch self.transitionStatus {
case .push :
fromVC?.view.layer.frame.origin.x = -rightX
toVC?.view.layer.frame.origin.x = leftX
self.keyViewCopy.frame = self.toFrame
case .pop :
fromVC?.view.layer.frame.origin.x = rightX
toVC?.view.layer.frame.origin.x = leftX
self.keyViewCopy.frame = containView.convert(self.keyView.frame, from: self.keyView.superview)
default :
fatalError("You set false status.")
}
}) { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
if finished && !self.cancelPop {
toVC?.view.addSubview(self.keyViewCopy)
if self.transitionStatus == .pop {
self.keyView.layer.opacity = 1
self.keyViewCopy.removeFromSuperview()
}
self.completion?()
self.completion = nil
}
self.cancelPop = false
}
}
}
| mit | 1c7c67eda4e379001167c7f6e844b5b9 | 37.788462 | 140 | 0.615022 | 5.3219 | false | false | false | false |
kentya6/NexturnController | NexturnController/CentralManager.swift | 1 | 2181 | //
// CentralManager.swift
// NexturnController
//
// Created by Kengo Yokoyama on 2014/12/24.
// Copyright (c) 2014年 Kengo Yokoyama. All rights reserved.
//
import Foundation
import CoreBluetooth
class CentralManager: CBCentralManager {
fileprivate var nexturnObjectArray = [NexturnObject]()
override init(delegate: CBCentralManagerDelegate?, queue: DispatchQueue?, options: [String : Any]? = nil) {
super.init(delegate: delegate, queue: queue, options: options)
self.delegate = self
}
// MARK: - Call from IBAction
func ledButtonTapped(_ tag: NSInteger) {
for nexturnObject in nexturnObjectArray {
nexturnObject.ledButtonTapped(tag)
}
}
}
extension CentralManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
let options = ["CBCentralManagerScanOptionAllowDuplicatesKey" : true]
scanForPeripherals(withServices: nil, options: options)
default:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard let name = peripheral.name else {
return
}
switch name {
case NexturnObject.Property.kName:
let nexturnObject = NexturnObject()
peripheral.delegate = nexturnObject
nexturnObject.peripheral = peripheral
connect(nexturnObject.peripheral!, options: nil)
nexturnObjectArray.append(nexturnObject)
default:
break
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
guard let name = peripheral.name else {
return
}
switch name {
case NexturnObject.Property.kName:
let UUID = CBUUID(string: NexturnObject.Property.kLEDServiceUUID)
nexturnObjectArray.last?.peripheral?.discoverServices([UUID])
default:
break
}
}
}
| mit | bdde89ca6588e8e4437f245a59b9443d | 30.128571 | 148 | 0.635154 | 4.831486 | false | false | false | false |
dankogai/swift-immutablearray | immutablearray.swift | 1 | 2625 | //
// immutablearray.swift
// immutablearray
//
// Created by Dan Kogai on 6/29/14.
// Copyright (c) 2014 Dan Kogai. All rights reserved.
//
class ImmutableArray<T> {
typealias Element = T
let vault:()->T[]
let count:Int
init() { vault = {[]}; count = 0 }
init(_ array:T[]) {
let copy = array.copy()
vault = {copy}
count = array.count
}
init(_ elements:T...) {
vault = {elements}
count = elements.count
}
}
extension ImmutableArray: Collection {
var startIndex:Int { return vault().startIndex }
var endIndex:Int { return vault().endIndex }
subscript (index:Int) -> T {
return vault()[index]
}
subscript (range:Range<Int>) -> ImmutableArray<T> {
return ImmutableArray(Array(vault()[range]))
}
func generate() -> IndexingGenerator<Array<T>> {
return vault().generate()
}
}
extension ImmutableArray : Printable, DebugPrintable {
var description:String {
return vault().description
}
var debugDescription:String {
return vault().debugDescription
}
}
@infix func ==<T: Equatable>(
lhs:ImmutableArray<T>, rhs:ImmutableArray<T>
)->Bool {
return lhs.vault() == rhs.vault()
}
@infix func ==<T: Equatable>(
lhs:ImmutableArray<T>, rhs:Array<T>
)->Bool {
return lhs.vault() == rhs
}
@infix func ==<T: Equatable>(
lhs:Array<T>, rhs:ImmutableArray<T>
)->Bool {
return lhs == rhs.vault()
}
@infix func !=<T: Equatable>(
lhs:ImmutableArray<T>, rhs:ImmutableArray<T>
)->Bool {
return lhs.vault() != rhs.vault()
}
@infix func !=<T: Equatable>(
lhs:ImmutableArray<T>, rhs:Array<T>
)->Bool {
return lhs.vault() != rhs
}
@infix func !=<T: Equatable>(
lhs:Array<T>, rhs:ImmutableArray<T>
)->Bool {
return lhs != rhs.vault()
}
extension ImmutableArray {
var isEmpty:Bool { return count == 0 }
func sort(block:(T,T)->Bool) -> ImmutableArray<T> {
let newarray = vault()
newarray.sort(block)
return ImmutableArray(newarray)
}
func filter(block:(T)->Bool) -> ImmutableArray<T> {
return ImmutableArray(vault().filter(block))
}
func map<U>(block:(T)->U) -> ImmutableArray<U> {
return ImmutableArray<U>(vault().map(block))
}
func reduce<U>(start:U, block:(U,T)->U) -> U {
return vault().reduce(start,block)
}
func reverse() -> ImmutableArray<T> {
return ImmutableArray(vault().reverse())
}
}
extension Array {
func immutable() -> ImmutableArray<T> {
return ImmutableArray(self)
}
}
| mit | 2ccf8e5a5187755c0f96c0e0d92b9c3f | 25.515152 | 55 | 0.590857 | 3.552097 | false | false | false | false |
Chuck8080/ios-swift-places | SwiftPlaces/Place.swift | 1 | 1281 | //
// Place.swift
// SwiftPlaces
//
// Created by Joshua Smith on 7/26/14.
// Copyright (c) 2014 iJoshSmith. All rights reserved.
//
import Foundation
/**
Data entity that represents a geographic area.
Subclasses NSObject to enable Obj-C instantiation.
*/
class Place : NSObject, Equatable
{
let
latitude: Double,
longitude: Double,
name: String,
postalCode: String
init(
latitude: Double,
longitude: Double,
name: String,
postalCode: String)
{
self.latitude = latitude
self.longitude = longitude
self.name = name
self.postalCode = postalCode
}
// Used by Foundation collections, such as NSSet.
override var hash: Int
{
get { return hashValue }
}
// I'm not sure where this is inherited from,
// or if it needs to be overridden.
override var hashValue: Int
{
get { return name.hashValue }
}
// Used by Foundation collections, such as NSSet.
override func isEqual(object: AnyObject!) -> Bool
{
return self == object as Place
}
}
// Required for Equatable protocol conformance
func == (lhs: Place, rhs: Place) -> Bool
{
return lhs.name == rhs.name
}
| mit | 473f647b03091299f30c83ba4e8fb9e7 | 20.711864 | 55 | 0.599532 | 4.227723 | false | false | false | false |
argent-os/argent-ios | app-ios/Auth.swift | 1 | 3555 | //
// Auth.swift
// app-ios
//
// Created by Sinan Ulkuatam on 5/11/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import Crashlytics
class Auth {
let username: String
let email: String
let password: String
required init(username: String, email: String, password: String) {
self.username = username
self.email = email
self.password = password
}
class func login(email: String, username: String, password: String, completionHandler: (String, Bool, String, NSError) -> ()) {
// check for empty fields
if(email.isEmpty) {
// display alert message
return;
} else if(password.isEmpty) {
return;
}
Alamofire.request(.POST, API_URL + "/login", parameters: [
"username": username,
"email":email,
"password":password
],
encoding:.JSON)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
// print(totalBytesWritten)
// print(totalBytesExpectedToWrite)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
// print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
// go to main view
if(response.response?.statusCode == 200) {
NSUserDefaults.standardUserDefaults().setBool(true,forKey:"userLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
} else {
// display error
}
switch response.result {
case .Success:
if let value = response.result.value {
let data = JSON(value)
// completion handler here for apple watch
let token = data["token"].stringValue
if response.result.error != nil {
completionHandler(token, false, username, response.result.error!)
} else {
completionHandler(token, true, username, NSError(domain: "nil", code: 000, userInfo: [:]))
}
NSUserDefaults.standardUserDefaults().setValue(token, forKey: "userAccessToken")
NSUserDefaults.standardUserDefaults().synchronize()
Answers.logLoginWithMethod("Access",
success: true,
customAttributes: nil)
// go to main view from completion handler
// self.performSegueWithIdentifier("homeView", sender: self);
}
case .Failure(let error):
print(error)
Answers.logLoginWithMethod("Access",
success: false,
customAttributes: nil)
// display error
}
}
}
} | mit | edf57ba27b6809bfb04ddbd6d177a65f | 35.649485 | 131 | 0.481148 | 6.246046 | false | false | false | false |
tominated/Quake-3-BSP-Renderer | Quake 3 BSP Renderer/Targa.swift | 1 | 2920 | //
// Targa.swift
// Quake 3 BSP Renderer
//
// Created by Thomas Brunoli on 14/01/2016.
// Copyright © 2016 Thomas Brunoli. All rights reserved.
//
import Foundation
import UIKit
func imageFromTGAData(_ data: Data) -> UIImage? {
let buffer = BinaryReader(data: data)
buffer.skip(2)
let imageType = buffer.getUInt8()
// Unsupported file type
if (imageType != 2 && imageType != 3) {
return nil
}
buffer.skip(9)
let width = Int(buffer.getUInt16())
let height = Int(buffer.getUInt16())
let bitDepth = Int(buffer.getUInt8())
let colorMode = bitDepth / 8
let imageDataLength = width * height * 4
var imageData: Array<UInt8> = []
imageData.reserveCapacity(imageDataLength)
buffer.skip(1)
// Swap image data from BGR(A) to RGBA
for _ in 0..<(width * height) {
let b = buffer.getUInt8()
let g = buffer.getUInt8()
let r = buffer.getUInt8()
let a = colorMode == 4 ? buffer.getUInt8() : 1
imageData.append(r)
imageData.append(g)
imageData.append(b)
imageData.append(a)
}
// Invert the Y axis
for y in 0..<(height / 2) {
for x in 0..<width {
let topIndex = y * width + x
let bottomIndex = (height - 1 - y) * width + x
for i in 0 ..< 4 {
let top = imageData[topIndex + i]
let bottom = imageData[bottomIndex + i]
imageData[topIndex + i] = bottom
imageData[bottomIndex + i] = top
}
}
}
let finalData = Data(bytes: imageData, count: imageDataLength)
return imageFromRGBAData(finalData, width: width, height: height)
}
private func imageFromRGBAData(_ data: Data, width: Int, height: Int) -> UIImage? {
let pixelData = (data as NSData).bytes
let bytesPerPixel = 4
let scanWidth = bytesPerPixel * width
let provider = CGDataProvider(dataInfo: nil, data: pixelData, size: height * scanWidth, releaseData: { _,_,_ in () })
let colorSpaceRef = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.last.rawValue)
let renderingIntent: CGColorRenderingIntent = .defaultIntent
let imageRef = CGImage(
width: width,
height: height,
bitsPerComponent: 8, // bitsPerComponent
bitsPerPixel: 32, // bitsPerPixel
bytesPerRow: scanWidth, // bytesPerRow
space: colorSpaceRef, // colorspace
bitmapInfo: bitmapInfo, // bitmapInfo
provider: provider!, // provider
decode: nil, // decode
shouldInterpolate: false, // shouldInterpolate
intent: renderingIntent // intent
)
if let ref = imageRef {
return UIImage(cgImage: ref)
}
return nil
}
| mit | eaf276132faedeffd27a9fc54db41773 | 27.067308 | 122 | 0.595409 | 4.363229 | false | false | false | false |
CH-HOWIE/Swift3_UITabBar_kvc | LoveFreshBeen_swift3.0/Classes/Home/View/HomeTableHeaderView.swift | 1 | 1034 | //
// HomeTableHeaderView.swift
// LoveFreshBeen_swift3.0
//
// Created by HOWIE-CH on 16/7/25.
// Copyright © 2016年 Howie. All rights reserved.
//
import UIKit
class HomeTableHeaderView: UIView {
@IBOutlet weak var pageImgView: DIYPageImgView!
@IBOutlet weak var firstButton: IconButton!
@IBOutlet weak var secondButton: IconButton!
@IBOutlet weak var thirdButton: IconButton!
@IBOutlet weak var lastButton: IconButton!
var iconItemArray: [IconsItem]? {
didSet{
guard let tempArray = iconItemArray else {
return
}
firstButton.item = tempArray[0]
secondButton.item = tempArray[1]
thirdButton.item = tempArray[2]
lastButton.item = tempArray[3]
}
}
class func homeTableHeaderCreate() -> HomeTableHeaderView {
return Bundle.main.loadNibNamed("HomeTableHeaderView", owner: nil, options: nil)[0] as! HomeTableHeaderView
}
}
| apache-2.0 | 1adeef7413dc483f85b68782d29cddcb | 24.775 | 115 | 0.615907 | 4.54185 | false | false | false | false |
wess/inquire | Sources/EmailField.swift | 2 | 838 | //
// EmailField.swift
// Inquire
//
// Created by Wesley Cope on 2/12/16.
// Copyright © 2016 Wess Cope. All rights reserved.
//
import Foundation
import UIKit
/// UITextField with email validation by default.
open class EmailField : TextField {
override open var validators: [ValidationRule] {
didSet {
let filtered = validators.filter { $0.pattern == Email.pattern }
if filtered.count == 0 {
validators.append(Email)
}
}
}
public required init(validators: [ValidationRule], setup: ((TextField) -> Void)?) {
super.init(validators: validators, setup: setup)
self.validators.append(Email)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1d8dc8eca3d0b4738a6306b3ea7bb22f | 25.15625 | 87 | 0.610514 | 4.359375 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/ProfileInfoViewController.swift | 1 | 21876 | //
// ProfileInfoViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 9/15/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import Anchorage
import BadgeSwift
import reddift
import RLBAlertsPickers
import SDCAlertView
import SDWebImage
import Then
import UIKit
class ProfileInfoViewController: UIViewController {
var user: Account?
weak var profile: UIViewController?
var interactionController: ProfileInfoDismissInteraction?
/// Overall height of the content view, including its out-of-bounds elements.
var contentViewHeight: CGFloat {
let converted = accountImageView.convert(accountImageView.bounds, to: view)
return view.frame.maxY - converted.minY
}
var outOfBoundsHeight: CGFloat {
let converted = accountImageView.convert(accountImageView.bounds, to: view)
return contentView.frame.minY - converted.minY
}
var spinner = UIActivityIndicatorView().then {
$0.style = UIActivityIndicatorView.Style.whiteLarge
$0.color = ColorUtil.theme.fontColor
$0.hidesWhenStopped = true
}
var contentView = UIView().then {
$0.backgroundColor = ColorUtil.theme.backgroundColor
$0.clipsToBounds = false
}
var backgroundView = UIView().then {
$0.backgroundColor = .clear
}
var closeButton = UIButton(type: .custom).then {
$0.setImage(UIImage(sfString: SFSymbol.xmark, overrideString: "close")!.getCopy(withSize: .square(size: 30), withColor: .white), for: UIControl.State.normal)
$0.contentEdgeInsets = UIEdgeInsets(top: 4, left: 16, bottom: 24, right: 24)
$0.accessibilityLabel = "Close"
}
// Content
var accountNameLabel = UILabel().then {
$0.font = FontGenerator.boldFontOfSize(size: 28, submission: false)
$0.textColor = ColorUtil.theme.fontColor
$0.numberOfLines = 1
$0.adjustsFontSizeToFitWidth = true
$0.minimumScaleFactor = 0.5
$0.baselineAdjustment = UIBaselineAdjustment.alignCenters
}
var accountAgeLabel = UILabel().then {
$0.font = FontGenerator.fontOfSize(size: 12, submission: false)
$0.textColor = ColorUtil.theme.fontColor
$0.numberOfLines = 1
$0.text = ""
}
var accountImageView = UIImageView().then {
$0.backgroundColor = ColorUtil.theme.foregroundColor
$0.contentMode = .scaleAspectFit
if #available(iOS 11.0, *) {
$0.accessibilityIgnoresInvertColors = true
}
if !SettingValues.flatMode {
$0.elevate(elevation: 2.0)
$0.layer.cornerRadius = 10
$0.clipsToBounds = true
}
}
var header = ProfileHeaderView()
var account: String
init(accountNamed: String, parent: UIViewController) {
self.account = accountNamed
self.profile = parent
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupConstraints()
setupActions()
interactionController = ProfileInfoDismissInteraction(viewController: self)
configureForAccount(named: account)
}
var setStyle: UIStatusBarStyle = .default {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return setStyle
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Focus the account label
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: accountNameLabel)
setStyle = .lightContent
}
override func viewWillDisappear(_ animated: Bool) {
setStyle = SettingValues.reduceColor && ColorUtil.theme.isLight ? .default : .lightContent
}
}
// MARK: - Setup
extension ProfileInfoViewController {
func setupViews() {
view.addSubview(backgroundView)
view.addSubview(closeButton)
view.addSubview(contentView)
contentView.addSubview(accountImageView)
contentView.addSubview(accountNameLabel)
contentView.addSubview(accountAgeLabel)
contentView.addSubview(header)
header.delegate = self
contentView.addSubview(spinner)
}
func setupConstraints() {
backgroundView.edgeAnchors == view.edgeAnchors
if #available(iOS 11, *) {
closeButton.topAnchor == view.safeTopAnchor
closeButton.leftAnchor == view.safeLeftAnchor
} else {
closeButton.topAnchor == view.safeTopAnchor + 24
closeButton.leftAnchor == view.safeLeftAnchor
}
contentView.horizontalAnchors == view.horizontalAnchors
contentView.bottomAnchor == view.bottomAnchor
accountImageView.leftAnchor == contentView.safeLeftAnchor + 20
accountImageView.centerYAnchor == contentView.topAnchor
accountImageView.sizeAnchors == CGSize.square(size: 100)
accountNameLabel.topAnchor == contentView.topAnchor + 8
accountNameLabel.leftAnchor == accountImageView.rightAnchor + 20
accountNameLabel.rightAnchor == contentView.rightAnchor - 20
accountAgeLabel.leftAnchor == accountNameLabel.leftAnchor
accountAgeLabel.topAnchor == accountNameLabel.bottomAnchor
header.topAnchor == accountAgeLabel.bottomAnchor + 22
header.horizontalAnchors == contentView.safeHorizontalAnchors + 20
header.bottomAnchor == contentView.safeBottomAnchor - 16
spinner.centerAnchors == header.centerAnchors
}
func setupActions() {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(didRequestClose))
backgroundView.addGestureRecognizer(recognizer)
}
func generateButtons(trophy: Trophy) -> UIView {
let baseView = UIView()
let more = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50))
more.sd_setImage(with: trophy.icon70!)
let subtitle = UILabel().then {
$0.textColor = ColorUtil.theme.fontColor
$0.font = UIFont.systemFont(ofSize: 10)
$0.text = trophy.title
$0.numberOfLines = 0
$0.textAlignment = .center
}
baseView.addSubview(more)
baseView.addSubview(subtitle)
more.horizontalAnchors == baseView.horizontalAnchors + 10
more.heightAnchor == 50
more.topAnchor == baseView.topAnchor
more.widthAnchor == 50
subtitle.heightAnchor == 15
subtitle.horizontalAnchors == baseView.horizontalAnchors
subtitle.topAnchor == more.bottomAnchor + 5
subtitle.widthAnchor == 70
baseView.isUserInteractionEnabled = true
return baseView
}
func getTrophies(_ user: Account) {
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.getTrophies(user.name, completion: { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let trophies):
var i = 0
DispatchQueue.main.async {
for trophy in trophies {
let b = self.generateButtons(trophy: trophy)
b.sizeAnchors == CGSize(width: 70, height: 70)
b.addTapGestureRecognizer(action: {
if trophy.url != nil {
var trophyURL = trophy.url!.absoluteString
if !trophyURL.contains("reddit.com") {
trophyURL = "https://www.reddit.com" + trophyURL
}
VCPresenter.presentModally(viewController: WebsiteViewController(url: URL(string: trophyURL) ?? trophy.url!, subreddit: ""), self, nil)
}
})
self.header.trophyArea.addSubview(b)
b.leftAnchor == self.header.trophyArea.leftAnchor + CGFloat(i * 75)
i += 1
}
if trophies.isEmpty {
let empty = UILabel(frame: CGRect(x: 0, y: 0, width: self.header.trophyArea.frame.size.width, height: 70))
empty.font = UIFont.boldSystemFont(ofSize: 14)
empty.textAlignment = .center
empty.text = "No trophies"
self.header.trophyArea.addSubview(empty)
self.header.trophyArea.contentSize = CGSize.init(width: self.header.trophyArea.frame.size.width, height: 70)
} else {
self.header.trophyArea.contentSize = CGSize.init(width: i * 75, height: 70)
}
}
}
})
} catch {
}
}
func configureForAccount(named: String) {
setLoadingState(true)
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.getUserProfile(named, completion: { (result) in
switch result {
case .failure(_):
// TODO: - handle this
break
case .success(let account):
self.user = account
DispatchQueue.main.async {
self.getTrophies(account)
if self.user != nil {
self.accountImageView.sd_setImage(with: URL(string: self.user!.image.decodeHTML()), placeholderImage: UIImage(sfString: SFSymbol.personFill, overrideString: "profile")?.getCopy(withColor: ColorUtil.theme.fontColor), options: [.allowInvalidSSLCertificates]) {[weak self] (image, _, _, _) in
guard let strongSelf = self else { return }
strongSelf.accountImageView.image = image
}
} else {
self.accountImageView.image = UIImage(sfString: SFSymbol.personFill, overrideString: "profile")?.getCopy(withColor: ColorUtil.theme.fontColor)
}
let accountName = self.user!.name.insertingZeroWidthSpacesBeforeCaptials()
// Populate configurable UI elements here.
self.accountNameLabel.attributedText = {
let paragraphStyle = NSMutableParagraphStyle()
// paragraphStyle.lineHeightMultiple = 0.8
return NSAttributedString(
string: accountName,
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
]
)
}()
if let account = self.user {
let creationDate = NSDate(timeIntervalSince1970: Double(account.created))
let creationDateString: String = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "yyyyMMMMd", options: 0, locale: NSLocale.current)
return dateFormatter.string(from: creationDate as Date)
}()
let day = Calendar.current.ordinality(of: .day, in: .month, for: Date()) == Calendar.current.ordinality(of: .day, in: .month, for: creationDate as Date)
let month = Calendar.current.ordinality(of: .month, in: .year, for: Date()) == Calendar.current.ordinality(of: .month, in: .year, for: creationDate as Date)
if day && month {
self.accountAgeLabel.text = "🍰 Created \(creationDateString) 🍰"
} else {
self.accountAgeLabel.text = "Created \(creationDateString)"
}
self.header.setAccount(account)
self.setLoadingState(false)
} else {
print("No account to show!")
}
}
}
})
} catch {
}
}
func setLoadingState(_ isOn: Bool) {
if isOn {
spinner.startAnimating()
} else {
spinner.stopAnimating()
}
UIView.animate(withDuration: 0.2) {
self.header.alpha = isOn ? 0 : 1
self.accountNameLabel.alpha = isOn ? 0 : 1
self.accountAgeLabel.alpha = isOn ? 0 : 1
}
}
}
extension ProfileInfoViewController: ProfileHeaderViewDelegate {
func didRequestPrivateMessage() {
if user == nil {
return
}
VCPresenter.presentAlert(TapBehindModalViewController.init(rootViewController: ReplyViewController.init(name: user!.name, completion: { (_) in })), parentVC: self)
}
func didRequestRemoveFriend() {
if user == nil {
return
}
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.unfriend(user!.name, completion: { (_) in
DispatchQueue.main.async {
BannerUtil.makeBanner(text: "Unfriended u/\(self.user!.name)", seconds: 3, context: self)
}
})
} catch {
}
}
func didRequestAddFriend() {
if user == nil {
return
}
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.friend(user!.name, completion: { (result) in
if result.error != nil {
print(result.error!)
}
DispatchQueue.main.async {
BannerUtil.makeBanner(text: "Friended u/\(self.user!.name)", seconds: 3, context: self)
}
})
} catch {
}
}
func didRequestSetColor() {
if let profile = profile as? ProfileViewController {
self.dismiss(animated: true) {
profile.pickColor(sender: self)
}
}
}
func didRequestEditTag() {
if let profile = profile as? ProfileViewController {
self.dismiss(animated: true) {
profile.tagUser()
}
}
}
}
// MARK: - Actions
extension ProfileInfoViewController {
@objc func didRequestClose() {
self.dismiss(animated: true, completion: nil)
}
@objc func privateMessage(_ sender: UIButton) {
self.present(ReplyViewController(name: user!.name, completion: { (_) in
}), animated: true)
}
@objc func colorChangeRequested() {
// TODO: - this
}
@objc func tagUserRequested() {
// TODO: - this
}
@objc func friendRequested(_ sender: UIButton) {
// TODO: - this
}
@objc func unfreindRequested(_ sender: UIButton) {
// TODO: - this
}
}
// MARK: - Accessibility
extension ProfileInfoViewController {
override func accessibilityPerformEscape() -> Bool {
super.accessibilityPerformEscape()
didRequestClose()
return true
}
override var accessibilityViewIsModal: Bool {
get {
return true
}
set { } // swiftlint:disable:this unused_setter_value
}
}
protocol ProfileHeaderViewDelegate: AnyObject {
func didRequestPrivateMessage()
func didRequestRemoveFriend()
func didRequestAddFriend()
func didRequestSetColor()
func didRequestEditTag()
}
class ProfileHeaderView: UIView {
weak var delegate: ProfileHeaderViewDelegate?
var commentKarmaLabel: UILabel = UILabel().then {
$0.numberOfLines = 0
$0.font = FontGenerator.fontOfSize(size: 12, submission: true)
$0.textAlignment = .center
$0.textColor = ColorUtil.theme.fontColor
$0.accessibilityTraits = UIAccessibilityTraits.button
}
var trophyArea: UIScrollView = UIScrollView().then {
$0.backgroundColor = .clear
}
var postKarmaLabel: UILabel = UILabel().then {
$0.numberOfLines = 0
$0.font = FontGenerator.fontOfSize(size: 12, submission: true)
$0.textAlignment = .center
$0.textColor = ColorUtil.theme.fontColor
$0.accessibilityTraits = UIAccessibilityTraits.button
}
var messageCell = UITableViewCell().then {
$0.configure(text: "Private Message", imageName: "inbox", sfSymbolName: .envelopeFill, imageColor: GMColor.yellow500Color())
}
var user: Account?
var friendCell = UITableViewCell()
var colorCell = UITableViewCell().then {
$0.configure(text: "Set user color", imageName: "add", sfSymbolName: .eyedropperFull, imageColor: GMColor.yellow500Color())
}
//let tag = ColorUtil.getTagForUser(name: user.name)
var tagCell = UITableViewCell().then {
//\((tag != nil) ? " (currently \(tag!))" : "")"
$0.configure(text: "Tag user", imageName: "flag", sfSymbolName: .tagFill, imageColor: GMColor.orange500Color())
}
var infoStack = UIStackView().then {
$0.spacing = 8
$0.axis = .horizontal
$0.distribution = .equalSpacing
}
var cellStack = UIStackView().then {
$0.spacing = 2
$0.axis = .vertical
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubviews(infoStack, trophyArea, cellStack)
infoStack.addArrangedSubviews(commentKarmaLabel, postKarmaLabel)
cellStack.addArrangedSubviews(messageCell, friendCell, colorCell, tagCell)
self.clipsToBounds = true
setupAnchors()
setupActions()
setAccount(nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setAccount(_ account: Account?) {
if account == nil {
return
}
self.user = account
commentKarmaLabel.attributedText = {
let attrs = [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 16, submission: true)]
let attributedString = NSMutableAttributedString(string: "\(account?.commentKarma.delimiter ?? "0")", attributes: attrs)
let subt = NSMutableAttributedString(string: "\nCOMMENT KARMA")
attributedString.append(subt)
return attributedString
}()
self.friendCell.configure(text: account?.isFriend ?? false ? "Remove friend" : "Add friend", imageName: "profile", sfSymbolName: account?.isFriend ?? false ? SFSymbol.personBadgeMinusFill : SFSymbol.personBadgePlusFill, imageColor: GMColor.yellow500Color())
postKarmaLabel.attributedText = {
let attrs = [NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 16, submission: true)]
let attributedString = NSMutableAttributedString(string: "\(account?.linkKarma.delimiter ?? "0")", attributes: attrs)
let subt = NSMutableAttributedString(string: "\nPOST KARMA")
attributedString.append(subt)
return attributedString
}()
}
func setupAnchors() {
infoStack.topAnchor == topAnchor
infoStack.horizontalAnchors == horizontalAnchors
trophyArea.topAnchor == infoStack.bottomAnchor + 25
trophyArea.heightAnchor == 70
trophyArea.horizontalAnchors == horizontalAnchors + 8
cellStack.topAnchor == trophyArea.bottomAnchor + 26
cellStack.horizontalAnchors == horizontalAnchors
messageCell.heightAnchor == 50
friendCell.heightAnchor == 50
tagCell.heightAnchor == 50
colorCell.heightAnchor == 50
cellStack.bottomAnchor == bottomAnchor
}
func setupActions() {
friendCell.addTapGestureRecognizer { [weak self] in
guard let strongSelf = self else { return }
if strongSelf.user?.isFriend ?? false {
strongSelf.delegate?.didRequestRemoveFriend()
} else {
strongSelf.delegate?.didRequestAddFriend()
}
}
messageCell.addTapGestureRecognizer { [weak self] in
guard let strongSelf = self else { return }
strongSelf.delegate?.didRequestPrivateMessage()
}
colorCell.addTapGestureRecognizer { [weak self] in
guard let strongSelf = self else { return }
strongSelf.delegate?.didRequestSetColor()
}
tagCell.addTapGestureRecognizer { [weak self] in
guard let strongSelf = self else { return }
strongSelf.delegate?.didRequestEditTag()
}
}
}
| apache-2.0 | 8f657713a21b377f5d1a05f56ae3bb22 | 35.448333 | 317 | 0.567927 | 5.283643 | false | false | false | false |
dabing1022/AlgorithmRocks | Books/剑指Offer.playground/Pages/05 PrintListReversingly.xcplaygroundpage/Contents.swift | 1 | 1708 | //: [Previous](@previous)
// Check sources folder
class Node<T: Equatable> {
var value: T?
var next: Node? = nil
init () {
}
init(val: T?) {
self.value = val
}
convenience init(val: T?, next: Node?) {
self.init(val: val)
self.next = next
}
}
struct Stack<T> {
var elements = [T]()
mutating func push(element: T) {
elements.append(element)
}
mutating func pop() -> T? {
if (elements.last != nil) {
return elements.removeLast()
} else {
return nil
}
}
func peek() -> T? {
return elements.last
}
mutating func clear() {
elements.removeAll()
}
var count: Int {
return elements.count
}
var isEmpty: Bool {
return elements.count == 0
}
}
/*: based on stack */
func printListReversingly_Stack(head: Node<Int>) {
var nodesStack: Stack<Node<Int>> = Stack()
var node: Node? = head
while (node != nil) {
nodesStack.push(node!)
node = node!.next
}
while (!nodesStack.isEmpty) {
node = nodesStack.peek()!
node!.value
nodesStack.pop()
}
}
/*: base on recursive */
func printListReversingly_Recursively(head: Node<Int>) {
if (head.next != nil) {
printListReversingly_Recursively(head.next!)
}
head.value
}
/*: Let's build test! */
var node4 = Node<Int>(val: 4, next: nil)
var node3 = Node<Int>(val: 3, next: node4)
var node2 = Node<Int>(val: 2, next: node3)
var head = Node<Int>(val: 1, next: node2)
printListReversingly_Stack(head)
printListReversingly_Recursively(head)
//: [Next](@next)
| mit | 0211f4fafda5e6d48a44fea17d3e4f29 | 18.860465 | 56 | 0.546838 | 3.521649 | false | false | false | false |
jessesquires/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0131.xcplaygroundpage/Contents.swift | 2 | 5091 | /*:
# Add `AnyHashable` to the standard library
* Proposal: [SE-0131](0131-anyhashable.md)
* Author: [Dmitri Gribenko](https://github.com/gribozavr)
* Review Manager: [Chris Lattner](http://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000263.html)
## Introduction
We propose to add a type-erased `AnyHashable` container to the
standard library.
The implementation of [SE-0116 "Import Objective-C `id` as Swift `Any`
type"](0116-id-as-any.md) requires a type-erased container for
hashable values. From SE-0116:
> We need a type-erased container to represent a heterogeneous
> hashable type that is itself `Hashable`, for use as the upper-bound
> type of heterogeneous `Dictionary`s and `Set`s.
Swift-evolution thread: [Add AnyHashable to the standard library](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160718/025264.html).
## Motivation
Currently the Objective-C type `NSDictionary *` is imported as
`[NSObject : AnyObject]`. We used `NSObject` as the key type because
it is the closest type (in spirit) to `AnyObject` that also conforms
to `Hashable`. The aim of SE-0116 is to eliminate `AnyObject` from
imported APIs, replacing it with `Any`. To import unannotated
NSDictionaries we need an `Any`-like type that conforms to `Hashable`.
Thus, unannotated NSDictionaries will be imported as `[AnyHashable :
Any]`.
For additional motivation and discussion of API importing and
bridging, see [SE-0116](0116-id-as-any.md).
## Detailed design
We are adding the `AnyHashable` type:
```swift
/// A type-erased hashable value.
///
/// Forwards equality comparisons and hashing operations to an
/// underlying hashable value, hiding its specific type.
///
/// You can store mixed-type keys in `Dictionary` and other
/// collections that require `Hashable` by wrapping mixed-type keys in
/// `AnyHashable` instances:
///
/// let descriptions: [AnyHashable : Any] = [
/// AnyHashable("😄"): "emoji",
/// AnyHashable(42): "an Int",
/// AnyHashable(Int8(43)): "an Int8",
/// AnyHashable(Set(["a", "b"])): "a set of strings"
/// ]
/// print(descriptions[AnyHashable(42)]!) // prints "an Int"
/// print(descriptions[AnyHashable(43)]) // prints "nil"
/// print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8"
/// print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings"
public struct AnyHashable {
/// Creates an opaque hashable value that wraps `base`.
///
/// Example:
///
/// let x = AnyHashable(Int(42))
/// let y = AnyHashable(UInt8(42))
///
/// print(x == y) // Prints "false" because `Int` and `UInt8`
/// // are different types.
///
/// print(x == AnyHashable(Int(42))) // Prints "true".
public init<H : Hashable>(_ base: H)
/// The value wrapped in this `AnyHashable` instance.
///
/// let anyMessage = AnyHashable("Hello")
/// let unwrappedMessage: Any = anyMessage.base
/// print(unwrappedMessage) // prints "hello"
public var base: Any
}
extension AnyHashable : Equatable, Hashable {
public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool
public var hashValue: Int {
}
```
We are adding convenience APIs to `Set<AnyHashable>` that allow using
existing `Set` APIs with concrete values that conform to `Hashable`.
For example:
```swift
func contains42(_ data: Set<AnyHashable>) -> Bool {
// Works, but is too verbose:
// return data.contains(AnyHashable(42))
return data.contains(42) // Convenience API.
}
```
Convenience APIs for `Set<AnyHashable>`:
```swift
extension Set where Element == AnyHashable {
public func contains<ConcreteElement : Hashable>(
_ member: ConcreteElement
) -> Bool
public func index<ConcreteElement : Hashable>(
of member: ConcreteElement
) -> SetIndex<Element>?
mutating func insert<ConcreteElement : Hashable>(
_ newMember: ConcreteElement
) -> (inserted: Bool, memberAfterInsert: ConcreteElement)
@discardableResult
mutating func update<ConcreteElement : Hashable>(
with newMember: ConcreteElement
) -> ConcreteElement?
@discardableResult
mutating func remove<ConcreteElement : Hashable>(
_ member: ConcreteElement
) -> ConcreteElement?
}
```
Convenience APIs for `Dictionary<AnyHashable, *>`:
```swift
extension Dictionary where Key == AnyHashable {
public func index<ConcreteKey : Hashable>(forKey key: ConcreteKey)
-> DictionaryIndex<Key, Value>?
public subscript(_ key: _Hashable) -> Value? { get set }
@discardableResult
public mutating func updateValue<ConcreteKey : Hashable>(
_ value: Value, forKey key: ConcreteKey
) -> Value?
@discardableResult
public mutating func removeValue<ConcreteKey : Hashable>(
forKey key: ConcreteKey
) -> Value?
}
```
## Impact on existing code
`AnyHashable` itself is additive. Source-breaking changes are
discussed in SE-0116.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | 0f033c74932e548183d9c926101270df | 30.02439 | 150 | 0.690055 | 3.875095 | false | false | false | false |
Nyx0uf/MPDRemote | src/iOS/controllers/ArtistsVC.swift | 1 | 7002 | // ArtistsVC.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
final class ArtistsVC : UIViewController
{
// MARK: - Public properties
// Collection View
@IBOutlet var collectionView: MusicalCollectionView!
// Selected genre
var genre: Genre! = nil
// MARK: - Private properties
// Label in the navigationbar
private var titleView: UILabel! = nil
// MARK: - Initializers
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
// MARK: - UIViewController
override func viewDidLoad()
{
super.viewDidLoad()
// Remove back button label
navigationController?.navigationBar.backIndicatorImage = #imageLiteral(resourceName: "btn-back")
navigationController?.navigationBar.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "btn-back")
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
// Navigation bar title
titleView = UILabel(frame: CGRect(.zero, 100.0, 44.0))
titleView.numberOfLines = 2
titleView.textAlignment = .center
titleView.isAccessibilityElement = false
titleView.textColor = #colorLiteral(red: 0.1298420429, green: 0.1298461258, blue: 0.1298439503, alpha: 1)
navigationItem.titleView = titleView
// Display layout button
let layoutCollectionViewAsCollection = Settings.shared.bool(forKey: kNYXPrefLayoutArtistsCollection)
let displayButton = UIBarButtonItem(image: layoutCollectionViewAsCollection ? #imageLiteral(resourceName: "btn-display-list") : #imageLiteral(resourceName: "btn-display-collection"), style: .plain, target: self, action: #selector(changeCollectionLayoutType(_:)))
displayButton.accessibilityLabel = NYXLocalizedString(layoutCollectionViewAsCollection ? "lbl_pref_layoutastable" : "lbl_pref_layoutascollection")
navigationItem.leftBarButtonItems = [displayButton]
navigationItem.leftItemsSupplementBackButton = true
// CollectionView
collectionView.myDelegate = self
collectionView.displayType = .artists
collectionView.layoutType = layoutCollectionViewAsCollection ? .collection : .table
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
MusicDataSource.shared.getArtistsForGenre(genre) { (artists: [Artist]) in
DispatchQueue.main.async {
self.collectionView.items = artists
self.collectionView.reloadData()
self.updateNavigationTitle()
}
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask
{
return .portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .default
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "artists-to-albums"
{
guard let indexes = collectionView.indexPathsForSelectedItems else
{
return
}
if let indexPath = indexes.first
{
let vc = segue.destination as! AlbumsVC
vc.artist = collectionView.items[indexPath.row] as! Artist
}
}
}
// MARK: - Actions
@objc func changeCollectionLayoutType(_ sender: Any?)
{
var b = Settings.shared.bool(forKey: kNYXPrefLayoutArtistsCollection)
b = !b
Settings.shared.set(b, forKey: kNYXPrefLayoutArtistsCollection)
Settings.shared.synchronize()
collectionView.layoutType = b ? .collection : .table
if let buttons = navigationItem.leftBarButtonItems
{
if buttons.count >= 1
{
let btn = buttons[0]
btn.image = b ? #imageLiteral(resourceName: "btn-display-list") : #imageLiteral(resourceName: "btn-display-collection")
btn.accessibilityLabel = NYXLocalizedString(b ? "lbl_pref_layoutastable" : "lbl_pref_layoutascollection")
}
}
}
// MARK: - Private
private func updateNavigationTitle()
{
let attrs = NSMutableAttributedString(string: genre.name + "\n", attributes: [NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Medium", size: 14.0)!])
attrs.append(NSAttributedString(string: "\(collectionView.items.count) \(collectionView.items.count == 1 ? NYXLocalizedString("lbl_artist").lowercased() : NYXLocalizedString("lbl_artists").lowercased())", attributes: [NSAttributedStringKey.font : UIFont(name: "HelveticaNeue", size: 13.0)!]))
titleView.attributedText = attrs
}
}
// MARK: - MusicalCollectionViewDelegate
extension ArtistsVC : MusicalCollectionViewDelegate
{
func isSearching(actively: Bool) -> Bool
{
return false
}
func didSelectItem(indexPath: IndexPath)
{
performSegue(withIdentifier: "artists-to-albums", sender: self)
}
}
// MARK: - Peek & Pop
extension ArtistsVC
{
override var previewActionItems: [UIPreviewActionItem]
{
let playAction = UIPreviewAction(title: NYXLocalizedString("lbl_play"), style: .default) { (action, viewController) in
MusicDataSource.shared.getAlbumsForGenre(self.genre, firstOnly: false) {
MusicDataSource.shared.getTracksForAlbums(self.genre.albums) {
let ar = self.genre.albums.flatMap({$0.tracks}).flatMap({$0})
PlayerController.shared.playTracks(ar, shuffle: false, loop: false)
}
}
MiniPlayerView.shared.stayHidden = false
}
let shuffleAction = UIPreviewAction(title: NYXLocalizedString("lbl_alert_playalbum_shuffle"), style: .default) { (action, viewController) in
MusicDataSource.shared.getAlbumsForGenre(self.genre, firstOnly: false) {
MusicDataSource.shared.getTracksForAlbums(self.genre.albums) {
let ar = self.genre.albums.flatMap({$0.tracks}).flatMap({$0})
PlayerController.shared.playTracks(ar, shuffle: true, loop: false)
}
}
MiniPlayerView.shared.stayHidden = false
}
let addQueueAction = UIPreviewAction(title: NYXLocalizedString("lbl_alert_playalbum_addqueue"), style: .default) { (action, viewController) in
MusicDataSource.shared.getAlbumsForGenre(self.genre, firstOnly: false) {
for album in self.genre.albums
{
PlayerController.shared.addAlbumToQueue(album)
}
}
MiniPlayerView.shared.stayHidden = false
}
return [playAction, shuffleAction, addQueueAction]
}
}
| mit | 762bb926b775f83c5f700740eb0a19b2 | 35.092784 | 294 | 0.751357 | 3.958168 | false | false | false | false |
hooman/swift | test/AutoDiff/stdlib/anydifferentiable.swift | 1 | 7737 | // RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off)
// REQUIRES: executable_test
import _Differentiation
import StdlibUnittest
var TypeErasureTests = TestSuite("DifferentiableTypeErasure")
struct Vector: Differentiable, Equatable {
var x, y: Float
}
struct Generic<T: Differentiable & Equatable>: Differentiable, Equatable {
var x: T
}
extension AnyDerivative {
// This exists only to faciliate testing.
func moved(along offset: TangentVector) -> Self {
var result = self
result.move(by: offset)
return result
}
}
TypeErasureTests.test("AnyDifferentiable operations") {
do {
var any = AnyDifferentiable(Vector(x: 1, y: 1))
let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
any.move(by: tan)
expectEqual(Vector(x: 2, y: 2), any.base as? Vector)
}
do {
var any = AnyDifferentiable(Generic<Float>(x: 1))
let tan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
any.move(by: tan)
expectEqual(Generic<Float>(x: 2), any.base as? Generic<Float>)
}
}
TypeErasureTests.test("AnyDerivative operations") {
do {
var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
tan += tan
expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan + tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 0, y: 0)), tan - tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan.moved(along: tan))
expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan)
}
do {
var tan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
tan += tan
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 2)), tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan + tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 0)), tan - tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan.moved(along: tan))
}
}
TypeErasureTests.test("AnyDerivative.zero") {
var zero = AnyDerivative.zero
zero += zero
zero -= zero
expectEqual(zero, zero + zero)
expectEqual(zero, zero - zero)
expectEqual(zero, zero.moved(along: zero))
var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
expectEqual(zero, zero)
expectEqual(AnyDerivative(Vector.TangentVector.zero), tan - tan)
expectNotEqual(AnyDerivative(Vector.TangentVector.zero), zero)
expectNotEqual(AnyDerivative.zero, tan - tan)
tan += zero
tan -= zero
expectEqual(tan, tan + zero)
expectEqual(tan, tan - zero)
expectEqual(tan, tan.moved(along: zero))
expectEqual(tan, zero.moved(along: tan))
expectEqual(zero, zero)
expectEqual(tan, tan)
}
TypeErasureTests.test("AnyDifferentiable casting") {
let any = AnyDifferentiable(Vector(x: 1, y: 1))
expectEqual(Vector(x: 1, y: 1), any.base as? Vector)
let genericAny = AnyDifferentiable(Generic<Float>(x: 1))
expectEqual(Generic<Float>(x: 1),
genericAny.base as? Generic<Float>)
expectEqual(nil, genericAny.base as? Generic<Double>)
}
TypeErasureTests.test("AnyDifferentiable reflection") {
let originalVector = Vector(x: 1, y: 1)
let vector = AnyDifferentiable(originalVector)
let mirror = Mirror(reflecting: vector)
let children = Array(mirror.children)
expectEqual(2, children.count)
expectEqual(["x", "y"], children.map(\.label))
expectEqual([originalVector.x, originalVector.y], children.map { $0.value as! Float })
}
TypeErasureTests.test("AnyDerivative casting") {
let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
expectEqual(Vector.TangentVector(x: 1, y: 1), tan.base as? Vector.TangentVector)
let genericTan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
expectEqual(Generic<Float>.TangentVector(x: 1),
genericTan.base as? Generic<Float>.TangentVector)
expectEqual(nil, genericTan.base as? Generic<Double>.TangentVector)
let zero = AnyDerivative.zero
expectEqual(nil, zero.base as? Float)
expectEqual(nil, zero.base as? Vector.TangentVector)
expectEqual(nil, zero.base as? Generic<Float>.TangentVector)
}
TypeErasureTests.test("AnyDerivative reflection") {
let originalTan = Vector.TangentVector(x: 1, y: 1)
let tan = AnyDerivative(originalTan)
let mirror = Mirror(reflecting: tan)
let children = Array(mirror.children)
expectEqual(2, children.count)
expectEqual(["x", "y"], children.map(\.label))
expectEqual([originalTan.x, originalTan.y], children.map { $0.value as! Float })
}
TypeErasureTests.test("AnyDifferentiable differentiation") {
// Test `AnyDifferentiable` initializer.
do {
let x: Float = 3
let v = AnyDerivative(Float(2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP: Float = 2
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Vector(x: 4, y: 5)
let v = AnyDerivative(Vector.TangentVector(x: 2, y: 2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP = Vector.TangentVector(x: 2, y: 2)
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Generic<Double>(x: 4)
let v = AnyDerivative(Generic<Double>.TangentVector(x: 2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP = Generic<Double>.TangentVector(x: 2)
expectEqual(expectedVJP, 𝛁x)
}
}
TypeErasureTests.test("AnyDerivative differentiation") {
// Test `AnyDerivative` operations.
func tripleSum(_ x: AnyDerivative, _ y: AnyDerivative) -> AnyDerivative {
let sum = x + y
return sum + sum + sum
}
do {
let x = AnyDerivative(Float(4))
let y = AnyDerivative(Float(-2))
let v = AnyDerivative(Float(1))
let expectedVJP: Float = 3
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Float)
expectEqual(expectedVJP, 𝛁y.base as? Float)
}
do {
let x = AnyDerivative(Vector.TangentVector(x: 4, y: 5))
let y = AnyDerivative(Vector.TangentVector(x: -2, y: -1))
let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
let expectedVJP = Vector.TangentVector(x: 3, y: 3)
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Vector.TangentVector)
expectEqual(expectedVJP, 𝛁y.base as? Vector.TangentVector)
}
do {
let x = AnyDerivative(Generic<Double>.TangentVector(x: 4))
let y = AnyDerivative(Generic<Double>.TangentVector(x: -2))
let v = AnyDerivative(Generic<Double>.TangentVector(x: 1))
let expectedVJP = Generic<Double>.TangentVector(x: 3)
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Generic<Double>.TangentVector)
expectEqual(expectedVJP, 𝛁y.base as? Generic<Double>.TangentVector)
}
// Test `AnyDerivative` initializer.
func typeErased<T>(_ x: T) -> AnyDerivative
where T: Differentiable, T.TangentVector == T {
let any = AnyDerivative(x)
return any + any
}
do {
let x: Float = 3
let v = AnyDerivative(Float(1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP: Float = 2
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Vector.TangentVector(x: 4, y: 5)
let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP = Vector.TangentVector(x: 2, y: 2)
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Generic<Double>.TangentVector(x: 4)
let v = AnyDerivative(Generic<Double>.TangentVector(x: 1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP = Generic<Double>.TangentVector(x: 2)
expectEqual(expectedVJP, 𝛁x)
}
}
runAllTests()
| apache-2.0 | b35004fd5b5ff1cd104409aa35175203 | 32.471616 | 89 | 0.683757 | 3.457375 | false | true | false | false |
TTVS/NightOut | Clubber/CircularImagePickerOverlay.swift | 1 | 2808 | //
// CircularImagePickerOverlay.swift
// Clubber
//
// Created by Terra on 14/10/2015.
// Copyright © 2015 Dino Media Asia. All rights reserved.
//
import UIKit
class CircularImagePickerOverlay: UIView {
// override init(frame: CGRect) {
// super.init(frame: frame)
//
// self.opaque = false
// self.backgroundColor = UIColor.clearColor()
// let crosshair: UIImage = UIImage(named:"crosshair")!
// let crosshairView: UIImageView = UIImageView(image: crosshair)
// crosshairView.frame = CGRectMake(0, 40, 320, 300)
// crosshairView.contentMode = UIViewContentMode.Center
// self.addSubview(crosshairView)
//
//// crosshairView.release()
//
//
// let button = UIButton(type: UIButtonType.RoundedRect)
// button.setTitle("Catch now", forState: UIControlState.Normal)
// button.frame = CGRectMake(0, 430, 320, 40)
// self.addSubview(button)
//
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
//
// deinit {
// // perform the deinitialization
// }
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
backgroundColor = UIColor.clearColor()
userInteractionEnabled = true
let button = UIButton(type: UIButtonType.RoundedRect)
button.setTitle("Catch now", forState: UIControlState.Normal)
button.frame = CGRectMake(0, 430, 320, 40)
self.addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
// draws lines and curves to make shapes
let path = UIBezierPath()
let topCrosshair = CGPoint(x: center.x, y: center.y + 10.0)
let rightCrosshair = CGPoint(x: center.x + 10.0, y: center.y)
let bottomCrosshair = CGPoint(x: center.x, y: center.y - 10.0)
let leftCrosshair = CGPoint(x: center.x - 10.0, y: center.y)
// "pick up" the path and move it to the correct point, then draw across
path.moveToPoint(topCrosshair)
path.addLineToPoint(bottomCrosshair)
path.moveToPoint(leftCrosshair)
path.addLineToPoint(rightCrosshair)
path.lineWidth = 1.0
// Close to the yellow used in the Camera app
UIColor(red: 255.0, green: 204.0, blue: 0.0, alpha: 1.0).setStroke()
path.stroke()
}
}
| apache-2.0 | 572362407162c39872df312621ec6288 | 30.539326 | 80 | 0.60456 | 4.140118 | false | false | false | false |
lukaskubanek/LoremIpsum | Examples/Lorem Ipsum tvOS Example/Lorem Ipsum tvOS Example/ViewController.swift | 1 | 1987 | /*
* __ ____
* / / ____ ________ ____ ___ / _/___ _______ ______ ___
* / / / __ \/ ___/ _ \/ __ `__ \ / // __ \/ ___/ / / / __ `__ \
* / /___/ /_/ / / / __/ / / / / / _/ // /_/ (__ ) /_/ / / / / / /
* /_____/\____/_/ \___/_/ /_/ /_/ /___/ .___/____/\__,_/_/ /_/ /_/
* /_/
*
* ViewController.swift
* http://github.com/lukaskubanek/LoremIpsum
* 2013-2020 (c) Lukas Kubanek (http://lukaskubanek.com)
*/
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var informationLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
loadImage()
}
@IBAction func userPressedReloadButton() {
loadImage()
}
func loadImage() {
let services: [LIPlaceholderImageService] = [.dummyImage,
.placeKitten]
guard let service = services.randomElement() else { fatalError() }
var imageSize = imageView.bounds.size
var serviceString: String
switch service {
case .dummyImage: serviceString = "dummyimage.com"
case .loremPixel: serviceString = "lorempixel.com"
case .placeKitten: serviceString = "placekitten.com"
}
serviceString.append(" \(Int(imageSize.width)) x \(Int(imageSize.height))")
informationLabel.text = "Loading…"
imageView.image = nil
let scale = UIScreen.main.scale
imageSize = imageSize * scale
LoremIpsum.asyncPlaceholderImage(from: service, with: imageSize) { (image) in
self.imageView.image = image
self.informationLabel.text = serviceString
}
}
}
func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}
| mit | 135a477f2f2d638deab0511440eb678f | 29.075758 | 85 | 0.482116 | 4.075975 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/increasing-order-search-tree.swift | 2 | 1251 | /**
* https://leetcode.com/problems/increasing-order-search-tree/
*
*
*/
// Date: Thu Dec 3 11:11:21 PST 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func increasingBST(_ root: TreeNode?) -> TreeNode? {
var nodeList: [TreeNode] = []
func inorder(_ root: TreeNode?) {
guard let root = root else { return }
inorder(root.left)
nodeList.append(root)
inorder(root.right)
}
inorder(root)
var index = 0
while index < nodeList.count - 1 {
nodeList[index].left = nil
nodeList[index].right = nodeList[index + 1]
index += 1
}
nodeList[index].left = nil
nodeList[index].right = nil
return nodeList.first
}
} | mit | 57ad2d2071e870efa93839367d57cc22 | 28.809524 | 85 | 0.538769 | 3.605187 | false | false | false | false |
ygorshenin/omim | iphone/Maps/Bookmarks/Categories/Categories/BMCCategoryCell.swift | 2 | 1921 | protocol BMCCategoryCellDelegate {
func visibilityAction(category: BMCCategory)
func moreAction(category: BMCCategory, anchor: UIView)
}
final class BMCCategoryCell: MWMTableViewCell {
@IBOutlet private weak var visibility: UIButton!
@IBOutlet private weak var title: UILabel! {
didSet {
title.font = .regular16()
title.textColor = .blackPrimaryText()
}
}
@IBOutlet private weak var count: UILabel! {
didSet {
count.font = .regular14()
count.textColor = .blackSecondaryText()
}
}
@IBOutlet private weak var more: UIButton! {
didSet {
more.tintColor = .blackSecondaryText()
more.setImage(#imageLiteral(resourceName: "ic24PxMore"), for: .normal)
}
}
private var category: BMCCategory! {
willSet {
category?.removeObserver(self)
}
didSet {
categoryUpdated()
category?.addObserver(self)
}
}
private var delegate: BMCCategoryCellDelegate!
func config(category: BMCCategory, delegate: BMCCategoryCellDelegate) -> UITableViewCell {
self.category = category
self.delegate = delegate
return self
}
@IBAction private func visibilityAction() {
delegate.visibilityAction(category: category)
}
@IBAction private func moreAction() {
delegate.moreAction(category: category, anchor: more)
}
}
extension BMCCategoryCell: BMCCategoryObserver {
func categoryUpdated() {
title.text = category.title
count.text = String(format: L("bookmarks_places"), category.count)
if category.isVisible {
visibility.tintColor = .linkBlue()
visibility.setImage(#imageLiteral(resourceName: "radioBtnOn"), for: .normal)
visibility.imageView?.mwm_coloring = .blue
} else {
visibility.tintColor = .blackHintText()
visibility.setImage(#imageLiteral(resourceName: "radioBtnOff"), for: .normal)
visibility.imageView?.mwm_coloring = .gray
}
}
}
| apache-2.0 | de667b8d395184cdcbf44a6ea325a7d9 | 26.056338 | 92 | 0.690786 | 4.297539 | false | false | false | false |
sunilsharma08/AppUtility | AppUtility/AUColor.swift | 1 | 1613 | //
// AUColor.swift
// AppUtility
//
// Created by Sunil Sharma on 22/08/16.
// Copyright © 2016 Sunil Sharma. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
//Creating UIColor from RGB value
public convenience init(redValue: CGFloat, greenValue: CGFloat, blueValue: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: alpha)
}
//Creating UIColor from hex value alpha default value is 1
public convenience init(hex: Int, alpha: CGFloat = 1.0) {
let r = CGFloat((hex >> 16) & 0xff) / 255
let g = CGFloat((hex >> 08) & 0xff) / 255
let b = CGFloat((hex >> 00) & 0xff) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)
}
//Creating UIColor from hex string value
public convenience init(hexCode: String) {
let hex = hexCode.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count {
case 3:
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6:
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8:
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 255, 255, 255)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
| mit | c09e78933384153785c7742b123a2434 | 34.043478 | 114 | 0.560174 | 3.25 | false | false | false | false |
burakustn/BULoopView | BULoopView/Classes/BULoopView.swift | 1 | 6902 | //
// BULoopViiew.swift
// BULoopView
//
// Created by Burak Üstün on 23/06/17.
// Copyright © 2017 Burak Üstün. All rights reserved.
//
import UIKit
import Kingfisher
protocol BULoopViewDelegate {
func didSelectIndexAt(Index : Int)
}
public class BULoopView: UIView {
/*
The BULoopView's Delegate
*/
var delegate : BULoopViewDelegate? = nil
/**
* The Scrollview of this BULoopView
*/
fileprivate var LoopView:UIScrollView!
/**
* The Timer of this BULoopView
*/
fileprivate var LoopTimer:Timer?
/**
* Screensize for some operations
*/
fileprivate let screenSize: CGRect = UIScreen.main.bounds
/**
* The array of this BULoopView
*/
fileprivate var arrayLoop: [LoopItem] = []
/**
* Use the size of the BULoopView for Loop Item Height
*/
fileprivate var LoopItemHeight: CGFloat = 0.0
/** Produces LoopView
* @param Takes the array from the outside and turns it into the appropriate elements
*/
public func loadLoopView(LoopArray : [LoopItem]){
self.LoopView = UIScrollView.init(frame: self.bounds)
self.LoopItemHeight = self.frame.height
self.addSubview(self.LoopView)
self.arrayLoop = LoopArray
/**
If the size of the array is bigger than the BULoopView, starts the loop.
*/
if(CGFloat(self.arrayLoop.count) * self.LoopItemWidth > self.frame.size.width){
for j in 1..<3 {
for i in 0..<self.arrayLoop.count {
if j == 1{
self.createLoopItem(index: i)
}
else{
self.createLoopItem(index: i+self.arrayLoop.count)
}
}
}
self.LoopView.delegate = self
self.LoopView.showsVerticalScrollIndicator = false
self.LoopView.showsHorizontalScrollIndicator = false
self.LoopView.contentSize = CGSize(width : 2 * CGFloat(self.arrayLoop.count) * (self.LoopSpace + self.LoopItemWidth), height : self.LoopView.frame.height)
self.LoopTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.LoopViewcontrol), userInfo: nil, repeats: true)
RunLoop.current.add(self.LoopTimer!, forMode: RunLoopMode.commonModes)
}
else{
for i in 0..<self.arrayLoop.count {
self.createLoopItem(index: i)
}
}
}
/** Produces LoopItem according to the given sequence
* @param Produces position by taking index
* It only contains one photo and one text
*/
fileprivate func createLoopItem(index : Int){
let LoopItem:UIView = UIView.init(frame: CGRect(x: CGFloat(index) * (self.LoopSpace + self.LoopItemWidth), y: 5 , width : self.LoopItemWidth , height: self.LoopView.frame.height - 20))
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(sender:)))
tap.delegate = self as? UIGestureRecognizerDelegate
LoopItem.addGestureRecognizer(tap)
let imageView:UIImageView = UIImageView.init(frame: CGRect(x: 5, y: LoopItemMargin/2 , width : LoopItemImageWidth , height: LoopItemHeight - LoopItemMargin*2))
imageView.contentMode = .scaleAspectFit
if(index < self.arrayLoop.count){
imageView.kf.setImage(with: URL(string: self.arrayLoop[index].PhotoPath!))
}
else{
imageView.kf.setImage(with: URL(string: self.arrayLoop[index - self.arrayLoop.count].PhotoPath!))
}
let nameLabel:UILabel = UILabel.init(frame: CGRect(x: imageView.frame.size.width + 5, y: LoopItemMargin/2 , width : self.LoopItemWidth - imageView.frame.size.width - 15 , height : LoopItemHeight - LoopItemMargin*2))
nameLabel.textAlignment = .center
nameLabel.text = index < self.arrayLoop.count ? self.arrayLoop[index].Name : self.arrayLoop[index - self.arrayLoop.count].Name
if(self.labelFont != nil){
nameLabel.font = self.labelFont
}
nameLabel.textColor = self.textColor
let seperatorView:UIView = UIView.init(frame: CGRect(x: self.LoopItemWidth - 0.5 , y: LoopItemMargin/2 , width : 0.5 , height : LoopItemHeight - LoopItemMargin*2))
seperatorView.backgroundColor = self.seperatorColor
seperatorView.alpha = self.seperatorAlpha
LoopItem.backgroundColor = UIColor.clear
LoopItem.addSubview(seperatorView)
LoopItem.addSubview(imageView)
LoopItem.addSubview(nameLabel)
self.LoopView.addSubview(LoopItem)
}
/**
This fuction handles LoopItem's Click
**/
func handleTap(sender: UITapGestureRecognizer? = nil) {
self.delegate?.didSelectIndexAt(Index: (sender?.view?.tag)!)
}
@objc fileprivate func LoopViewcontrol(){
var point = CGPoint(x: CGFloat(self.LoopView.contentOffset.x), y: CGFloat(self.LoopView.contentOffset.y))
point.x += 0.5
self.LoopView.contentOffset = point
}
/**
* Use to set the Loop Items Space
*/
public var LoopSpace: CGFloat = 10.0
/**
* Use to set the Loop Items Width
*/
public var LoopItemWidth: CGFloat = 150.0
/**
* Use to set the Loop Items Margin
*/
public var LoopItemMargin:CGFloat = 10.0
/**
* Use to set the Loop Items Image Width
*/
public var LoopItemImageWidth:CGFloat = 50.0
/**
* Use to set the Loop Items Seperator Color
*/
public var seperatorColor:UIColor = UIColor( red:0.961, green:0.961, blue:0.961, alpha:1)
/**
* Use to set the Loop Seperator Alpha
*/
public var seperatorAlpha:CGFloat = 0.7
/**
* Use to set the Loop Items Text Color
*/
public var textColor:UIColor = UIColor( red:0.961, green:0.961, blue:0.961, alpha:1)
/**
* Use to set the Loop Items Text Font
*/
public var labelFont:UIFont? = nil
}
extension BULoopView : UIScrollViewDelegate{
/**
Endless Loop Mechanic
*/
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if(scrollView == LoopView){
if(scrollView.contentOffset.x > scrollView.contentSize.width / 2 + 2){
scrollView.contentOffset.x = 0
}
else if(scrollView.contentOffset.x < -0.5){
scrollView.contentOffset.x = scrollView.contentSize.width / 2 - 0.5
}
}
}
}
| mit | 147f866bd4a44dc9113e741d97162eae | 34.369231 | 231 | 0.594171 | 4.321429 | false | false | false | false |
KrishMunot/swift | test/SILOptimizer/devirt_inherited_conformance.swift | 6 | 5299 | // RUN: %target-swift-frontend -O %s -emit-sil | FileCheck %s
// Make sure that we can dig all the way through the class hierarchy and
// protocol conformances.
// CHECK-LABEL: sil @_TF28devirt_inherited_conformance6driverFT_T_ : $@convention(thin) () -> () {
// CHECK: bb0
// CHECK: [[UNKNOWN2a:%.*]] = function_ref @unknown2a : $@convention(thin) () -> ()
// CHECK: apply [[UNKNOWN2a]]
// CHECK: apply [[UNKNOWN2a]]
// CHECK: [[UNKNOWN3a:%.*]] = function_ref @unknown3a : $@convention(thin) () -> ()
// CHECK: apply [[UNKNOWN3a]]
// CHECK: apply [[UNKNOWN3a]]
// CHECK: return
@_silgen_name("unknown1a")
func unknown1a() -> ()
@_silgen_name("unknown1b")
func unknown1b() -> ()
@_silgen_name("unknown2a")
func unknown2a() -> ()
@_silgen_name("unknown2b")
func unknown2b() -> ()
@_silgen_name("unknown3a")
func unknown3a() -> ()
@_silgen_name("unknown3b")
func unknown3b() -> ()
struct Int32 {}
protocol P {
// We do not specialize typealias's correctly now.
//typealias X
func doSomething(_ x : Int32)
// This exposes a SILGen bug. FIXME: Fix up this test in the future.
// class func doSomethingMeta()
}
class B : P {
// We do not specialize typealias's correctly now.
//typealias X = B
func doSomething(_ x : Int32) {
unknown1a()
}
// See comment in protocol P
//class func doSomethingMeta() {
// unknown1b()
//}
}
class B2 : B {
// When we have covariance in protocols, change this to B2.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething(_ x : Int32) {
unknown2a()
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown2b()
//}
}
class B3 : B {
// When we have covariance in protocols, change this to B3.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething(_ x : Int32) {
unknown3a()
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown3b()
//}
}
func WhatShouldIDo<T : P>(_ t : T, _ x : Int32) {
t.doSomething(x)
}
func WhatShouldIDo2(_ p : P, _ x : Int32) {
p.doSomething(x)
}
public func driver() -> () {
let b2 = B2()
let b3 = B3()
let x = Int32()
WhatShouldIDo(b2, x)
WhatShouldIDo2(b2, x)
WhatShouldIDo(b3, x)
WhatShouldIDo2(b3, x)
}
// Test that inherited conformances work properly with
// standard operators like == and custom operators like ---
// Comparable is similar to Equatable, but uses a usual method
// instead of an operator.
public protocol Comparable {
func compare(_: Self, _: Self) -> Bool
}
// Define a custom operator to be used instead of ==
infix operator --- { associativity left precedence 140 }
// Simple is a protocol that simply defines an operator and
// a few methods with different number of arguments.
public protocol Simple {
func foo(_: Self) -> Bool
func boo(_: Self, _: Self) -> Bool
func ---(_: Self, _: Self) -> Bool
}
public class C: Equatable, Comparable, Simple {
public func compare(_ c1:C, _ c2:C) -> Bool {
return c1 == c2
}
public func foo(_ c:C) -> Bool {
return true
}
public func boo(_ c1:C, _ c2:C) -> Bool {
return false
}
}
// D inherits a bunch of conformances from C.
// We want to check that compiler can handle
// them properly and is able to devirtualize
// them.
public class D: C {
}
public func ==(lhs: C, rhs: C) -> Bool {
return true
}
public func ---(lhs: C, rhs: C) -> Bool {
return true
}
public func compareEquals<T:Equatable>(_ x: T, _ y:T) -> Bool {
return x == y
}
public func compareMinMinMin<T:Simple>(_ x: T, _ y:T) -> Bool {
return x --- y
}
public func compareComparable<T:Comparable>(_ x: T, _ y:T) -> Bool {
return x.compare(x, y)
}
// Check that a call of inherited Equatable.== can be devirtualized.
// CHECK-LABEL: sil @_TF28devirt_inherited_conformance17testCompareEqualsFT_Sb : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
// CHECK: }
public func testCompareEquals() -> Bool {
return compareEquals(D(), D())
}
// Check that acall of inherited Simple.== can be devirtualized.
// CHECK-LABEL: sil @_TF28devirt_inherited_conformance20testCompareMinMinMinFT_Sb : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testCompareMinMinMin() -> Bool {
return compareMinMinMin(D(), D())
}
// Check that a call of inherited Comparable.== can be devirtualized.
// CHECK-LABEL: sil @_TF28devirt_inherited_conformance21testCompareComparableFT_Sb : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testCompareComparable() -> Bool {
return compareComparable(D(), D())
}
public func BooCall<T:Simple>(_ x:T, _ y:T) -> Bool {
return x.boo(y, y)
}
// Check that a call of inherited Simple.boo can be devirtualized.
// CHECK-LABEL: sil @_TF28devirt_inherited_conformance11testBooCallFT_Sb : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, 0
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testBooCall() -> Bool {
return BooCall(D(), D())
}
| apache-2.0 | c0a56014d69087e2b322ae125bf0a336 | 24.475962 | 116 | 0.656162 | 3.322257 | false | false | false | false |
chiraggupta/RatingsMonitor | Sources/App/Controllers/ReviewsFetcher.swift | 1 | 899 | import Foundation
import Vapor
import HTTP
struct ReviewsFetcher {
let jsonParser = ReviewsJSONParser()
let urlSession = URLSession(configuration: .default)
func getReviews(completion: @escaping (Result<[Review]>) -> Void) {
let url = URL(string: "https://itunes.apple.com/us/rss/customerreviews/id=640199958/sortby=mostrecent/json")!
let dataTask = urlSession.dataTask(with: url) { (data, _, error) in
completion(self.handleResponse(data: data, error: error))
}
dataTask.resume()
}
func handleResponse(data: Data?, error: Error?) -> Result<[Review]> {
if let error = error {
return Result.failure(error)
}
if let data = data {
let reviews = jsonParser.parse(data: data)
return Result.success(reviews)
}
return Result.failure(Abort.custom(status: .internalServerError, message: "No data received from AppStore."))
}
}
| mit | 2a66d9549fb24e84eb9e553a68821650 | 26.242424 | 113 | 0.686318 | 3.960352 | false | false | false | false |
soffes/Camo | Camo/Camo.swift | 1 | 946 | //
// Camo.swift
// Camo
//
// Created by Sam Soffes on 12/5/15.
// Copyright © 2015 Sam Soffes. All rights reserved.
//
import Foundation
import Crypto
public struct Camo {
// MARK: - Properties
public let secret: String
public let baseURL: URL
public let hmacAlgorithm: HMAC.Algorithm
// MARK: - Initializers
public init(secret: String, baseURL: URL, hmacAlgorithm: HMAC.Algorithm = .sha1) {
self.secret = secret
self.baseURL = baseURL
self.hmacAlgorithm = hmacAlgorithm
}
// MARK: - URL Signing
public func sign(URL: Foundation.URL) -> Foundation.URL? {
guard let signature = HMAC.sign(message: URL.absoluteString, algorithm: hmacAlgorithm, key: secret),
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: true)
else { return nil }
components.path = "/\(signature)"
components.queryItems = [
URLQueryItem(name: "url", value: URL.absoluteString)
]
return components.url
}
}
| mit | 2da7553a1c897204d3211c5568988d8a | 20.477273 | 102 | 0.706878 | 3.539326 | false | false | false | false |
YaoJuan/YJDouYu | YJDouYu/YJDouYu/Classes/Home-首页/ViewModel/YJBaseVM.swift | 1 | 1287 | //
// YJBaseVM.swift
// YJDouYu
//
// Created by 赵思 on 2017/8/3.
// Copyright © 2017年 赵思. All rights reserved.
//
import UIKit
import ObjectMapper
import SwiftyJSON
class YJBaseVM: NSObject {
var groupItems = [YJRecommondGroupItem]()
}
enum ItemType {
case single
case group
}
// MARK: - 请求数据
extension YJBaseVM {
func loadAnchorData(itemType: ItemType,URLString: String, paramaters: [String : Any]? = nil, finished: @escaping () -> ()) {
NetworkTool.requestData(type: .GET, URLString: URLString, paramaters: paramaters) {result in
let dict = JSON(result).dictionaryValue["data"]?.arrayObject
switch itemType {
// 1.如果数据解析出来是组模型
case .group:
self.groupItems = Mapper<YJRecommondGroupItem>().mapArray(JSONObject: dict) ?? [YJRecommondGroupItem]()
// 2.如果是单个模型包装成组模型
case .single:
let grouItem = YJRecommondGroupItem()
grouItem.room_list = Mapper<YJRecommendRoomItem>().mapArray(JSONObject: dict) ?? [YJRecommendRoomItem]()
self.groupItems.append(grouItem)
}
finished()
}
}
}
| mit | 760ad2a4da105324070dfcc216f51210 | 26.681818 | 128 | 0.59688 | 4.087248 | false | false | false | false |
yyny1789/KrMediumKit | Source/Utils/Extensions/String+Regex.swift | 1 | 1334 | import Foundation
public enum Regex: String {
case Email = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
case Number = "^[0-9]*?$"
var pattern: String {
return rawValue
}
}
public extension String {
public func match(_ pattern: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count)) != nil
} catch {
return false
}
}
public func getSpecificStr(_ regex: String) -> String? {
do {
let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpression.Options.caseInsensitive)
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
if let match = matches.first {
let range = match.rangeAt(1)
if let swiftRange = rangeFromNSRange(range, forString: self) {
let result = self.substring(with: swiftRange)
return result
}
}
} catch {
// regex was bad!
}
return nil
}
}
| mit | 0cd1b9d6638671b714999fc050c97577 | 29.318182 | 152 | 0.542729 | 4.615917 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/Argo/Types/JSON.swift | 1 | 2312 | import Foundation
/// A type safe representation of JSON.
public enum JSON {
case object([String: JSON])
case array([JSON])
case string(String)
case number(NSNumber)
case bool(Bool)
case null
}
public extension JSON {
/**
Transform an `Any` instance into `JSON`.
This is used to move from a loosely typed object (like those returned from
`NSJSONSerialization`) to the strongly typed `JSON` tree structure.
- parameter json: A loosely typed object
*/
init(_ json: Any) {
switch json {
case let v as [Any]:
self = .array(v.map(JSON.init))
case let v as [String: Any]:
self = .object(v.map(JSON.init))
case let v as String:
self = .string(v)
case let v as NSNumber:
if v.isBool {
self = .bool(v.boolValue)
} else {
self = .number(v)
}
default:
self = .null
}
}
}
extension JSON: Decodable {
/**
Decode `JSON` into `Decoded<JSON>`.
This simply wraps the provided `JSON` in `.Success`. This is useful because
it means we can use `JSON` values with the `<|` family of operators to pull
out sub-keys.
- parameter json: The `JSON` value to decode
- returns: The provided `JSON` wrapped in `.Success`
*/
public static func decode(_ json: JSON) -> Decoded<JSON> {
return pure(json)
}
}
extension JSON: CustomStringConvertible {
public var description: String {
switch self {
case let .string(v): return "String(\(v))"
case let .number(v): return "Number(\(v))"
case let .bool(v): return "Bool(\(v))"
case let .array(a): return "Array(\(a.description))"
case let .object(o): return "Object(\(o.description))"
case .null: return "Null"
}
}
}
extension JSON: Equatable { }
public func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case let (.string(l), .string(r)): return l == r
case let (.number(l), .number(r)): return l == r
case let (.bool(l), .bool(r)): return l == r
case let (.array(l), .array(r)): return l == r
case let (.object(l), .object(r)): return l == r
case (.null, .null): return true
default: return false
}
}
/// MARK: Deprecations
extension JSON {
@available(*, deprecated, renamed: "init")
static func parse(_ json: Any) -> JSON {
return JSON(json)
}
}
| mit | 011ab2b62541ea3840840cc008825fec | 22.591837 | 79 | 0.612457 | 3.584496 | false | false | false | false |
PrashantMangukiya/SwiftPhotoGallery | SwiftPhotoGallery/SwiftPhotoGallery/SwiftyJSON.swift | 1 | 35518 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let error1 as NSError {
error.memory = error1
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/// Private object
private var _object: AnyObject = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError?
/// Object in JSON
public var object: AnyObject {
get {
return _object
}
set {
_object = newValue
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
case _ as NSString:
_type = .String
case _ as NSNull:
_type = .Null
case _ as [AnyObject]:
_type = .Array
case _ as [String : AnyObject]:
_type = .Dictionary
default:
_type = .Unknown
_object = NSNull()
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
public static var nullJSON: JSON { get { return JSON(NSNull()) } }
}
// MARK: - SequenceType
extension JSON: SequenceType{
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return (self.object as! [AnyObject]).isEmpty
case .Dictionary:
return (self.object as! [String : AnyObject]).isEmpty
default:
return false
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
get {
switch self.type {
case .Array:
return self.arrayValue.count
case .Dictionary:
return self.dictionaryValue.count
default:
return 0
}
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of this *sequence*.
*/
public func generate() -> AnyGenerator<(String, JSON)> {
switch self.type {
case .Array:
let array_ = object as! [AnyObject]
var generate_ = array_.generate()
var index_: Int = 0
return anyGenerator {
if let element_: AnyObject = generate_.next() {
return ("\(index_++)", JSON(element_))
} else {
return nil
}
}
case .Dictionary:
let dictionary_ = object as! [String : AnyObject]
var generate_ = dictionary_.generate()
return anyGenerator {
if let (key_, value_): (String, AnyObject) = generate_.next() {
return (key_, JSON(value_))
} else {
return nil
}
}
default:
return anyGenerator {
return nil
}
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol SubscriptType {}
extension Int: SubscriptType {}
extension String: SubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var errorResult_ = JSON.nullJSON
errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return errorResult_
}
let array_ = self.object as! [AnyObject]
if index >= 0 && index < array_.count {
return JSON(array_[index])
}
var errorResult_ = JSON.nullJSON
errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return errorResult_
}
set {
if self.type == .Array {
var array_ = self.object as! [AnyObject]
if array_.count > index {
array_[index] = newValue.object
self.object = array_
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var returnJSON = JSON.nullJSON
if self.type == .Dictionary {
if let object_: AnyObject = self.object[key] {
returnJSON = JSON(object_)
} else {
returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return returnJSON
}
set {
if self.type == .Dictionary {
var dictionary_ = self.object as! [String : AnyObject]
dictionary_[key] = newValue.object
self.object = dictionary_
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: SubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [SubscriptType]) -> JSON {
get {
if path.count == 0 {
return JSON.nullJSON
}
var next = self
for sub in path {
next = next[sub:sub]
}
return next
}
set {
switch path.count {
case 0: return
case 1: self[sub:path[0]] = newValue
default:
var last = newValue
var newPath = path
newPath.removeLast()
for sub in Array(path.reverse()) {
var previousLast = self[newPath]
previousLast[sub:sub] = last
last = previousLast
if newPath.count <= 1 {
break
}
newPath.removeLast()
}
self[sub:newPath[0]] = last
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: SubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var dictionary_ = [String : AnyObject]()
for (key_, value) in elements {
dictionary_[key_] = value
}
self.init(dictionary_)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return "\(data)"
//return NSString(data: data, encoding: NSUTF8StringEncoding)
//return NSString(data: data, encoding: encoding)
} catch _ {
return nil
}
case .String:
return (self.object as! String)
case .Number:
return (self.object as! NSNumber).stringValue
case .Bool:
return (self.object as! Bool).description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return (self.object as! [AnyObject]).map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.object as? [AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableArray(array: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] {
var result = [Key: NewValue](minimumCapacity:source.count)
for (key,value) in source {
result[key] = transform(value)
}
return result
}
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
get {
if self.type == .Dictionary {
return _map(self.object as! [String : AnyObject]){ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
get {
return self.dictionary ?? [:]
}
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.object as? [String : AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.object.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.object as? NSNumber
default:
return nil
}
}
set {
self.object = newValue?.copy() ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as! NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue.copy()
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return NSNull()
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON: Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) == (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) == (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) <= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) >= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) > (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) > (rhs.object as! String)
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) < (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) < (rhs.object as! String)
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
}
//MARK:- Unavailable
@available(*, unavailable, renamed="JSON")
public typealias JSONValue = JSON
extension JSON {
@available(*, unavailable, message="use 'init(_ object:AnyObject)' instead")
public init(object: AnyObject) {
self = JSON(object)
}
@available(*, unavailable, renamed="dictionaryObject")
public var dictionaryObjects: [String : AnyObject]? {
get { return self.dictionaryObject }
}
@available(*, unavailable, renamed="arrayObject")
public var arrayObjects: [AnyObject]? {
get { return self.arrayObject }
}
@available(*, unavailable, renamed="int8")
public var char: Int8? {
get {
return self.number?.charValue
}
}
@available(*, unavailable, renamed="int8Value")
public var charValue: Int8 {
get {
return self.numberValue.charValue
}
}
@available(*, unavailable, renamed="uInt8")
public var unsignedChar: UInt8? {
get{
return self.number?.unsignedCharValue
}
}
@available(*, unavailable, renamed="uInt8Value")
public var unsignedCharValue: UInt8 {
get{
return self.numberValue.unsignedCharValue
}
}
@available(*, unavailable, renamed="int16")
public var short: Int16? {
get{
return self.number?.shortValue
}
}
@available(*, unavailable, renamed="int16Value")
public var shortValue: Int16 {
get{
return self.numberValue.shortValue
}
}
@available(*, unavailable, renamed="uInt16")
public var unsignedShort: UInt16? {
get{
return self.number?.unsignedShortValue
}
}
@available(*, unavailable, renamed="uInt16Value")
public var unsignedShortValue: UInt16 {
get{
return self.numberValue.unsignedShortValue
}
}
@available(*, unavailable, renamed="int")
public var long: Int? {
get{
return self.number?.longValue
}
}
@available(*, unavailable, renamed="intValue")
public var longValue: Int {
get{
return self.numberValue.longValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedLong: UInt? {
get{
return self.number?.unsignedLongValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedLongValue: UInt {
get{
return self.numberValue.unsignedLongValue
}
}
@available(*, unavailable, renamed="int64")
public var longLong: Int64? {
get{
return self.number?.longLongValue
}
}
@available(*, unavailable, renamed="int64Value")
public var longLongValue: Int64 {
get{
return self.numberValue.longLongValue
}
}
@available(*, unavailable, renamed="uInt64")
public var unsignedLongLong: UInt64? {
get{
return self.number?.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="uInt64Value")
public var unsignedLongLongValue: UInt64 {
get{
return self.numberValue.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="int")
public var integer: Int? {
get {
return self.number?.integerValue
}
}
@available(*, unavailable, renamed="intValue")
public var integerValue: Int {
get {
return self.numberValue.integerValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedInteger: Int? {
get {
return self.number?.unsignedIntegerValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedIntegerValue: Int {
get {
return self.numberValue.unsignedIntegerValue
}
}
}
| mit | ff7a9afca0eb5064b619e4519c147cc6 | 25.486204 | 264 | 0.526212 | 4.727539 | false | false | false | false |
wangyaqing/LeetCode-swift | Solutions/1.twoSum.playground/Contents.swift | 1 | 388 | //: Playground - noun: a place where people can play
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var map = [Int: Int]()
for index in 0...nums.count-1 {
let num = nums[index]
let result = target - num
if let first = map[num] {
return [first, index]
} else {
map[result] = index
}
}
return []
}
| mit | 914f10910107e8bc8c2bcbb3c7f49d19 | 23.25 | 52 | 0.487113 | 3.660377 | false | false | false | false |
CanyFrog/HCComponent | HCSource/HCColor+HSBA.swift | 1 | 2455 | //
// HCColor+HSBA.swift
// HCFoundation
//
// Created by huangcong on 2017/3/10.
// Copyright © 2017年 com.foundation.HC. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: HSB Color Space
/*
HSV (色相hue, 饱和度saturation, 明度value),也称HSB (B指brightness)是艺术家们常用的,因为与加法减法混色的术语相比,使用色相,饱和度等概念描述色彩更自然直观。HSV是RGB色彩空间的一种变形,它的内容与色彩尺度与其出处——RGB色彩空间有密切联系
https://www.wikiwand.com/zh/HSL%E5%92%8CHSV%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4
*/
extension HCColor {
/// get color with HSB color space
///
/// - Parameters:
/// - hue: hue angleValue from 0 to 360
/// - saturation: 0 to 1
/// - brightness: 0 to 1
/// - alpha: 0 to 1 ,defaule 1
public convenience init(angleValue hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat = 1.0) {
self.init(hue: clip(hue, 0, 360)/360, saturation: clip(saturation, 0.0, 1.0), brightness: clip(brightness, 0.0, 1.0), alpha: clip(alpha, 0.0, 1.0))
}
// MARK: - Getting the HSB Components
/**
Returns the HSB (hue, saturation, brightness) components.
- returns: The HSB components as a tuple (h, s, b).
*/
public final func toHSBAComponents() -> (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat) {
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return (h: h, s: s, b: b, a: a)
}
#if os(iOS) || os(tvOS) || os(watchOS)
/**
The hue component as CGFloat between 0.0 to 1.0.
*/
public final var hueComponent: CGFloat {
return toHSBAComponents().h
}
/**
The saturation component as CGFloat between 0.0 to 1.0.
*/
public final var saturationComponent: CGFloat {
return toHSBAComponents().s
}
/**
The brightness component as CGFloat between 0.0 to 1.0.
*/
public final var brightnessComponent: CGFloat {
return toHSBAComponents().b
}
/**
The alpha component as CGFloat between 0.0 to 1.0.
*/
public final var hsbalphaComponent: CGFloat {
return toHSBAComponents().a
}
#endif
}
| mit | 7751bfb3ba76cce71fb5f0d662a8f774 | 27.375 | 155 | 0.605286 | 3.131034 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.